How to use setElement method of com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement class

Best Carina code snippet using com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement.setElement

Source:ExtendedWebElement.java Github

copy

Full Screen

...160 throw new RuntimeException("Unable to identify element using By: " + by.toString());161 }162 return staleElement;163 }164 public void setElement(WebElement element) {165 this.element = element;166 }167 public String getName() {168 return name != null ? name : String.format(" (%s)", by);169 }170 public String getNameWithLocator() {171 return by != null ? name + String.format(" (%s)", by) : name + " (n/a)";172 }173 public void setName(String name) {174 this.name = name;175 }176 public String getText() {177 String text = null;178 try {179 text = findElement(EXPLICIT_TIMEOUT).getText();180 } catch (StaleElementReferenceException e) {181 LOGGER.debug(e.getMessage(), e.getCause());182 element = findStaleElement();183 text = element.getText();184 }185 return text;186 }187 public String getAttribute(String attributeName) {188 String attribute = null;189 try {190 attribute = findElement(EXPLICIT_TIMEOUT).getAttribute(attributeName);191 } catch (StaleElementReferenceException e) {192 LOGGER.debug(e.getMessage(), e.getCause());193 element = findStaleElement();194 attribute = element.getAttribute(attributeName);195 }196 return attribute;197 }198 public By getBy() {199 return by;200 }201 public void setBy(By by) {202 this.by = by;203 }204 @Override205 public String toString() {206 return name;207 }208 /**209 * Clicks on element.210 */211 public void click() {212 click(EXPLICIT_TIMEOUT);213 }214 /**215 * Clicks on element.216 *217 * @param timeout to wait218 */219 public void click(long timeout) {220 captureElements();221 clickSafe(timeout, true);222 String msg = Messager.ELEMENT_CLICKED.info(getName());223 summary.log(msg);224 try {225 Screenshot.capture(getDriver(), msg);226 } catch (Exception e) {227 LOGGER.info(e.getMessage());228 }229 }230 /**231 * Double Clicks on element.232 */233 public void doubleClick() {234 doubleClickSafe(true);235 String msg = Messager.ELEMENT_DOUBLE_CLICKED.info(getName());236 summary.log(msg);237 try {238 Screenshot.capture(getDriver(), msg);239 } catch (Exception e) {240 LOGGER.info(e.getMessage());241 }242 }243 /**244 * Safe doubleClick on element, used to reduce any problems with that action.245 *246 * @param startTimer Start time247 */248 private void doubleClickSafe(boolean startTimer) {249 WebDriver drv = getDriver();250 Actions action = new Actions(drv);251 if (startTimer) {252 timer = System.currentTimeMillis();253 }254 try {255 element = findElement(EXPLICIT_TIMEOUT);256 action.moveToElement(element).doubleClick(element).build().perform();257 } catch (UnhandledAlertException e) {258 LOGGER.debug(e.getMessage(), e.getCause());259 drv.switchTo().alert().accept();260 } catch (StaleElementReferenceException e) {261 LOGGER.debug(e.getMessage(), e.getCause());262 element = findStaleElement();263 } catch (Exception e) {264 LOGGER.debug(e.getMessage(), e.getCause());265 if (e.getMessage().contains("Element is not clickable")) {266 scrollTo();267 }268 pause((double) RETRY_TIME / 1000);269 if (System.currentTimeMillis() - timer < EXPLICIT_TIMEOUT * 1000) {270 doubleClickSafe(false);271 } else {272 String msg = Messager.ELEMENT_NOT_DOUBLE_CLICKED.error(getNameWithLocator());273 summary.log(msg);274 throw new RuntimeException(msg, e);275 }276 }277 }278 /**279 * Mouse Right click to element.280 *281 * @return boolean true if there is no errors.282 */283 public boolean rightClick() {284 boolean res = false;285 String msg = "Right Click";286 try {287 WebDriver drv = getDriver();288 Actions action = new Actions(drv);289 element = findElement(EXPLICIT_TIMEOUT);290 action.moveToElement(element).contextClick(element).build().perform();291 msg = Messager.ELEMENT_RIGHT_CLICKED.info(getName());292 summary.log(msg);293 res = true;294 } catch (Exception e) {295 msg = Messager.ELEMENT_NOT_RIGHT_CLICKED.info(getName());296 summary.log(msg);297 LOGGER.error(e.getMessage());298 }299 try {300 Screenshot.capture(getDriver(), msg);301 } catch (Exception e) {302 LOGGER.info(e.getMessage());303 }304 return res;305 }306 /**307 * Click Hidden Element.308 * useful when element present in DOM but actually is not visible.309 * And can't be clicked by standard click.310 *311 * @return boolean true if there is no errors.312 */313 public boolean clickHiddenElement() {314 String msg = "Hidden Element Click";315 boolean res = false;316 try {317 WebElement elem = findElement(EXPLICIT_TIMEOUT);318 JavascriptExecutor executor = (JavascriptExecutor) getDriver();319 executor.executeScript("arguments[0].click();", elem);320 msg = Messager.HIDDEN_ELEMENT_CLICKED.info(getName());321 summary.log(msg);322 res = true;323 } catch (Exception e) {324 msg = Messager.HIDDEN_ELEMENT_NOT_CLICKED.info(getName());325 summary.log(msg);326 LOGGER.error(e.getMessage());327 }328 try {329 Screenshot.capture(getDriver(), msg);330 } catch (Exception e) {331 LOGGER.info(e.getMessage());332 }333 return res;334 }335 /**336 * Check that element present.337 *338 * @return element existence status.339 */340 public boolean isElementPresent() {341 return isElementPresent(EXPLICIT_TIMEOUT);342 }343 /**344 * Check that element present within specified timeout.345 *346 * @param timeout - timeout.347 * @return element existence status.348 */349 public boolean isElementPresent(long timeout) {350 boolean result;351 if (timeout <= 0) {352 LOGGER.warn("Timeout should be bigger than 0.");353 timeout = 1;354 }355 356 final long finalTimeout = timeout;357 final WebDriver drv = getDriver();358 setImplicitTimeout(1);359 wait = new WebDriverWait(drv, timeout, RETRY_TIME);360 try {361 wait.until((Function<WebDriver, Object>) dr -> findElement(finalTimeout).isDisplayed());362 result = true;363 } catch (Exception e) {364 LOGGER.debug(e.getMessage(), e.getCause());365 result = false;366 }367 setImplicitTimeout();368 return result;369 }370 /**371 * Check that element not present within specified timeout.372 *373 * @param timeout - timeout.374 * @return element existence status.375 */376 public boolean isElementNotPresent(long timeout) {377 return !isElementPresent(timeout);378 }379 /**380 * Check that element with text present.381 *382 * @param text of element to check.383 * @return element with text existence status.384 */385 public boolean isElementWithTextPresent(final String text) {386 return isElementWithTextPresent(text, EXPLICIT_TIMEOUT);387 }388 public boolean isElementWithTextPresent(final String text, long timeout) {389 boolean result;390 final String decryptedText = cryptoTool.decryptByPattern(text, CRYPTO_PATTERN);391 wait = new WebDriverWait(getDriver(), timeout, RETRY_TIME);392 try {393 wait.until((Function<WebDriver, Object>) dr -> {394 try {395 element = findElement(timeout);396 return element.isDisplayed() && element.getText().contains(decryptedText);397 } catch (Exception e) {398 LOGGER.debug(e.getMessage(), e.getCause());399 return false;400 }401 });402 result = true;403 summary.log(Messager.ELEMENT_WITH_TEXT_PRESENT.info(getName(), text));404 } catch (Exception e) {405 LOGGER.debug(e.getMessage(), e.getCause());406 result = false;407 summary.log(Messager.ELEMENT_WITH_TEXT_NOT_PRESENT.error(getNameWithLocator(), text));408 }409 return result;410 }411 public boolean clickIfPresent() {412 return clickIfPresent(EXPLICIT_TIMEOUT);413 }414 public boolean clickIfPresent(long timeout) {415 boolean result;416 WebDriver drv = getDriver();417 setImplicitTimeout(1);418 wait = new WebDriverWait(drv, timeout, RETRY_TIME);419 try {420 wait.until((Function<WebDriver, Object>) dr -> findElement(timeout).isDisplayed());421 captureElements();422 element.click();423 String msg = Messager.ELEMENT_CLICKED.info(getName());424 summary.log(msg);425 result = true;426 } catch (Exception e) {427 LOGGER.debug(e.getMessage(), e.getCause());428 result = false;429 }430 setImplicitTimeout();431 return result;432 }433 /**434 * Types text to specified element.435 *436 * @param text to type.437 */438 public void type(String text) {439 captureElements();440 String msg;441 final String decryptedText = cryptoTool.decryptByPattern(text, CRYPTO_PATTERN);442 WebDriver drv = getDriver();443 wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, RETRY_TIME);444 try {445 element = findElement(EXPLICIT_TIMEOUT);446 wait.until((Function<WebDriver, Object>) dr -> element.isDisplayed());447 scrollTo();448 element.clear();449 element.sendKeys(decryptedText);450 msg = Messager.KEYS_SEND_TO_ELEMENT.info(text, getName());451 summary.log(msg);452 } catch (StaleElementReferenceException e) {453 element = findStaleElement();454 LOGGER.debug(e.getMessage(), e.getCause());455 element.clear();456 element.sendKeys(decryptedText);457 msg = Messager.KEYS_SEND_TO_ELEMENT.info(text, getName());458 summary.log(msg);459 } catch (Exception e) {460 msg = Messager.KEYS_NOT_SEND_TO_ELEMENT.error(text, getNameWithLocator());461 summary.log(msg);462 throw new RuntimeException(msg, e);463 }464 Screenshot.capture(drv, msg);465 }466 /**467 * Set implicit timeout to default IMPLICIT_TIMEOUT value.468 */469 public void setImplicitTimeout() {470 setImplicitTimeout(IMPLICIT_TIMEOUT);471 }472 /**473 * Set implicit timeout.474 *475 * @param timeout in seconds. Minimal value - 1 second476 */477 public void setImplicitTimeout(long timeout) {478 if (timeout < 1) {479 timeout = 1;480 }481 try {482 getDriver().manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);483 } catch (Exception e) {484 LOGGER.error("Unable to set implicit timeout to " + timeout, e);485 getDriver().manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);486 }487 }488 /**489 * Safe click on element, used to reduce any problems with that action.490 *491 * @param startTimer Start time492 */493 private void clickSafe(long timeout, boolean startTimer) {494 boolean clicked = false;495 Exception reason = null;496 if (startTimer) {497 timer = System.currentTimeMillis();498 }499 try {500 findElement(timeout).click();501 clicked = true;502 } catch (UnhandledAlertException e) {503 LOGGER.debug(e.getMessage(), e.getCause());504 getDriver().switchTo().alert().accept();505 } catch (StaleElementReferenceException e) {506 element = findStaleElement();507 LOGGER.debug(e.getMessage(), e.getCause());508 } catch (Exception e) {509 LOGGER.debug(e.getMessage(), e.getCause());510 scrollTo();511 reason = e;512 }513 if (!clicked) {514 pause((double) RETRY_TIME / 1000);515 //repeat again until timeout achieved516 if (System.currentTimeMillis() - timer < timeout * 1000) {517 clickSafe(timeout, false);518 } else {519 String msg = Messager.ELEMENT_NOT_CLICKED.error(getNameWithLocator());520 summary.log(msg);521 throw new RuntimeException(msg, reason);522 }523 }524 }525 public void scrollTo() {526 if (Configuration.get(Parameter.DRIVER_TYPE).toLowerCase().contains(SpecialKeywords.MOBILE)) {527 LOGGER.debug("scrollTo javascript is unsupported for mobile devices!");528 return;529 }530 try {531 Locatable locatableElement = (Locatable) findElement(EXPLICIT_TIMEOUT);532 //[VD] onScreen should be updated onto onPage as only 2nd one returns real coordinates without scrolling... read below material for details533 //https://groups.google.com/d/msg/selenium-developers/nJR5VnL-3Qs/uqUkXFw4FSwJ534 //[CB] onPage -> inViewPort535 //https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/remote/RemoteWebElement.java?r=abc64b1df10d5f5d72d11fba37fabf5e85644081536 int y = locatableElement.getCoordinates().inViewPort().getY();537 int offset = R.CONFIG.getInt("scroll_to_element_y_offset");538 ((JavascriptExecutor) getDriver()).executeScript("window.scrollBy(0," + (y - offset) + ");");539 } catch (Exception e) {540 // TODO: calm error logging as it is too noisy541 //LOGGER.debug("Scroll to element: " + getName() + " not performed!" + e.getMessage());542 }543 }544 /**545 * Inputs file path to specified element.546 *547 * @param filePath path548 */549 public void attachFile(String filePath) {550 String msg;551 final String decryptedFilePath = cryptoTool.decryptByPattern(filePath, CRYPTO_PATTERN);552 WebDriver drv = getDriver();553 wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, RETRY_TIME);554 try {555 element = findElement(EXPLICIT_TIMEOUT);556 wait.until((Function<WebDriver, Object>) dr -> element.isDisplayed());557 element.sendKeys(decryptedFilePath);558 msg = Messager.FILE_ATTACHED.info(filePath);559 summary.log(msg);560 } catch (Exception e) {561 msg = Messager.FILE_NOT_ATTACHED.error(filePath);562 summary.log(msg);563 throw new RuntimeException(msg, e);564 }565 Screenshot.capture(drv, msg);566 }567 /**568 * Check checkbox569 * <p>570 * for checkbox Element571 */572 public void check() {573 if (isElementPresent() && !findElement(EXPLICIT_TIMEOUT).isSelected()) {574 click();575 String msg = Messager.CHECKBOX_CHECKED.info(getName());576 summary.log(msg);577 Screenshot.capture(getDriver(), msg);578 }579 }580 /**581 * Uncheck checkbox582 * <p>583 * for checkbox Element584 */585 public void uncheck() {586 if (isElementPresent() && findElement(EXPLICIT_TIMEOUT).isSelected()) {587 click();588 String msg = Messager.CHECKBOX_UNCHECKED.info(getName());589 summary.log(msg);590 Screenshot.capture(getDriver(), msg);591 }592 }593 /**594 * Get checkbox state.595 *596 * @return - current state597 */598 public boolean isChecked() {599 assertElementPresent();600 element = findElement(EXPLICIT_TIMEOUT);601 boolean res = element.isSelected();602 if (element.getAttribute("checked") != null) {603 res |= element.getAttribute("checked").equalsIgnoreCase("true");604 }605 return res;606 }607 /**608 * Get selected elements from one-value select.609 *610 * @return selected value611 */612 public String getSelectedValue() {613 assertElementPresent();614 return new Select(findElement(EXPLICIT_TIMEOUT)).getAllSelectedOptions().get(0).getText();615 }616 /**617 * Get selected elements from multi-value select.618 *619 * @return selected values620 */621 public List<String> getSelectedValues() {622 assertElementPresent();623 Select s = new Select(findElement(EXPLICIT_TIMEOUT));624 List<String> values = new ArrayList<String>();625 for (WebElement we : s.getAllSelectedOptions()) {626 values.add(we.getText());627 }628 return values;629 }630 private WebDriver getDriver() {631 return driver;632 }633 /**634 * Selects text in specified select element.635 *636 * @param selectText select text637 * @return true if item selected, otherwise false.638 */639 public boolean select(final String selectText) {640 boolean isSelected = false;641 final String decryptedSelectText = cryptoTool.decryptByPattern(selectText, CRYPTO_PATTERN);642 WebDriver drv = getDriver();643 wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, RETRY_TIME);644 645 final Select s = new Select(findElement(EXPLICIT_TIMEOUT));646 String msg = null;647 try {648 wait.until((Function<WebDriver, Object>) dr -> {649 try {650 s.selectByVisibleText(decryptedSelectText);651 return true;652 } catch (Exception e) {653 //do nothing654 }655 return false;656 });657 isSelected = true;658 msg = Messager.SELECT_BY_TEXT_PERFORMED.info(selectText, getName());659 } catch (Exception e) {660 msg = Messager.SELECT_BY_TEXT_NOT_PERFORMED.error(selectText, getNameWithLocator());661 e.printStackTrace();662 }663 summary.log(msg);664 Screenshot.capture(drv, msg);665 return isSelected;666 }667 /**668 * Select multiple text values in specified select element.669 *670 * @param values final String[]671 * @return boolean.672 */673 public boolean select(final String[] values) {674 boolean result = true;675 for (String value : values) {676 if (!select(value)) {677 result = false;678 }679 }680 return result;681 }682 /**683 * Selects value according to text value matcher.684 *685 * @param matcher {@link} BaseMatcher686 * @return true if item selected, otherwise false.687 * <p>688 * Usage example:689 * BaseMatcher&lt;String&gt; match=new BaseMatcher&lt;String&gt;() {690 * {@literal @}Override691 * public boolean matches(Object actual) {692 * return actual.toString().contains(RequiredText);693 * }694 * {@literal @}Override695 * public void describeTo(Description description) {696 * }697 * };698 */699 public boolean selectByMatcher(final BaseMatcher<String> matcher) {700 boolean isSelected = false;701 WebDriver drv = getDriver();702 wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, RETRY_TIME);703 704 final Select s = new Select(findElement(EXPLICIT_TIMEOUT));705 String msg = null;706 707 try {708 wait.until((Function<WebDriver, Object>) dr -> {709 try {710 String fullTextValue = null;711 for (WebElement option : s.getOptions()) {712 if (matcher.matches(option.getText())) {713 fullTextValue = option.getText();714 break;715 }716 }717 s.selectByVisibleText(fullTextValue);718 return true;719 } catch (Exception e) {720 LOGGER.debug(e.getMessage(), e.getCause());721 }722 return false;723 });724 isSelected = true;725 msg = Messager.SELECT_BY_MATCHER_TEXT_PERFORMED.info(matcher.toString(), getName());726 } catch (Exception e) {727 msg = Messager.SELECT_BY_MATCHER_TEXT_NOT_PERFORMED.error(matcher.toString(), getNameWithLocator());728 e.printStackTrace();729 }730 summary.log(msg);731 Screenshot.capture(drv, msg);732 return isSelected;733 }734 /**735 * Selects first value according to partial text value.736 *737 * @param partialSelectText select by partial text738 * @return true if item selected, otherwise false.739 */740 public boolean selectByPartialText(final String partialSelectText) {741 boolean isSelected = false;742 WebDriver drv = getDriver();743 wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, RETRY_TIME);744 745 final Select s = new Select(findElement(EXPLICIT_TIMEOUT));746 String msg = null;747 try {748 wait.until((Function<WebDriver, Object>) dr -> {749 try {750 String fullTextValue = null;751 for (WebElement option : s.getOptions()) {752 if (option.getText().contains(partialSelectText)) {753 fullTextValue = option.getText();754 break;755 }756 }757 s.selectByVisibleText(fullTextValue);758 return true;759 } catch (Exception e) {760 LOGGER.debug(e.getMessage(), e.getCause());761 }762 return false;763 });764 isSelected = true;765 msg = Messager.SELECT_BY_TEXT_PERFORMED.info(partialSelectText, getName());766 } catch (Exception e) {767 msg = Messager.SELECT_BY_TEXT_NOT_PERFORMED.error(partialSelectText, getNameWithLocator());768 e.printStackTrace();769 }770 summary.log(msg);771 Screenshot.capture(drv, msg);772 return isSelected;773 }774 /**775 * Selects item by index in specified select element.776 *777 * @param index to select by778 * @return true if item selected, otherwise false.779 */780 public boolean select(final int index) {781 boolean isSelected = false;782 WebDriver drv = getDriver();783 wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, RETRY_TIME);784 785 final Select s = new Select(findElement(EXPLICIT_TIMEOUT));786 String msg = null;787 try {788 wait.until((Function<WebDriver, Object>) dr -> {789 try {790 s.selectByIndex(index);791 return true;792 } catch (Exception e) {793 LOGGER.debug(e.getMessage(), e.getCause());794 }795 return false;796 });797 isSelected = true;798 msg = Messager.SELECT_BY_INDEX_PERFORMED.info(String.valueOf(index), getName());799 } catch (Exception e) {800 msg = Messager.SELECT_BY_INDEX_NOT_PERFORMED.error(String.valueOf(index), getNameWithLocator());801 e.printStackTrace();802 }803 summary.log(msg);804 Screenshot.capture(drv, msg);805 return isSelected;806 }807 // --------------------------------------------------------------------------808 // Base UI validations809 // --------------------------------------------------------------------------810 public void assertElementPresent() {811 assertElementPresent(EXPLICIT_TIMEOUT);812 }813 public void assertElementPresent(long timeout) {814 if (isElementPresent(timeout)) {815 Screenshot.capture(getDriver(), Messager.ELEMENT_PRESENT.getMessage(getName()));816 } else {817 Assert.fail(Messager.ELEMENT_NOT_PRESENT.getMessage(getNameWithLocator()));818 }819 }820 public void assertElementWithTextPresent(final String text) {821 assertElementWithTextPresent(text, EXPLICIT_TIMEOUT);822 }823 public void assertElementWithTextPresent(final String text, long timeout) {824 if (isElementWithTextPresent(text, timeout)) {825 Screenshot.capture(getDriver(), Messager.ELEMENT_WITH_TEXT_PRESENT.getMessage(getName(), text));826 } else {827 Assert.fail(Messager.ELEMENT_WITH_TEXT_NOT_PRESENT.getMessage(getNameWithLocator(), text));828 }829 }830 /**831 * Find Extended Web Element on page using By starting search from this object.832 *833 * @param by Selenium By locator834 * @return ExtendedWebElement if exists otherwise null.835 */836 public ExtendedWebElement findExtendedWebElement(By by) {837 return findExtendedWebElement(by, by.toString(), EXPLICIT_TIMEOUT);838 }839 /**840 * Find Extended Web Element on page using By starting search from this object.841 *842 * @param by Selenium By locator843 * @param timeout to wait844 * @return ExtendedWebElement if exists otherwise null.845 */846 public ExtendedWebElement findExtendedWebElement(By by, long timeout) {847 return findExtendedWebElement(by, by.toString(), timeout);848 }849 /**850 * Find Extended Web Element on page using By starting search from this object.851 *852 * @param by Selenium By locator853 * @param name Element name854 * @return ExtendedWebElement if exists otherwise null.855 */856 public ExtendedWebElement findExtendedWebElement(final By by, String name) {857 return findExtendedWebElement(by, name, EXPLICIT_TIMEOUT);858 }859 /**860 * Find Extended Web Element on page using By starting search from this object.861 *862 * @param by Selenium By locator863 * @param name Element name864 * @param timeout Timeout to find865 * @return ExtendedWebElement if exists otherwise null.866 */867 public ExtendedWebElement findExtendedWebElement(final By by, String name, long timeout) {868 ExtendedWebElement element;869 final WebDriver drv = getDriver();870 setImplicitTimeout(1);871 wait = new WebDriverWait(drv, timeout, RETRY_TIME);872 try {873 wait.until((Function<WebDriver, Object>) dr -> {874 //try to search starting from existing webElement and using driver directly875 if (!drv.findElements(by).isEmpty()) {876 return true;877 } else if (getElement() != null) {878 return !getElement().findElements(by).isEmpty();879 }880 return false;881 });882 element = new ExtendedWebElement(this.getElement().findElement(by), name, by, driver);883 //summary.log(Messager.ELEMENT_FOUND.info(name));884 } catch (Exception e) {885 element = null;886 //summary.log(Messager.ELEMENT_NOT_FOUND.error(name));887 setImplicitTimeout(IMPLICIT_TIMEOUT);888 throw new RuntimeException(e);889 }890 setImplicitTimeout(IMPLICIT_TIMEOUT);891 return element;892 }893 public List<ExtendedWebElement> findExtendedWebElements(By by) {894 return findExtendedWebElements(by, EXPLICIT_TIMEOUT);895 }896 public List<ExtendedWebElement> findExtendedWebElements(final By by, long timeout) {897 List<ExtendedWebElement> extendedWebElements = new ArrayList<ExtendedWebElement>();898 List<WebElement> webElements = new ArrayList<WebElement>();899 final WebDriver drv = getDriver();900 setImplicitTimeout(1);901 wait = new WebDriverWait(drv, timeout, RETRY_TIME);902 try {903 wait.until((Function<WebDriver, Object>) dr -> {904 //try to search starting from existing webElement and using driver directly905 if (!drv.findElements(by).isEmpty()) {906 return true;907 } else if (getElement() != null) {908 return !getElement().findElements(by).isEmpty();909 }910 return false;911 });912 webElements = this.getElement().findElements(by);913 } catch (Exception e) {914 LOGGER.debug(e.getMessage(), e.getCause());915 //do nothing916 }917 for (WebElement element : webElements) {918 String name = "undefined";919 try {920 name = element.getText();921 } catch (Exception e) {922 /* do nothing*/923 LOGGER.debug(e.getMessage(), e.getCause());924 }925 extendedWebElements.add(new ExtendedWebElement(element, name, driver));926 }927 setImplicitTimeout();928 return extendedWebElements;929 }930 public void tapWithCoordinates(double x, double y) {931 HashMap<String, Double> tapObject = new HashMap<String, Double>();932 tapObject.put("x", x);933 tapObject.put("y", y);934 final WebDriver drv = getDriver();935 JavascriptExecutor js = (JavascriptExecutor) drv;936 js.executeScript("mobile: tap", tapObject);937 }938 public void waitUntilElementNotPresent(final long timeout) {939 final ExtendedWebElement element = this;940 LOGGER.info(String.format("Wait until element %s disappear", element.getName()));941 final WebDriver drv = getDriver();942 setImplicitTimeout(1);943 wait = new WebDriverWait(drv, timeout, RETRY_TIME);944 try {945 wait.until((Function<WebDriver, Object>) dr -> {946 boolean result = drv.findElements(element.getBy()).size() == 0;947 if (!result) {948 LOGGER.debug(drv.getPageSource());949 LOGGER.info(String.format("Element %s is still present. Wait until it disappear.",950 element.getName()));951 }952 return result;953 });954 } catch (Exception e) {955 LOGGER.debug(e.getMessage(), e.getCause());956 // do nothing957 }958 setImplicitTimeout();959 }960 /**961 * is Element Not Present After Wait962 *963 * @param timeout in seconds964 * @return boolean - false if element still present after wait - otherwise true if it disappear965 */966 public boolean isElementNotPresentAfterWait(final long timeout) {967 final ExtendedWebElement element = this;968 LOGGER.info(String.format("Check element %s not presence after wait.", element.getName()));969 Wait<WebDriver> wait =970 new FluentWait<WebDriver>(getDriver()).withTimeout(timeout, TimeUnit.SECONDS).pollingEvery(1,971 TimeUnit.SECONDS).ignoring(NoSuchElementException.class);972 try {973 return wait.until(driver -> {974 boolean result = driver.findElements(element.getBy()).isEmpty();975 if (!result) {976 LOGGER.info(String.format("Element '%s' is still present. Wait until it disappear.", element977 .getNameWithLocator()));978 }979 return result;980 });981 } catch (Exception e) {982 LOGGER.error("Error happened: " + e.getMessage(), e.getCause());983 LOGGER.warn("Return standard element not presence method");984 return !element.isElementPresent();985 }986 }987 /**988 * Checks that element clickable.989 *990 * @return element clickability status.991 */992 public boolean isClickable() {993 return isClickable(EXPLICIT_TIMEOUT);994 }995 /**996 * Check that element clickable within specified timeout.997 *998 * @param timeout - timeout.999 * @return element clickability status.1000 */1001 public boolean isClickable(long timeout) {1002 final WebDriver drv = getDriver();1003 By locator = getBy();1004 boolean res = true;1005 String msg = "";1006 try {1007 ExpectedConditions.elementToBeClickable(locator);1008 (new WebDriverWait(drv, timeout)).until(ExpectedConditions.elementToBeClickable(locator));1009 msg = Messager.ELEMENT_BECOME_CLICKABLE.info(getName());1010 summary.log(msg);1011 } catch (TimeoutException ex) {1012 msg = Messager.ELEMENT_NOT_BECOME_CLICKABLE.info(getName());1013 summary.log(msg);1014 LOGGER.error(ex);1015 res = false;1016 } catch (Exception e) {1017 msg = Messager.ELEMENT_NOT_BECOME_CLICKABLE.info(getName());1018 summary.log(msg);1019 LOGGER.error(e);1020 res = false;1021 }1022 try {1023 Screenshot.capture(getDriver(), msg);1024 } catch (Exception e) {1025 LOGGER.info(e.getMessage());1026 }1027 return res;1028 }1029 1030 /**1031 * Checks that element visible.1032 *1033 * @return element visibility status.1034 */1035 public boolean isVisible() {1036 return isVisible(EXPLICIT_TIMEOUT);1037 }1038 /**1039 * Check that element visible within specified timeout.1040 *1041 * @param timeout - timeout.1042 * @return element visibility status.1043 */1044 public boolean isVisible(long timeout) {1045 final WebDriver drv = getDriver();1046 By locator = getBy();1047 boolean res = true;1048 String msg = "";1049 try {1050 ExpectedConditions.elementToBeClickable(locator);1051 (new WebDriverWait(drv, timeout)).until(ExpectedConditions.visibilityOfElementLocated(locator));1052 msg = Messager.ELEMENT_BECOME_VISIBLE.info(getName());1053 summary.log(msg);1054 } catch (TimeoutException ex) {1055 msg = Messager.ELEMENT_NOT_BECOME_VISIBLE.info(getName());1056 summary.log(msg);1057 LOGGER.error(ex);1058 res = false;1059 } catch (Exception e) {1060 msg = Messager.ELEMENT_NOT_BECOME_VISIBLE.info(getName());1061 summary.log(msg);1062 LOGGER.error(e);1063 res = false;1064 }1065 try {1066 Screenshot.capture(getDriver(), msg);1067 } catch (Exception e) {1068 LOGGER.info(e.getMessage());1069 }1070 return res;1071 }1072 public ExtendedWebElement format(Object... objects) {1073 String locator = by.toString();1074 By by = null;1075 if (locator.startsWith("By.id: ")) {1076 by = By.id(String.format(StringUtils.remove(locator, "By.id: "), objects));1077 }1078 if (locator.startsWith("By.name: ")) {1079 by = By.name(String.format(StringUtils.remove(locator, "By.name: "), objects));1080 }1081 if (locator.startsWith("By.xpath: ")) {1082 by = By.xpath(String.format(StringUtils.remove(locator, "By.xpath: "), objects));1083 }1084 if (locator.startsWith("linkText: ")) {1085 by = By.linkText(String.format(StringUtils.remove(locator, "linkText: "), objects));1086 }1087 if (locator.startsWith("partialLinkText: ")) {1088 by = By.linkText(String.format(StringUtils.remove(locator, "partialLinkText: "), objects));1089 }1090 if (locator.startsWith("css: ")) {1091 by = By.cssSelector(String.format(StringUtils.remove(locator, "css: "), objects));1092 }1093 if (locator.startsWith("tagName: ")) {1094 by = By.tagName(String.format(StringUtils.remove(locator, "tagName: "), objects));1095 }1096 return new ExtendedWebElement(null, name, by, driver);1097 }1098 private void captureElements() {1099 if (!Configuration.getBoolean(Parameter.SMART_SCREENSHOT)) {1100 return;1101 }1102 if (!BrowserType.CHROME.equalsIgnoreCase(Configuration.get(Parameter.BROWSER))){1103 return;1104 }1105 String currentUrl;1106 if (!Configuration.get(Parameter.BROWSER).isEmpty()) {1107 currentUrl = driver.getCurrentUrl();1108 } else {1109 //change for XBox and looks like mobile part1110 currentUrl = driver.getTitle();1111 }1112 String cache = getUrlWithoutParameters(currentUrl);1113 if (!MetadataCollector.getAllCollectedData().containsKey(cache)) {1114 try {1115 ElementsInfo elementsInfo = new ElementsInfo();1116 elementsInfo.setCurrentURL(currentUrl);1117 1118 String metadataScreenPath = Screenshot.captureMetadata(getDriver(), String.valueOf(cache.hashCode()));1119 //TODO: double check that file exist because due to the different reason screenshot can miss1120 File newPlace = new File(metadataScreenPath);1121 1122 ScreenShootInfo screenShootInfo = new ScreenShootInfo();1123 screenShootInfo.setScreenshotPath(newPlace.getAbsolutePath());1124 BufferedImage bimg = ImageIO.read(newPlace);1125 1126 screenShootInfo.setWidth(bimg.getWidth());1127 screenShootInfo.setHeight(bimg.getHeight());1128 elementsInfo.setScreenshot(screenShootInfo);1129 List<WebElement> all = driver.findElements(By.xpath("//*"));1130 List<WebElement> control = driver.findElements(By.xpath("//input[not(contains(@type,'hidden'))] | //button | .//*[contains(@class, 'btn') and not(self::span)] | //select"));1131 for (WebElement webElement : control) {1132 ElementInfo elementInfo = getElementInfo(new ExtendedWebElement(webElement, driver));1133 int elementPosition = all.indexOf(webElement);1134 for (int i = 1; i < 5; i++) {1135 if (elementPosition - i < 0) {1136 break;1137 }1138 if (control.indexOf(all.get(elementPosition - i)) > 0) {1139 break;1140 }1141 if (!all.get(elementPosition - i).isDisplayed()) {1142 continue;1143 }1144 String sti = all.get(elementPosition - i).getText();1145 if (sti == null || sti.isEmpty() || control.get(0).getText().equals(sti)) {1146 continue;1147 } else {1148 elementInfo.setTextInfo(getElementInfo(new ExtendedWebElement(all.get(elementPosition - i), driver)));1149 break;1150 }1151 }1152 elementsInfo.addElement(elementInfo);1153 MetadataCollector.putPageInfo(cache, elementsInfo);1154 }1155 } catch (IOException e) {1156 LOGGER.error("Unable to capture elements metadata!", e);1157 } catch (Exception e) {1158 LOGGER.error("Unable to capture elements metadata!", e);1159 } catch (Throwable thr) {1160 LOGGER.error("Unable to capture elements metadata!", thr);1161 }1162 }1163 }1164 private String getUrlWithoutParameters(String url) {1165 try {1166 URI uri = new URI(url);1167 return new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, uri.getFragment()).toString();1168 } catch (URISyntaxException e) {1169 e.printStackTrace();1170 }1171 return url;1172 }1173 @SuppressWarnings("unchecked")1174 private ElementInfo getElementInfo(ExtendedWebElement extendedWebElement) {1175 ElementInfo elementInfo = new ElementInfo();1176 if (extendedWebElement.isElementPresent(1)) {1177 Point location = extendedWebElement.getElement().getLocation();1178 Dimension size = extendedWebElement.getElement().getSize();1179 elementInfo.setRect(new Rect(location.getX(), location.getY(), size.getWidth(), size.getHeight()));1180 elementInfo.setElementsAttributes((Map<String, String>) ((RemoteWebDriver) driver).executeScript(ATTRIBUTE_JS, extendedWebElement.getElement()));1181 try {1182 elementInfo.setText(extendedWebElement.getText());1183 } catch (Exception e){1184 elementInfo.setText("");1185 }1186 return elementInfo;1187 } else {1188 return null;1189 }1190 }1191 /**1192 * Pause for specified timeout.1193 * 1194 * @param timeout...

Full Screen

Full Screen

Source:Table.java Github

copy

Full Screen

...58 }59 public ExtendedWebElement getElement() {60 return element;61 }62 public void setElement( ExtendedWebElement element ) {63 this.element = element;64 }65 }66 public static class TableRow {67 private List<TableCell> cells;68 public TableRow() {69 this.cells = new ArrayList<TableCell>();70 }71 public List<TableCell> getCells() {72 return cells;73 }74 public void setCells( List<TableCell> cells ) {75 this.cells = cells;76 }...

Full Screen

Full Screen

setElement

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.demo.gui.pages;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.support.FindBy;4import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;5import com.qaprosoft.carina.core.gui.AbstractPage;6{7 private ExtendedWebElement logo;8 public HomePage(WebDriver driver)9 {10 super(driver);11 setUiLoadedMarker(logo);12 }13}14package com.qaprosoft.carina.demo.gui.pages;15import org.openqa.selenium.WebDriver;16import org.openqa.selenium.support.FindBy;17import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;18import com.qaprosoft.carina.core.gui.AbstractPage;19{20 private ExtendedWebElement logo;21 public HomePage(WebDriver driver)22 {23 super(driver);24 setUiLoadedMarker(logo);25 }26}27package com.qaprosoft.carina.demo.gui.pages;28import org.openqa.selenium.WebDriver;29import org.openqa.selenium.support.FindBy;30import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;31import com.qaprosoft.carina.core.gui.AbstractPage;32{33 private ExtendedWebElement logo;34 public HomePage(WebDriver driver)35 {36 super(driver);37 setUiLoadedMarker(logo);38 }39}40package com.qaprosoft.carina.demo.gui.pages;41import org.openqa.selenium.WebDriver;42import org.openqa.selenium.support.FindBy;43import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;44import com.qaprosoft.carina.core.gui.AbstractPage;45{

Full Screen

Full Screen

setElement

Using AI Code Generation

copy

Full Screen

1import org.testng.annotations.Test;2import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;3import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;4import org.openqa.selenium.By;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.chrome.ChromeDriver;8public class SetElement {9 public void setElement() {10 WebDriver driver = new ChromeDriver();11 WebElement element = driver.findElement(By.name("q"));12 ExtendedWebElement extendedWebElement = new ExtendedWebElement(element);13 extendedWebElement.setElement(element);14 extendedWebElement.click();15 driver.quit();16 }17}18import org.testng.annotations.Test;19import org.openqa.selenium.By;20import org.openqa.selenium.WebDriver;21import org.openqa.selenium.WebElement;22import org.openqa.selenium.chrome.ChromeDriver;23public class SetElement {24 public void setElement() {25 WebDriver driver = new ChromeDriver();26 WebElement element = driver.findElement(By.name("q"));27 element.click();28 driver.quit();29 }30}31import org.testng.annotations.Test;32import org.openqa.selenium.By;33import org.openqa.selenium.WebDriver;34import org.openqa.selenium.WebElement;35import org.openqa.selenium.chrome.ChromeDriver;36public class SetElement {37 public void setElement() {38 WebDriver driver = new ChromeDriver();39 WebElement element = driver.findElement(By.name("q"));40 element.click();41 driver.quit();42 }43}44import org.testng.annotations.Test;45import org.openqa.selenium.By;46import org.openqa.selenium.WebDriver;47import org.openqa.selenium.WebElement;48import org.openqa.selenium.chrome.ChromeDriver;49public class SetElement {50 public void setElement() {51 WebDriver driver = new ChromeDriver();52 WebElement element = driver.findElement(By.name("q"));53 element.click();54 driver.quit();55 }56}57import org.testng.annotations.Test;58import org.openqa.selenium.By

Full Screen

Full Screen

setElement

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.webdriver.decorator;2import java.util.List;3import org.openqa.selenium.By;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.support.FindBy;6import org.openqa.selenium.support.FindBys;7import org.openqa.selenium.support.How;8import org.testng.Assert;9import org.testng.annotations.Test;10import com.qaprosoft.carina.core.foundation.AbstractTest;11import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;12public class ExtendedWebElementTest extends AbstractTest {13 private ExtendedWebElement testElement;14 private List<ExtendedWebElement> testElements;15 private WebElement testWebElement;16 private List<WebElement> testWebElements;17 public void testExtendedWebElement() {18 Assert.assertNotNull(testElement);19 Assert.assertNotNull(testWebElement);20 Assert.assertNotNull(testElements);21 Assert.assertNotNull(testWebElements);22 Assert.assertEquals(testElements.size(), testWebElements.size());23 }24 public void testSetElement() {25 Assert.assertNotNull(testElement);26 Assert.assertNotNull(testWebElement);27 Assert.assertNotNull(testElements);28 Assert.assertNotNull(testWebElements);29 Assert.assertEquals(testElements.size(), testWebElements.size());30 testElements.get(0).setElement(testWebElement);31 Assert.assertEquals(testElements.get(0).getElement(), testWebElement);32 }33}34package com.qaprosoft.carina.core.foundation.webdriver.decorator;35import java.lang.reflect.Field;36import java.util.List;37import org.openqa.selenium.By;38import org.openqa.selenium.WebElement;39import org.openqa.selenium.support.FindBy;40import org.openqa.selenium.support.FindBys;41import org.openqa.selenium.support.How;42import org.testng.Assert;43import org.testng.annotations.Test;44import com.qaprosoft.carina.core.foundation.AbstractTest;45import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;46public class ExtendedWebElementTest extends AbstractTest {47 private ExtendedWebElement testElement;48 private List<ExtendedWebElement> testElements;

Full Screen

Full Screen

setElement

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.demo;2import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;3import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.support.FindBy;7import org.openqa.selenium.support.PageFactory;8public class SetElementExample {9 WebDriver driver;10 @FindBy(id = "mytext")11 ExtendedWebElement myText;12 public SetElementExample(WebDriver driver) {13 this.driver = driver;14 PageFactory.initElements(driver, this);15 }16 public void setElementValue() {17 myText.setElement("This is my test");18 }19 public static void main(String[] args) {20 System.setProperty("webdriver.chrome.driver", "chromedriver.exe");21 WebDriver driver = new ChromeDriver();22 SetElementExample setElementExample = new SetElementExample(driver);23 setElementExample.setElementValue();24 }25}26package com.qaprosoft.carina.demo;27import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;28import org.openqa.selenium.WebDriver;29import org.openqa.selenium.chrome.ChromeDriver;30import org.openqa.selenium.support.FindBy;31import org.openqa.selenium.support.PageFactory;32public class SetElementExample {33 WebDriver driver;34 @FindBy(id = "mytext")35 ExtendedWebElement myText;36 public SetElementExample(WebDriver driver) {37 this.driver = driver;38 PageFactory.initElements(driver, this);39 }40 public void setElementValue() {41 myText.setElement("This is my test");42 }43 public static void main(String[] args) {44 System.setProperty("webdriver.chrome.driver", "chromedriver.exe");45 WebDriver driver = new ChromeDriver();46 SetElementExample setElementExample = new SetElementExample(driver);47 setElementExample.setElementValue();48 }49}50I have a requirement where I need to click on a button which is not visible on the page. I have tried using the scrollIntoView() method but it is not working. Can you please help me with this?

Full Screen

Full Screen

setElement

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.webdriver.decorator;2import org.openqa.selenium.By;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.support.pagefactory.ElementLocator;5import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;6import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler;7import java.lang.reflect.Field;8import java.lang.reflect.InvocationHandler;9import java.lang.reflect.Proxy;10public class ExtendedElementLocatorFactory implements ElementLocatorFactory {11 private final ExtendedFieldDecorator decorator;12 private final SearchContext searchContext;13 public ExtendedElementLocatorFactory(SearchContext searchContext, ExtendedFieldDecorator decorator) {14 this.searchContext = searchContext;15 this.decorator = decorator;16 }17 public ElementLocator createLocator(Field field) {18 return new ExtendedElementLocator(searchContext, field, decorator);19 }20 public static WebElement createWebElement(ExtendedFieldDecorator decorator, Field field) {21 InvocationHandler handler = new LocatingElementHandler(new ExtendedElementLocator(decorator.getSearchContext(), field, decorator));22 WebElement proxy = (WebElement) Proxy.newProxyInstance(WebElement.class.getClassLoader(), new Class[]{WebElement.class}, handler);23 return proxy;24 }25}26package com.qaprosoft.carina.core.foundation.webdriver.decorator;27import org.openqa.selenium.By;28import org.openqa.selenium.WebElement;29import org.openqa.selenium.support.pagefactory.ElementLocator;30import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;31import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler;32import java.lang.reflect.Field;33import java.lang.reflect.InvocationHandler;34import java.lang.reflect.Proxy;35public class ExtendedElementLocatorFactory implements ElementLocatorFactory {36 private final ExtendedFieldDecorator decorator;37 private final SearchContext searchContext;38 public ExtendedElementLocatorFactory(SearchContext searchContext, ExtendedFieldDecorator decorator) {39 this.searchContext = searchContext;40 this.decorator = decorator;41 }42 public ElementLocator createLocator(Field field) {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful