use of com.seleniumtests.customexception.CustomSeleniumTestsException in project seleniumRobot by bhecquet.
the class PageObject method selectNewWindow.
/**
* Selects the first unknown window. To use immediately after an action creates a new window or tab
* Each time we do a click, but just before it (selenium click, JS click or action click), we record the list of windows.
* I a new window or tab is displayed, we select it.
* @param waitMs wait for N milliseconds before raising error
* @return
*/
public final String selectNewWindow(int waitMs) {
// app test are not compatible with window
if (SeleniumTestsContextManager.getThreadContext().getTestType().family() == TestType.APP) {
throw new ScenarioException("Application are not compatible with Windows");
}
// Keep the name of the current window handle before switching
// sometimes, our action made window disappear
String mainWindowHandle;
try {
mainWindowHandle = driver.getWindowHandle();
} catch (Exception e) {
mainWindowHandle = "";
}
internalLogger.debug("Current handle: " + mainWindowHandle);
// wait for window to be displayed
Instant end = systemClock.instant().plusMillis(waitMs + 250L);
Set<String> handles = new TreeSet<>();
boolean found = false;
while (end.isAfter(systemClock.instant()) && !found) {
handles = driver.getWindowHandles();
internalLogger.debug("All handles: " + handles.toString());
for (String handle : handles) {
// we already know this handle
if (getCurrentHandles().contains(handle)) {
continue;
}
selectWindow(handle);
// wait for a valid address
String address = "";
Instant endLoad = systemClock.instant().plusMillis(5000);
while (address.isEmpty() && endLoad.isAfter(systemClock.instant())) {
address = driver.getCurrentUrl();
}
// TODO: reactivate feature
try {
// Point windowPosition = driver.manage().window().getPosition();
// org.openqa.selenium.interactions.Mouse mouse = ((HasInputDevices) driver).getMouse();
// mouse.click();
// Mouse mouse = new DesktopMouse();
// mouse.click(new DesktopScreenRegion(Math.max(0, windowPosition.x) + driver.manage().window().getSize().width / 2, Math.max(0, windowPosition.y) + 5, 2, 2).getCenter());
} catch (Exception e) {
internalLogger.warn("error while giving focus to window");
}
found = true;
break;
}
WaitHelper.waitForMilliSeconds(300);
}
// check window has changed
if (waitMs > 0 && mainWindowHandle.equals(driver.getWindowHandle())) {
throw new CustomSeleniumTestsException("new window has not been found. Handles: " + handles);
}
return mainWindowHandle;
}
use of com.seleniumtests.customexception.CustomSeleniumTestsException in project seleniumRobot by bhecquet.
the class CachedHtmlElement method findElements.
@Override
public List<WebElement> findElements(By by) {
List<WebElement> foundElements = new ArrayList<>();
if (by instanceof By.ById) {
Field field;
try {
field = By.ById.class.getDeclaredField("id");
field.setAccessible(true);
foundElements.add(new CachedHtmlElement(cachedElement.getElementById((String) field.get(by))));
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new CustomSeleniumTestsException(ERROR_PROBLEM_SEARCHING_BY_FIELD, e);
}
} else if (by instanceof By.ByTagName) {
Field field;
try {
field = By.ByTagName.class.getDeclaredField("tagName");
field.setAccessible(true);
foundElements.addAll(cachedElement.getElementsByTag((String) field.get(by)).stream().map(CachedHtmlElement::new).collect(Collectors.toList()));
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new CustomSeleniumTestsException(ERROR_PROBLEM_SEARCHING_BY_FIELD, e);
}
} else if (by instanceof By.ByClassName) {
Field field;
try {
field = By.ByClassName.class.getDeclaredField("className");
field.setAccessible(true);
foundElements.addAll(cachedElement.getElementsByClass((String) field.get(by)).stream().map(CachedHtmlElement::new).collect(Collectors.toList()));
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new CustomSeleniumTestsException(ERROR_PROBLEM_SEARCHING_BY_FIELD, e);
}
} else if (by instanceof By.ByName) {
Field field;
try {
field = By.ByName.class.getDeclaredField("name");
field.setAccessible(true);
foundElements.addAll(cachedElement.getElementsByAttributeValue("name", (String) field.get(by)).stream().map(CachedHtmlElement::new).collect(Collectors.toList()));
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new CustomSeleniumTestsException(ERROR_PROBLEM_SEARCHING_BY_FIELD, e);
}
} else if (by instanceof By.ByLinkText || by instanceof By.ByPartialLinkText) {
Field field;
try {
field = By.ByLinkText.class.getDeclaredField("linkText");
field.setAccessible(true);
for (Element el : cachedElement.getElementsByTag("a")) {
try {
el.getElementsContainingOwnText((String) field.get(by)).get(0);
foundElements.add(new CachedHtmlElement(el));
} catch (IndexOutOfBoundsException e) {
// nothing to do
}
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new CustomSeleniumTestsException(ERROR_PROBLEM_SEARCHING_BY_FIELD, e);
}
} else {
throw new NotImplementedException(String.format("%s is not implemented in cached element", by.getClass()));
}
return foundElements;
}
use of com.seleniumtests.customexception.CustomSeleniumTestsException in project seleniumRobot by bhecquet.
the class ElementInfo method updateInfo.
/**
* Update information by calling the real element.
* @param htmlElement
* @param driver
*/
public void updateInfo(HtmlElement htmlElement) {
if (htmlElement.getRealElement() == null) {
throw new CustomSeleniumTestsException(String.format("Updating element information [%s] is not possible if real element has not yet been searched", name));
}
String newText = htmlElement.getRealElement().getText();
// depending on drivers, rect may raise an error
Rectangle newRectangle;
try {
newRectangle = htmlElement.getRealElement().getRect();
} catch (WebDriverException e) {
Point location = htmlElement.getRealElement().getLocation();
Dimension size = htmlElement.getRealElement().getSize();
newRectangle = new Rectangle(location, size);
}
String newB64Image = "";
String newTagName = "";
Map<String, Object> newAttributes = new HashMap<>();
// only capture picture in FULL mode
if (SeleniumTestsContextManager.getThreadContext().getAdvancedElementSearch() == Mode.FULL) {
try {
BufferedImage fullImg = getScreenshot();
// Get the location of htmlElement on the page
Point point = newRectangle.getPoint();
// Get width and height of the element
int eleWidth = newRectangle.getWidth();
int eleHeight = newRectangle.getHeight();
Point scrollPosition = ((CustomEventFiringWebDriver) htmlElement.getDriver()).getScrollPosition();
// Crop the entire page screenshot to get only element screenshot. Keep 20 px around the picture
BufferedImage eleScreenshot = ImageProcessor.cropImage(fullImg, Math.max(0, point.getX() - scrollPosition.getX() - 20), Math.max(0, point.getY() - scrollPosition.getY() - 20), Math.min(eleWidth + 40, fullImg.getWidth()), Math.min(eleHeight + 40, fullImg.getHeight()));
// for debug purpose
/*File tmp = File.createTempFile("screenshot", ".png");
tmp.deleteOnExit();
ImageIO.write(eleScreenshot, "png", tmp);*/
newB64Image = ImageProcessor.toBase64(eleScreenshot);
} catch (Exception e) {
logger.error("Error taking element screenshot", e);
}
}
if (SeleniumTestsContextManager.isWebTest()) {
newTagName = htmlElement.getRealElement().getTagName();
newAttributes = (Map<String, Object>) ((JavascriptExecutor) htmlElement.getDriver()).executeScript(JAVASCRIPT_GET_ATTRIBUTES, htmlElement.getRealElement());
}
// record stability information (is the information stable over time or not)
totalSearch += 1;
textStability = newText.equals(text) ? textStability + 1 : 0;
tagStability = newTagName.equals(tagName) ? tagStability + 1 : 0;
rectangleStability = newRectangle.equals(new Rectangle(coordX, coordY, height, width)) ? rectangleStability + 1 : 0;
for (Entry<String, Object> entryAttr : newAttributes.entrySet()) {
// attribute was unknown
if (!attributes.containsKey(entryAttr.getKey()) || !attributesStability.containsKey(entryAttr.getKey())) {
attributesStability.put(entryAttr.getKey(), 0);
} else // attribute is known but changed
if (attributes.containsKey(entryAttr.getKey())) {
if (!attributes.get(entryAttr.getKey()).equals(newAttributes.get(entryAttr.getKey()))) {
attributesStability.put(entryAttr.getKey(), 0);
} else {
attributesStability.put(entryAttr.getKey(), attributesStability.get(entryAttr.getKey()) + 1);
}
}
}
// reset indicators for attributes that are not found anymore
for (Entry<String, Object> entryAttr : attributes.entrySet()) {
if (!newAttributes.containsKey(entryAttr.getKey())) {
attributesStability.put(entryAttr.getKey(), 0);
}
}
// TODO: image
b64ImageStability = 0;
text = newText;
coordX = newRectangle.x;
coordY = newRectangle.y;
width = newRectangle.width;
height = newRectangle.height;
b64Image = newB64Image;
tagName = newTagName;
attributes = newAttributes;
lastUpdate = LocalDateTime.now();
}
use of com.seleniumtests.customexception.CustomSeleniumTestsException in project seleniumRobot by bhecquet.
the class HtmlElement method findElement.
/**
* Finds the element using By type. Implicit Waits is built in createWebDriver()
* in WebUIDriver to handle dynamic element problem. This method is invoked
* before all the basic operations like click, sendKeys, getText, etc. Use
* waitForPresent to use Explicit Waits to deal with special element which needs
* long time to present.
*
* @param waitForVisibility wait for element to be visible
* @param makeVisible whether we try to make the element visible. Should
* be true except when trying to know if element is
* displayed
*/
public void findElement(boolean waitForVisibility, boolean makeVisible) {
// TODO:
// https://discuss.appium.io/t/how-can-i-scroll-to-an-element-in-appium-im-using-android-native-app/10618/14
// String DESTINATION_ELEMENT_TEXT= "KUBO";
// ((AndroidDriver) driver).findElementByAndroidUIAutomator("new
// UiScrollable(new UiSelector())
// .scrollIntoView(new UiSelector().text(DESTINATION_ELEMENT_TEXT))");
ElementInfo elementInfo = null;
// search element information. Do not stop if something goes wrong here
if (SeleniumTestsContextManager.getThreadContext().getAdvancedElementSearch() != ElementInfo.Mode.FALSE) {
try {
elementInfo = ElementInfo.getInstance(this);
} catch (Exception e) {
logger.info("Error getting element info");
}
}
// if a parent is defined, search for it before getting the sub element
setDriver(updateDriver());
if (parent != null) {
parent.findElement(false, false);
// inside a parent
if (by instanceof ByXPath) {
try {
Field xpathExpressionField = ByXPath.class.getDeclaredField("xpathExpression");
xpathExpressionField.setAccessible(true);
String xpath = (String) xpathExpressionField.get(by);
if (xpath.startsWith("//")) {
by = By.xpath("." + xpath);
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new CustomSeleniumTestsException(e);
}
}
setElement(findSeleniumElement(parent.getRealElementNoSearch(), elementInfo));
} else {
setElement(findSeleniumElement(getDriver(), elementInfo));
}
if (makeVisible) {
makeWebElementVisible(getRealElementNoSearch());
if (scrollToElementBeforeAction) {
((CustomEventFiringWebDriver) getDriver()).scrollToElement(getRealElementNoSearch(), OPTIMAL_SCROLLING);
}
}
// element
if (waitForVisibility && makeVisible) {
try {
new WebDriverWait(getDriver(), 1).until(ExpectedConditions.visibilityOf(getRealElementNoSearch()));
} catch (TimeoutException e) {
logger.error(String.format("Element %s has never been made visible", toString()));
}
}
// If we are here, element has been found, update elementInformation
if (elementInfo != null) {
try {
elementInfo.updateInfo(this);
elementInfo.exportToJsonFile(false, this);
} catch (Exception e) {
logger.warn("Error storing element information: " + e.getMessage());
}
}
}
Aggregations