Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.github.siwenyan.glue.CommonUiStepDefinition Maven / Gradle / Ivy
package com.github.siwenyan.glue;
import com.github.siwenyan.common.*;
import com.github.siwenyan.superglue.Login;
import com.github.siwenyan.superglue.SearchCriteria;
import com.github.siwenyan.web.*;
import com.github.siwenyan.web.ui.IReadable;
import com.github.siwenyan.web.ui.SlowBy;
import com.github.siwenyan.web.ui.UIComponentFactory;
import com.github.siwenyan.web.ui.UIComponentTable;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CommonUiStepDefinition {
private static final Logger log = Logger.getLogger(CommonUiStepDefinition.class.getName());
private ScenarioLogger scenarioLogger = null;
private Scenario scenario;
private String owner;
private WebDriver driver() throws Throwable {
return Login.login(scenario, null);
}
@Before
public void beforeScenario(Scenario scenario) throws Throwable {
log.warn("beforeScenario");
this.scenario = scenario;
this.owner = scenario.getId();
this.scenarioLogger = new ScenarioLogger(scenario, log, null);
LibPage.getInstance();
}
@After(order = 1)
public void afterScenario(Scenario scenario) throws Throwable {
log.warn("afterScenario");
if (scenario.isFailed()) {
WebUtils.demoBreakPoint(scenario, driver(), "Scenario failed.");
}
}
@And("^user verifies there are \"([^\"]*)\" elements with xpath \"([^\"]*)\"$")
public void userVerifiesThereAreElementsWithXpath(String count0, String xpath0) throws Throwable {
int count1 = Integer.parseInt(WhiteBoard.getInstance().resolve(owner, count0));
String xpath1 = WhiteBoard.getInstance().resolve(owner, xpath0);
Assert.assertEquals("Number of elements mismatch.",
count1, WebUtils.countElementsByXpath(driver(), xpath1));
}
@And("^user waits until there are \"([^\"]*)\" elements with xpath \"([^\"]*)\"$")
public void userWaitsUntilThereAreElementsWithXpath(String count0, String xpath0) throws Throwable {
int count1 = Integer.parseInt(WhiteBoard.getInstance().resolve(owner, count0));
String xpath1 = WhiteBoard.getInstance().resolve(owner, xpath0);
WebDriver d = driver();
Assert.assertTrue("Number of elements mismatch.",
WebUtils.waitUntil("There are " + count1 + " elements with xpath " + xpath1, 30, new IEvaluator() {
@Override
public boolean evaluate() throws Exception {
return count1 == WebUtils.countElementsByXpath(d, xpath1);
}
})
);
}
@Given("^user refreshes current page$")
public void userRefreshesCurrentPage() throws Throwable {
WebUtils.refreshPage(driver());
}
/**
* Add --End-- at the end of the dropdown options so code knows it's the end of the option list.
*
* @param pageName
* @param data
* @throws Throwable
*/
@Then("^user verifies on \"([^\"]*)\" below dropdown lists contain and contains only the options in below order$")
public void userVerifiesOnBelowDropdownListsContainsAndContainsOnlyTheOptionsInBelowOrder(String pageName, List> data) throws Throwable {
pageName = WhiteBoard.getInstance().resolve(owner, pageName);
int rows = data.size();
int cols = data.get(0).size();
for (int col = 0; col < cols; col++) {
List expectedOptions = new ArrayList<>(rows);
for (int row = 1; row < rows; row++) {
String option = data.get(row).get(col);
if (option != null && !option.equals("--End--")) {
expectedOptions.add(option);
} else break;
}
expectedOptions = WhiteBoard.getInstance().resolveStringList(owner, expectedOptions);
boolean hasExpectedOptions = null != expectedOptions && expectedOptions.size() > 0;
By locator = PageObjectUtils.getInstance().getLocator(pageName, data.get(0).get(col), driver());
IElementProvider ep = new ElementProviderOnSearchContext(driver(), locator);
boolean elementVisible = WebUtils.waitElementVisible(ep,1);
if (hasExpectedOptions) {
if (elementVisible) {
List actualOptions = WebUtils.getDropdownListOptions(ep);
WebUtils.demoBreakPoint(scenario, driver(), "Dropdown list for " + locator);
Assert.assertEquals("Options are different.", expectedOptions, actualOptions);
} else {
Assert.fail("Couldn't find element: " + locator);
}
} else {
if (elementVisible) {
Assert.fail("Missing expected options for element: " + locator);
} else {
scenarioLogger.warn("OK");
}
}
}
}
@And("^user verifies \"([^\"]*)\" looks like below layout$")
public void userVerifiesLooksLikeBelowLayout(String pageName, List> layout) throws Throwable {
//TODO: fix for Jenkins
// layout = WhiteBoard.getInstance().resolveListOfStringList(owner, layout);
// int rows = layout.size();
// int cols = layout.get(0).size();
//
// // left-right
// WebUtils.scrollTo(driver(), 0, 0);
// for (int row = 0; row < rows; row++) {
// By lastLocator = null;
// for (int col = 0; col < cols; col++) {
// String locatorName = layout.get(row).get(col);
// if (!StringTools.isEmpty(locatorName)) {
// By currentLocator = CommonPageObject.getLocator(pageName, locatorName);
// if (null != lastLocator) {
// scenarioLogger.warn("Checking: " + pageName + "." + locatorName);
// scenarioLogger.warn("left-right: " + lastLocator + "-" + currentLocator);
// Assert.assertTrue("Should be displayed in left-right.", LocationUtils.leftRightSameRow(driver(), lastLocator, currentLocator));
// Assert.assertFalse("Should NOT be displayed in up-down.", LocationUtils.upDownSameColumn(driver(), lastLocator, currentLocator));
// }
// lastLocator = currentLocator;
// scenarioLogger.warn("Last locator: " + pageName + "." + locatorName);
// }
// }
// }
//
// // up-down
// WebUtils.scrollTo(driver(), 0, 0);
// for (int col = 0; col < cols; col++) {
// By lastLocator = null;
// for (int row = 0; row < rows; row++) {
// String locatorName = layout.get(row).get(col);
// if (!StringTools.isEmpty(locatorName)) {
// By currentLocator = CommonPageObject.getLocator(pageName, locatorName);
// if (null != lastLocator) {
// scenarioLogger.warn("Checking: " + pageName + "." + locatorName);
// scenarioLogger.warn("up-down: " + lastLocator + "-" + currentLocator);
// Assert.assertFalse("Should NOT be displayed in left-right.", LocationUtils.leftRightSameRow(driver(), lastLocator, currentLocator));
// Assert.assertTrue("Should be displayed in up-down.", LocationUtils.upDownSameColumn(driver(), lastLocator, currentLocator));
// }
// lastLocator = currentLocator;
// scenarioLogger.warn("Last locator: " + pageName + "." + locatorName);
// }
// }
// }
//
// WebUtils.demoBreakPoint(scenario, driver(), pageName + " Layout");
}
@When("^user clicks \"([^\"]*)\" on \"([^\"]*)\"$")
public void userClicksOn(String locator, String pageName) throws Throwable {
By by = PageObjectUtils.getInstance().getLocator(pageName, locator);
WebUtils.click(new ElementProviderOnSearchContext(driver(), by));
Sys.sleep(2);
}
@When("^user clicks \"([^\"]*)\" for \"([^\"]*)\" on \"([^\"]*)\"$")
public void userClicksForOn(String locatorMethodName, String stringArgs, String pageName) throws Throwable {
stringArgs = WhiteBoard.getInstance().resolve(owner, stringArgs);
String[] args = stringArgs.split("\\s*,\\s*");
By by = PageObjectUtils.getInstance().getLocator(pageName, locatorMethodName, args);
WebUtils.click(new ElementProviderOnSearchContext(driver(), by));
}
@Given("^user adds below data on \"([^\"]*)\" and click \"([^\"]*)\"$")
public void userAddsBelowDataOnAndClick(String pageName, String saveButtonLocatorName, List> maps) throws Throwable {
maps = WhiteBoard.getInstance().resolve(owner, maps);
for (Map map : maps) {
for (String locatorName : map.keySet()) {
By by = PageObjectUtils.getInstance().getLocator(pageName, locatorName);
UIComponentFactory.asEditable(new ElementProviderOnSearchContext(driver(), by)).edit(map.get(locatorName));
}
WebUtils.demoBreakPoint(scenario, driver(), "Add Data");
By saveButtonLocator = PageObjectUtils.getInstance().getLocator(pageName, saveButtonLocatorName);
WebUtils.click(new ElementProviderOnSearchContext(driver(), saveButtonLocator));
WebUtils.demoBreakPoint(scenario, driver(), "Add Data completed");
}
}
@When("^user searches on \"([^\"]*)\" using below criteria and extract result as \"([^\"]*)\" with key header \"([^\"]*)\"$")
public void userSearchesOnUsingBelowCriteriaAndExtractResultAsWithKeyHeader(String searchablePageName, String prefix, String keyHeader, List> maps) throws Throwable {
prefix = WhiteBoard.getInstance().resolve(owner, prefix);
ISearchable searchable = PageObjectUtils.getInstance().newSearchable(searchablePageName, driver());
SearchCriteria searchCriteria = new SearchCriteria(scenario, driver());
searchCriteria.setCriteria(WhiteBoard.getInstance().resolve(owner, maps).get(0), searchable.getFilterTableXpath());
WebUtils.click(new ElementProviderOnSearchContext(driver(), searchable.getSearchButtonLocator()));
Sys.sleep(3);
WebUtils.extractGridToWhiteBoard(driver(), scenario, prefix, keyHeader, searchable.getResultTableXpath(), searchable.hasPagination(), false, true);
}
@And("^user verifies \"([^\"]*)\" is checked on \"([^\"]*)\"$")
public void userVerifiesIsSelectedOn(String elementName, String pageName) throws Throwable {
By by = PageObjectUtils.getInstance().getLocator(pageName, elementName);
Assert.assertTrue(WebUtils.isChecked(new ElementProviderOnSearchContext(driver(), by)));
}
@Then("^user verifies \"([^\"]*)\" is blank on \"([^\"]*)\"$")
public void userVerifiesIsBlankOn(String elementName, String pageName) throws Throwable {
By by = PageObjectUtils.getInstance().getLocator(pageName, elementName);
IReadable readable = UIComponentFactory.asReadable(new ElementProviderOnSearchContext(driver(), by));
Assert.assertTrue(StringTools.isEmpty((String) readable.read()));
}
@When("^user inputs \"([^\"]*)\" in \"([^\"]*)\"$")
public void userInputsIn(String value, String locatorString) throws Throwable {
WebDriver driver = driver();
final String value1 = WhiteBoard.getInstance().resolve(owner, value);
Retry retry = new Retry("Input " + value + " with field " + locatorString) {
@Override
protected void tryOnce() throws Exception {
WebElement el = WebUtils.slowFindElement(driver, locatorString, null).get();
if (null == el) {
Assert.fail("Couldn't find element: " + locatorString);
} else {
boolean success = UIComponentFactory.asEditable(new ElementProviderOnElement(driver, el)).edit(value1);
Assert.assertTrue("Couldn't input value " + value + " in element: " + locatorString, success);
}
}
};
Assert.assertTrue("Input fail.", retry.execute());
}
@And("^user clicks \"([^\"]*)\"$")
public void userClicks(String locatorString) throws Throwable {
locatorString = WhiteBoard.getInstance().resolve(owner, locatorString);
Assert.assertFalse(StringTools.isEmpty(locatorString));
WebDriver d = driver();
try {
IElementProvider ep = WebUtils.slowFindClickableElement(d, locatorString, null);
if (!WebUtils.click(ep)) {
throw new RuntimeException("Try clicking in another way.");
}
} catch (Exception e) {
By by = PageObjectUtils.getInstance().getLocator(locatorString, 10000);
Assert.assertTrue(WebUtils.click(new ElementProviderOnSearchContext(d, by)));
}
}
@And("^user clicks \"([^\"]*)\" until \"([^\"]*)\" is \"([^\"]*)\" if \"([^\"]*)\"$")
public void userClicksUntilIsIf(String clickLocator, String displayLocator0, String untilCriteria, String evaluationExpression) throws Throwable {
if (WhiteBoard.getInstance().evaluate(owner, evaluationExpression)) {
userClicksUntilIs(clickLocator, displayLocator0, untilCriteria);
}
}
@And("^user clicks \"([^\"]*)\" until \"([^\"]*)\" is \"([^\"]*)\"$")
public void userClicksUntilIs(String clickLocator, String displayLocator0, String untilCriteria) throws Throwable {
clickLocator = WhiteBoard.getInstance().resolve(owner, clickLocator);
String displayLocator = WhiteBoard.getInstance().resolve(owner, displayLocator0);
WebDriver d = driver();
IElementProvider epClick = new ElementProviderOnSearchContext(d, SlowBy.by(d, clickLocator, PageObjectUtils.getInstance(), null, null));
boolean success = WebUtils.clickUntil(epClick, new IEvaluator() {
@Override
public boolean evaluate() {
IElementProvider epDisplay = new ElementProviderOnSearchContext(d, SlowBy.by(d, displayLocator, PageObjectUtils.getInstance(), null, null));
boolean displayed = WebUtils.waitElementVisible(epDisplay, 1);
if ("displayed".equals(untilCriteria)) {
return displayed;
} else if ("not displayed".equals(untilCriteria)) {
return !displayed;
} else {
throw new AssertionError("Unknown until criteria: " + untilCriteria);
}
}
});
String msg = "user clicks " + clickLocator + " until " + displayLocator + " is " + untilCriteria;
WebUtils.demoBreakPoint(scenario, d, msg);
Assert.assertTrue(msg, success);
}
@And("^user clicks \"([^\"]*)\" and waits until \"([^\"]*)\" is \"([^\"]*)\"$")
public void userClicksAndWaitsUntilIs(String clickLocator, String displayLocator0, String untilCriteria) throws Throwable {
clickLocator = WhiteBoard.getInstance().resolve(owner, clickLocator);
String displayLocator = WhiteBoard.getInstance().resolve(owner, displayLocator0);
WebDriver d = driver();
IEvaluator condition = new IEvaluator() {
@Override
public boolean evaluate() {
IElementProvider epDisplay = new ElementProviderOnSearchContext(d, SlowBy.by(d, displayLocator, PageObjectUtils.getInstance(), null, null));
boolean displayed = WebUtils.waitElementVisible(epDisplay, 1);
if ("displayed".equals(untilCriteria)) {
return displayed;
} else if ("not displayed".equals(untilCriteria)) {
return !displayed;
} else {
throw new AssertionError("Unknown until criteria: " + untilCriteria);
}
}
};
if (WebUtils.waitUntil("Check if already " + untilCriteria, 5, condition)) {
scenarioLogger.warn("Already " + untilCriteria);
return;
}
By clickBy = SlowBy.by(d, clickLocator, PageObjectUtils.getInstance(), null, null);
Assert.assertTrue(WebUtils.click(new ElementProviderOnSearchContext(d, clickBy)));
boolean success = WebUtils.waitUntil("Wait until " + untilCriteria, 60, condition);
String msg = "user clicks " + clickLocator + " and wait until " + displayLocator + " is " + untilCriteria;
Assert.assertTrue(msg, success);
}
@And("^user waits until \"([^\"]*)\" is \"([^\"]*)\" within \"([^\"]*)\" seconds if \"([^\"]*)\"$")
public void userWaitsUntilIsWithinSecondsIf(String displayLocator0, String untilCriteria, int withinSeconds, String evaluationExpression) throws Throwable {
if (WhiteBoard.getInstance().evaluate(owner, evaluationExpression)) {
userWaitsUntilIsWithinSeconds(displayLocator0, untilCriteria, withinSeconds);
}
}
@And("^user waits until \"([^\"]*)\" is \"([^\"]*)\"$")
public void userWaitsUntilIs(String displayLocator0, String untilCriteria) throws Throwable {
userWaitsUntilIsWithinSeconds(displayLocator0, untilCriteria, 15);
}
@And("^user waits until \"([^\"]*)\" is \"([^\"]*)\" within \"([^\"]*)\" seconds$")
public void userWaitsUntilIsWithinSeconds(String displayLocator0, String untilCriteria, int withinSeconds) throws Throwable {
String displayLocator = WhiteBoard.getInstance().resolve(owner, displayLocator0);
WebDriver d = driver();
IEvaluator condition = new IEvaluator() {
@Override
public boolean evaluate() {
By locator = null;
try {
locator = PageObjectUtils.getInstance().getLocator(displayLocator);
} catch (Exception e) {
log.warn("Locator: " + displayLocator + " might be invalid. [" + e.getMessage() + "]");
// do nothing
}
if (null == locator) {
locator = SlowBy.by(d, displayLocator, null, null, null);
}
boolean displayed = WebUtils.waitElementVisible(new ElementProviderOnSearchContext(d, locator), 1);
if ("displayed".equals(untilCriteria)) {
return displayed;
} else if ("not displayed".equals(untilCriteria)) {
return !displayed;
} else {
throw new AssertionError("Unknown until criteria: " + untilCriteria);
}
}
};
String msg = "user waits until [" + displayLocator + "] " + untilCriteria;
boolean success = WebUtils.waitUntil(msg, withinSeconds, condition);
WebUtils.demoBreakPoint(scenario, d, msg);
Assert.assertTrue("Failed: " + msg, success);
}
@When("^table \"([^\"]*)\" is extracted as maps with prefix \"([^\"]*)\" and key header \"([^\"]*)\"$")
public void tableIsExtractedAsMapsWithPrefix(String tableXpath, String prefix, String keyHeader) throws Throwable {
prefix = WhiteBoard.getInstance().resolve(owner, prefix);
tableXpath = WhiteBoard.getInstance().resolve(owner, tableXpath);
try {
tableXpath = PageObjectUtils.getInstance().getXpath(tableXpath);
} catch (InvalidLocatorException e) {
// do nothing
}
WebUtils.extractGridToWhiteBoard(driver(), scenario, prefix, keyHeader, tableXpath, false, false, true);
WebUtils.demoBreakPoint(scenario, driver(), tableXpath + " is extracted with prefix " + prefix + " and key header " + keyHeader);
}
@When("^transposed table \"([^\"]*)\" is extracted as maps with prefix \"([^\"]*)\" and key header \"([^\"]*)\"$")
public void transposedTableIsExtractedAsMapsWithPrefix(String tableXpath, String prefix, String keyHeader) throws Throwable {
WebDriver d = driver();
prefix = WhiteBoard.getInstance().resolve(owner, prefix);
tableXpath = WhiteBoard.getInstance().resolve(owner, tableXpath);
try {
tableXpath = PageObjectUtils.getInstance().getXpath(tableXpath);
} catch (InvalidLocatorException e) {
// do nothing
}
Assert.assertFalse(StringTools.isEmpty(tableXpath));
WebUtils.extractGridToWhiteBoard(d, scenario, prefix, keyHeader, tableXpath, false, true, true);
WebUtils.demoBreakPoint(scenario, d, tableXpath + " is extracted with prefix " + prefix + " and key header " + keyHeader);
}
@Then("^user verifies \"([^\"]*)\" is \"([^\"]*)\" pixels beneath \"([^\"]*)\" on \"([^\"]*)\"$")
public void userVerifiesIsPixelsBeneathOn(String subjectName, String pixels, String referenceName, String pageName) throws Throwable {
By subjectLocator = PageObjectUtils.getInstance().getLocator(pageName, subjectName);
By referenceLocator = PageObjectUtils.getInstance().getLocator(pageName, referenceName);
String[] p = pixels.split("to", 2);
int from = Integer.parseInt(p[0].trim());
int to = Integer.parseInt(p[1].trim());
int actual = LocationUtils.verticalDistanceInPixels(driver(), referenceLocator, subjectLocator);
WebUtils.demoBreakPoint(scenario, driver(), subjectName + " is " + pixels + " pixels beneath " + referenceName);
Assert.assertTrue(pixels, actual >= from && actual <= to);
}
@And("^user verifies content of \"([^\"]*)\" on page \"([^\"]*)\" matches \"([^\"]*)\"$")
public void userVerifiesContentOfOnPageMatches(String elementName, String pageName, String expectedContent) throws Throwable {
By by = PageObjectUtils.getInstance().getLocator(pageName, elementName);
if (null == by) {
String locatorExpression = "${pages_" + pageName + "." + elementName + "}";
by = By.xpath(WhiteBoard.getInstance().resolve(owner, locatorExpression));
}
String actualContent = "";
WebDriver d = driver();
IElementProvider ep = new ElementProviderOnSearchContext(d, by);
if (WebUtils.waitElementVisible(ep, 1)) {
actualContent = WebUtils.simpleContent(ep);
}
expectedContent = WhiteBoard.getInstance().resolve(owner, expectedContent);
scenarioLogger.warn("Expected content: [" + expectedContent + "]");
scenarioLogger.warn(" Actual content: [" + actualContent + "]");
Assert.assertTrue(expectedContent.equals(actualContent) || actualContent.matches(expectedContent));
}
@And("^user verifies content of \"([^\"]*)\" on page \"([^\"]*)\" contains \"([^\"]*)\"$")
public void userVerifiesContentOfOnPageContains(String elementName, String pageName, String expectedContent) throws Throwable {
By by = PageObjectUtils.getInstance().getLocator(pageName, elementName);
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
String actualContent = WebUtils.simpleContent(ep);
expectedContent = WhiteBoard.getInstance().resolve(owner, expectedContent);
Assert.assertTrue("", actualContent.contains(expectedContent));
}
@Then("^user verifies map \"([^\"]*)\" \"([^\"]*)\" \"([^\"]*)\"$")
public void userVerifiesMap(String mapName, String evaluation, String targetOption) throws Throwable {
WebUtils.demoBreakPoint(scenario, driver(), "user verifies map " + mapName + " " + evaluation + " " + targetOption);
Map map = WhiteBoard.getInstance().getMap(owner, mapName);
targetOption = WhiteBoard.getInstance().resolve(owner, targetOption);
switch (evaluation) {
case "contains value":
Assert.assertTrue(map.containsValue(targetOption));
break;
case "does not contain value":
Assert.assertTrue(!map.containsValue(targetOption));
break;
default:
Assert.fail("Unsupported evaluation: " + evaluation);
}
}
@Then("^user should see message \"([^\"]*)\"$")
public void userShouldSeeMessage(String expectedValue) throws Throwable {
String note = "user should see message '" + expectedValue + "'";
WebUtils.demoBreakPoint(scenario, driver(), note);
IElementProvider ep = new ElementProviderOnSearchContext(driver(), By.xpath("//*[text()='" + expectedValue + "']"));
Assert.assertTrue(note, WebUtils.waitElementVisible(ep, 60));
}
@When("^is clickable \"([^\"]*)\" for \"([^\"]*)\" on \"([^\"]*)\"$")
public void isLinkClickable(String locatorMethodName, String stringArgs, String pageName) throws Throwable {
stringArgs = WhiteBoard.getInstance().resolve(owner, stringArgs);
String[] args = stringArgs.split("\\s*,\\s*");
By by = PageObjectUtils.getInstance().getLocator(pageName, locatorMethodName, args);
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
boolean click = WebUtils.waitElementVisible(ep, 60);
Assert.assertFalse(click);
}
@And("^grid \"([^\"]*)\" with \"([^\"]*)\" is extracted as \"([^\"]*)\"$")
public void searchResultIsExtractedAsFromTableWithXpath(String tableXpath, String with, String name) throws Throwable {
tableXpath = WhiteBoard.getInstance().resolve(owner, tableXpath);
if (StringTools.isEmpty(tableXpath)) {
Assert.fail("Missing tableXpath: " + tableXpath);
}
WebUtils.demoBreakPoint(scenario, driver(), "Extracting " + tableXpath + " as " + name);
with = WhiteBoard.getInstance().resolve(owner, with);
Map map = DataTableTools.asMap(with);
String layout = map.get("layout");
if ("singleRecordTable".equals(layout)) {
List> lists = new UIComponentTable(new ElementProviderOnSearchContext(driver(), By.xpath(tableXpath))).read();
Map singleRecord = new LinkedHashMap<>();
List lastRow = lists.get(0);
for (int i = 1; i < lists.size(); i++) {
List currRow = lists.get(i);
if (currRow.size() == lastRow.size()) {
for (int j = 0; j < currRow.size(); j++) {
String key = lastRow.get(j);
if (singleRecord.containsKey(key)) {
key += 2;
}
singleRecord.put(key, currRow.get(j));
}
if (i < lists.size() - 1) {
lastRow = lists.get(++i);
}
} else {
lastRow = currRow;
}
}
WhiteBoard.getInstance().putMap(owner, name, singleRecord);
} else if ("transposedTable".equals(layout)) {
Map transposedTable = WebUtils.transposedTableAsMaps(driver(), tableXpath, 30).get(0);
WhiteBoard.getInstance().putMap(owner, name, transposedTable);
} else {
String keyHeader = map.get("keyHeader");
if (StringTools.isEmpty(keyHeader)) {
keyHeader = "ROW_NUMBER";
}
boolean hasPagination = false;
if (Boolean.parseBoolean(map.get("hasPagination"))) {
hasPagination = true;
}
WebUtils.extractGridToWhiteBoard(driver(), scenario, name, keyHeader, tableXpath, hasPagination, false, true);
}
}
@Then("^user should see NO \"([^\"]*)\" for \"([^\"]*)\" on \"([^\"]*)\"$")
public void userShouldSeeNOForOn(String locatorMethodName, String stringArgs, String pageName) throws Throwable {
stringArgs = WhiteBoard.getInstance().resolve(owner, stringArgs);
String[] args = stringArgs.split("\\s*,\\s*");
By by = PageObjectUtils.getInstance().getLocator(pageName, locatorMethodName, args);
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
Assert.assertFalse(WebUtils.waitElementVisible(ep, 10));
}
@Then("^user verifies element \"([^\"]*)\" on \"([^\"]*)\" \"([^\"]*)\" values in \"([^\"]*)\"$")
public void userVerifiesElementOnValuesIn(String locatorName, String pageName, String verb, String listName) throws Throwable {
By by = PageObjectUtils.getInstance().getLocator(pageName, locatorName);
List list = WhiteBoard.getInstance().getList(owner, listName);
for (String target : list) {
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
boolean success = UIComponentFactory.asEditable(ep).edit(target);
WebUtils.demoBreakPoint(scenario, driver(), "target=" + target);
switch (verb) {
case "accepts":
Assert.assertTrue(success);
break;
case "does not accept":
Assert.assertFalse(success);
break;
default:
Assert.fail("Unknown verb: " + verb);
}
}
}
@And("^column \"([^\"]*)\" is extracted as list \"([^\"]*)\" from grid \"([^\"]*)\"$")
public void columnIsExtractedAsListFromGrid(String columnName, String listName, String tableXpathOrExpression) throws Throwable {
String xpath = null;
try {
xpath = PageObjectUtils.getInstance().getXpath(tableXpathOrExpression);
} catch (InvalidLocatorException e) {
xpath = tableXpathOrExpression;
}
List list = WebUtils.tableColumnAsList(driver(), xpath, columnName);
WhiteBoard.getInstance().putList(owner, listName, list);
WebUtils.demoBreakPoint(scenario, driver(), "column " + columnName + " is extracted as list " + listName + " from grid " + xpath);
}
@Then("^user validates \"([^\"]*)\" is \"([^\"]*)\" on \"([^\"]*)\"$")
public void userValidatesIsOn(String locatorName, String verb, String pageName) throws Throwable {
WebDriver d = driver();
By by = null;
String xpath = "${" + pageName + "." + locatorName + "}";
xpath = WhiteBoard.getInstance().resolve(owner, xpath);
if (!StringTools.isEmpty(xpath) && WebUtils.waitElementVisible(new ElementProviderOnSearchContext(d, By.xpath(xpath)), 1)) {
by = By.xpath(xpath);
} else {
by = PageObjectUtils.getInstance().getLocator(pageName, locatorName);
}
WebUtils.demoBreakPoint(scenario, d, "userValidatesIsOn()");
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
switch (verb.trim().toLowerCase()) {
case "displayed":
Assert.assertTrue(WebUtils.waitElementVisible(ep, 1));
break;
case "not displayed":
Assert.assertFalse(WebUtils.waitElementVisible(ep, 1));
break;
case "enabled":
Assert.assertTrue(WebUtils.isEnabled(ep));
break;
case "disabled":
Assert.assertFalse(WebUtils.isEnabled(ep));
break;
default:
Assert.fail("Unknown verb: " + verb);
}
}
@Then("^user validates \"([^\"]*)\" for \"([^\"]*)\" is \"([^\"]*)\" on \"([^\"]*)\"$")
public void userValidatesForIsOn(String locatorName, String args, String verb, String pageName) throws Throwable {
args = WhiteBoard.getInstance().resolve(owner, args);
By by = PageObjectUtils.getInstance().getLocator(pageName, locatorName, args.split(">"));
WebDriver d = driver();
WebUtils.demoBreakPoint(scenario, d, "userValidatesForIsOn()");
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
switch (verb.trim().toLowerCase()) {
case "displayed":
Assert.assertTrue(WebUtils.waitElementVisible(ep, 1));
break;
case "not displayed":
Assert.assertFalse(WebUtils.waitElementVisible(ep, 1));
break;
default:
Assert.fail("Unknown verb: " + verb);
}
}
@When("^user switches to the new browser tab$")
public void userSwitchesToTheNewBrowserTab() throws Throwable {
WebDriver d = driver();
ArrayList tabs = new ArrayList(d.getWindowHandles());
if (1 == tabs.size()) {
Retry retry = new Retry("Retry waiting for new tab") {
@Override
protected void tryOnce() throws Exception {
tabs.clear();
tabs.addAll(d.getWindowHandles());
}
@Override
protected boolean until() throws Exception {
return tabs.size() > 1;
}
};
Assert.assertTrue("Only one tab found.", retry.execute());
}
d.switchTo().window(tabs.get(tabs.size() - 1));
}
@Then("^user validates content of \"([^\"]*)\" matches \"([^\"]*)\"$")
public void userValidatesContentOfMatches(String locator, String expectedContentRegex) throws Throwable {
WebDriver driver = driver();
WebElement el = WebUtils.slowFindElement(driver, locator, null).get();
if (null == el) {
List elContainer = new ArrayList<>(1);
Retry retry = new Retry("Retry waiting for element " + locator) {
@Override
protected void tryOnce() throws Exception {
WebElement el = WebUtils.slowFindElement(driver, locator, null).get();
if (null != el) {
elContainer.clear();
elContainer.add(el);
}
}
@Override
protected boolean until() throws Exception {
return 1 == elContainer.size();
}
};
Assert.assertTrue(retry.execute());
el = elContainer.get(0);
}
String actualContent = WebUtils.simpleContent(new ElementProviderOnElement(driver, el));
WebUtils.demoBreakPoint(scenario, driver, "user validates content of \"" + locator + "\" matches \"" + expectedContentRegex + "\"");
Assert.assertTrue(actualContent.matches(expectedContentRegex));
}
@And("^user closes the current tab$")
public void userClosesTheCurrentTab() throws Throwable {
WebUtils.closeCurrentTab(Login.getLastAccessedLogin(scenario).driver());
}
@Given("^user inputs below data by labels$")
public void userInputsBelowDataByLabels(List> data0) throws Throwable {
List> data1 = WhiteBoard.getInstance().resolveListOfStringList(owner, data0);
Assert.assertTrue(WebUtils.inputAllByLabels(driver(), data1, null));
WebUtils.demoBreakPoint(scenario, driver(), "Input completed: " + data1.toString());
}
@Given("^user inputs below data by labels within \"([^\"]*)\" if \"([^\"]*)\"$")
public void userInputsBelowDataByLabelsIf(String parentXpath, String evaluationExpression, List> data0) throws Throwable {
if (WhiteBoard.getInstance().evaluate(owner, evaluationExpression)) {
userInputsBelowDataByLabels(parentXpath, data0);
}
}
@Given("^user inputs below data by labels within \"([^\"]*)\"$")
public void userInputsBelowDataByLabels(String parentXpath, List> data0) throws Throwable {
parentXpath = WhiteBoard.getInstance().resolve(owner, parentXpath);
List> data1 = WhiteBoard.getInstance().resolveListOfStringList(owner, data0);
Assert.assertTrue(WebUtils.inputAllByLabels(driver(), data1, parentXpath));
WebUtils.demoBreakPoint(scenario, driver(), "Input completed: " + data1.toString());
}
@Given("^user inputs below data by labels within \"([^\"]*)\" and save by clicking \"([^\"]*)\"$")
public void userInputsBelowDataByLabelsAndSaveByClicking(String parentXpath, String saveLocator, List> data0) throws Throwable {
parentXpath = WhiteBoard.getInstance().resolve(owner, parentXpath);
List> data1 = WhiteBoard.getInstance().resolveListOfStringList(owner, data0);
Assert.assertTrue(WebUtils.inputAllByLabels(driver(), data1, parentXpath));
WebUtils.demoBreakPoint(scenario, driver(), "Input completed: " + data1.toString());
}
@Then("^user cannot input below data by labels within \"([^\"]*)\"$")
public void userCannotInputBelowDataByLabels(String parentXpath, List> data0) throws Throwable {
parentXpath = WhiteBoard.getInstance().resolve(owner, parentXpath);
List> data1 = WhiteBoard.getInstance().resolveListOfStringList(owner, data0);
Assert.assertFalse(WebUtils.inputAllByLabels(driver(), data1, parentXpath));
WebUtils.demoBreakPoint(scenario, driver(), "Input completed: " + data1.toString());
}
/**
* Writing message and screenshot to cucumber report
*
* @param message
*/
@Then("^take note \"([^\"]*)\" with screenshot$")
public void takeNoteWithScreenshot(String message) throws Throwable {
message = WhiteBoard.getInstance().resolve(owner, message);
WebUtils.demoBreakPoint(scenario, driver(), message);
}
@Given("^current url is stored as \"([^\"]*)\"$")
public void currentUrlIsStoredAs(String urlName) throws Throwable {
WhiteBoard.getInstance().putString(owner, urlName, Login.getLastAccessedLogin(scenario).driver().getCurrentUrl());
}
@When("^user inputs \"([^\"]*)\" in \"([^\"]*)\" on \"([^\"]*)\"$")
public void userInputsInOn(String value, String locatorName, String pageName) throws Throwable {
By by = PageObjectUtils.getInstance().getLocator(pageName, locatorName);
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
boolean success = UIComponentFactory.asEditable(ep).edit(WhiteBoard.getInstance().resolve(owner, value));
Assert.assertTrue("Input failed.", success);
}
@And("^user clicks \"([^\"]*)\" button$")
public void userClicksButton(String buttonIdentifier) throws Throwable {
By by = SlowBy.by(driver(), buttonIdentifier, null, null, null);
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
boolean success = WebUtils.click(ep);
Assert.assertTrue("Click failed.", success);
}
@And("^user verifies \"([^\"]*)\" on page \"([^\"]*)\" is \"([^\"]*)\"$")
public void userVerifiesOnPageIs(String locatorName, String pageName, String evaluation) throws Throwable {
By by = PageObjectUtils.getInstance().getLocator(pageName, locatorName);
IElementProvider ep = new ElementProviderOnSearchContext(driver(), by);
switch (evaluation.toLowerCase()) {
case "checked":
Assert.assertTrue(WebUtils.isChecked(ep));
break;
case "unchecked":
Assert.assertFalse(WebUtils.isChecked(ep));
break;
case "displayed":
Assert.assertTrue(WebUtils.waitElementVisible(ep, 1));
break;
case "not displayed":
Assert.assertFalse(WebUtils.waitElementVisible(ep, 1));
break;
default:
Assert.fail("Unsupported evaluation: " + evaluation);
}
}
}