How to use getRetryInterval method of com.qaprosoft.carina.core.foundation.webdriver.DriverHelper class

Best Carina code snippet using com.qaprosoft.carina.core.foundation.webdriver.DriverHelper.getRetryInterval

Source:ExtendedWebElement.java Github

copy

Full Screen

...314 LOGGER.warn("Fluent wait less than 1sec timeout might hangs! Updating to 1 sec.");315 timeout = 1;316 }317 318 long retryInterval = getRetryInterval(timeout);319 320 //try to use better tickMillis clock321 Wait<WebDriver> wait = new WebDriverWait(getDriver(), 322 java.time.Clock.tickMillis(java.time.ZoneId.systemDefault()), 323 Sleeper.SYSTEM_SLEEPER, 324 timeout, 325 retryInterval)326 .withTimeout(Duration.ofSeconds(timeout));327 // [VD] Notes:328 // do not ignore TimeoutException or NoSuchSessionException otherwise you can wait for minutes instead of timeout!329 // [VD] note about NoSuchSessionException is pretty strange. Let's ignore here and return false only in case of330 // TimeoutException putting details into the debug log message. All the rest shouldn't be ignored331 332 // 7.3.17-SNAPSHOT. Removed NoSuchSessionException (Mar-11-2022)333 //.ignoring(NoSuchSessionException.class) // why do we ignore noSuchSession? Just to minimize errors?334 335 // 7.3.20.1686-SNAPSHOT. Removed ignoring WebDriverException (Jun-03-2022).336 // Goal to test if inside timeout happens first and remove interruption and future call337 // removed ".ignoring(NoSuchElementException.class);" as NotFoundException ignored by waiter itself338 // added explicit .withTimeout(Duration.ofSeconds(timeout)); 339 LOGGER.debug("waitUntil: starting... timeout: " + timeout);340 boolean res = false;341 try {342 wait.until(condition);343 res = true;344 } catch (TimeoutException e) {345 LOGGER.debug("waitUntil: org.openqa.selenium.TimeoutException", e);346 } finally {347 LOGGER.debug("waiter is finished. conditions: " + condition);348 }349 return res;350 351 }352 private WebElement findElement() {353 List<WebElement> elements = searchContext.findElements(this.by);354 if (elements.isEmpty()) {355 throw new NoSuchElementException(SpecialKeywords.NO_SUCH_ELEMENT_ERROR + this.by.toString());356 }357 if (elements.size() > 1) {358 //TODO: think about moving into the debug or info level359 LOGGER.warn(String.format("returned first but found %d elements by xpath: %s", elements.size(), getBy()));360 }361 this.element = elements.get(0);362 return element;363 }364 365 public void setElement(WebElement element) {366 this.element = element;367 }368 public String getName() {369 return this.name + this.formatValues;370 }371 public String getNameWithLocator() {372 if (this.by != null) {373 return this.name + this.formatValues + String.format(" (%s)", by);374 } else {375 return this.name + this.formatValues + " (n/a)";376 }377 }378 public void setName(String name) {379 this.name = name;380 }381 382 /**383 * Get element By.384 *385 * @return By by386 */387 public By getBy() {388 // todo move this code from getter389 By value = by;390 if (caseInsensitiveConverter != null) {391 value = caseInsensitiveConverter.convert(this.by);392 }393 return value;394 }395 public void setBy(By by) {396 this.by = by;397 }398 public void setSearchContext(SearchContext searchContext) {399 this.searchContext = searchContext;400 }401 @Override402 public String toString() {403 return name;404 }405 /**406 * Get element text.407 *408 * @return String text409 */410 public String getText() {411 return (String) doAction(ACTION_NAME.GET_TEXT, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()));412 }413 /**414 * Get element location.415 *416 * @return Point location417 */418 public Point getLocation() {419 return (Point) doAction(ACTION_NAME.GET_LOCATION, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()));420 }421 /**422 * Get element size.423 *424 * @return Dimension size425 */426 public Dimension getSize() {427 return (Dimension) doAction(ACTION_NAME.GET_SIZE, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()));428 }429 /**430 * Get element attribute.431 *432 * @param name of attribute433 * @return String attribute value434 */435 public String getAttribute(String name) {436 return (String) doAction(ACTION_NAME.GET_ATTRIBUTE, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), name);437 }438 /**439 * Click on element.440 */441 public void click() {442 click(EXPLICIT_TIMEOUT);443 }444 /**445 * Click on element.446 *447 * @param timeout to wait448 */449 public void click(long timeout) {450 click(timeout, getDefaultCondition(getBy()));451 }452 453 /**454 * Click on element.455 *456 * @param timeout to wait457 * @param waitCondition458 * to check element conditions before action459 */460 public void click(long timeout, ExpectedCondition<?> waitCondition) {461 doAction(ACTION_NAME.CLICK, timeout, waitCondition);462 }463 464 /**465 * Click on element by javascript.466 */467 public void clickByJs() {468 clickByJs(EXPLICIT_TIMEOUT);469 }470 /**471 * Click on element by javascript.472 *473 * @param timeout to wait474 */475 public void clickByJs(long timeout) {476 clickByJs(timeout, getDefaultCondition(getBy()));477 }478 479 /**480 * Click on element by javascript.481 *482 * @param timeout to wait483 * @param waitCondition484 * to check element conditions before action485 */486 public void clickByJs(long timeout, ExpectedCondition<?> waitCondition) {487 doAction(ACTION_NAME.CLICK_BY_JS, timeout, waitCondition);488 }489 490 /**491 * Click on element by Actions.492 */493 public void clickByActions() {494 clickByActions(EXPLICIT_TIMEOUT);495 }496 /**497 * Click on element by Actions.498 *499 * @param timeout to wait500 */501 public void clickByActions(long timeout) {502 clickByActions(timeout, getDefaultCondition(getBy()));503 }504 505 /**506 * Click on element by Actions.507 *508 * @param timeout to wait509 * @param waitCondition510 * to check element conditions before action511 */512 public void clickByActions(long timeout, ExpectedCondition<?> waitCondition) {513 doAction(ACTION_NAME.CLICK_BY_ACTIONS, timeout, waitCondition);514 }515 516 /**517 * Double Click on element.518 */519 public void doubleClick() {520 doubleClick(EXPLICIT_TIMEOUT);521 }522 523 /**524 * Double Click on element.525 *526 * @param timeout to wait527 */528 public void doubleClick(long timeout) {529 doubleClick(timeout, getDefaultCondition(getBy()));530 }531 /**532 * Double Click on element.533 *534 * @param timeout to wait535 * @param waitCondition536 * to check element conditions before action537 */538 public void doubleClick(long timeout, ExpectedCondition<?> waitCondition) {539 doAction(ACTION_NAME.DOUBLE_CLICK, timeout, waitCondition);540 }541 542 /**543 * Mouse RightClick on element.544 */545 public void rightClick() {546 rightClick(EXPLICIT_TIMEOUT);547 }548 549 /**550 * Mouse RightClick on element.551 *552 * @param timeout to wait553 */554 public void rightClick(long timeout) {555 rightClick(timeout, getDefaultCondition(getBy()));556 }557 558 /**559 * Mouse RightClick on element.560 *561 * @param timeout to wait562 * @param waitCondition563 * to check element conditions before action564 */565 public void rightClick(long timeout, ExpectedCondition<?> waitCondition) {566 doAction(ACTION_NAME.RIGHT_CLICK, timeout, waitCondition);567 }568 569 /**570 * MouseOver (Hover) an element.571 */572 public void hover() {573 hover(null, null);574 }575 /**576 * MouseOver (Hover) an element.577 * @param xOffset x offset for moving578 * @param yOffset y offset for moving579 */580 public void hover(Integer xOffset, Integer yOffset) {581 doAction(ACTION_NAME.HOVER, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), xOffset, yOffset);582 }583 584 /**585 * Click onto element if it present.586 *587 * @return boolean return true if clicked588 */589 public boolean clickIfPresent() {590 return clickIfPresent(EXPLICIT_TIMEOUT);591 }592 /**593 * Click onto element if present.594 *595 * @param timeout - timeout596 * @return boolean return true if clicked597 */598 public boolean clickIfPresent(long timeout) {599 boolean present = isElementPresent(timeout);600 if (present) {601 click();602 }603 return present;604 }605 606 /**607 * Send Keys to element.608 * 609 * @param keys Keys610 */611 public void sendKeys(Keys keys) {612 sendKeys(keys, EXPLICIT_TIMEOUT);613 }614 /**615 * Send Keys to element.616 *617 * @param keys Keys618 * @param timeout to wait619 */620 public void sendKeys(Keys keys, long timeout) {621 sendKeys(keys, timeout, getDefaultCondition(getBy()));622 }623 624 /**625 * Send Keys to element.626 *627 * @param keys Keys628 * @param timeout to wait629 * @param waitCondition630 * to check element conditions before action631 */632 public void sendKeys(Keys keys, long timeout, ExpectedCondition<?> waitCondition) {633 doAction(ACTION_NAME.SEND_KEYS, timeout, waitCondition, keys);634 }635 636 637 /**638 * Type text to element.639 * 640 * @param text String641 */642 public void type(String text) {643 type(text, EXPLICIT_TIMEOUT);644 }645 /**646 * Type text to element.647 *648 * @param text String649 * @param timeout to wait650 */651 public void type(String text, long timeout) {652 type(text, timeout, getDefaultCondition(getBy()));653 }654 655 /**656 * Type text to element.657 *658 * @param text String659 * @param timeout to wait660 * @param waitCondition661 * to check element conditions before action662 */663 public void type(String text, long timeout, ExpectedCondition<?> waitCondition) {664 doAction(ACTION_NAME.TYPE, timeout, waitCondition, text);665 }666 667 /**668 /**669 * Scroll to element (applied only for desktop).670 * Useful for desktop with React 671 */672 public void scrollTo() {673 if (Configuration.getDriverType().equals(SpecialKeywords.MOBILE)) {674 LOGGER.debug("scrollTo javascript is unsupported for mobile devices!");675 return;676 }677 try {678 Locatable locatableElement = (Locatable) this.findElement();679 // [VD] onScreen should be updated onto onPage as only 2nd one680 // returns real coordinates without scrolling... read below material681 // for details682 // https://groups.google.com/d/msg/selenium-developers/nJR5VnL-3Qs/uqUkXFw4FSwJ683 // [CB] onPage -> inViewPort684 // https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/remote/RemoteWebElement.java?r=abc64b1df10d5f5d72d11fba37fabf5e85644081685 int y = locatableElement.getCoordinates().inViewPort().getY();686 int offset = R.CONFIG.getInt("scroll_to_element_y_offset");687 ((JavascriptExecutor) getDriver()).executeScript("window.scrollBy(0," + (y - offset) + ");");688 } catch (Exception e) {689 //do nothing690 }691 }692 693 /* Inputs file path to specified element.694 *695 * @param filePath path696 */697 public void attachFile(String filePath) {698 doAction(ACTION_NAME.ATTACH_FILE, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), filePath);699 }700 /**701 * Check checkbox702 * <p>703 * for checkbox Element704 */705 public void check() {706 doAction(ACTION_NAME.CHECK, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()));707 }708 /**709 * Uncheck checkbox710 * <p>711 * for checkbox Element712 */713 public void uncheck() {714 doAction(ACTION_NAME.UNCHECK, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()));715 }716 /**717 * Get checkbox state.718 *719 * @return - current state720 */721 public boolean isChecked() {722 return (boolean) doAction(ACTION_NAME.IS_CHECKED, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()));723 }724 /**725 * Get selected elements from one-value select.726 *727 * @return selected value728 */729 public String getSelectedValue() {730 return (String) doAction(ACTION_NAME.GET_SELECTED_VALUE, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()));731 }732 /**733 * Get selected elements from multi-value select.734 *735 * @return selected values736 */737 @SuppressWarnings("unchecked")738 public List<String> getSelectedValues() {739 return (List<String>) doAction(ACTION_NAME.GET_SELECTED_VALUES, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()));740 }741 /**742 * Selects text in specified select element.743 *744 * @param selectText select text745 * @return true if item selected, otherwise false.746 */747 public boolean select(final String selectText) {748 return (boolean) doAction(ACTION_NAME.SELECT, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), selectText);749 }750 /**751 * Select multiple text values in specified select element.752 *753 * @param values final String[]754 * @return boolean.755 */756 public boolean select(final String[] values) {757 return (boolean) doAction(ACTION_NAME.SELECT_VALUES, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), values);758 }759 /**760 * Selects value according to text value matcher.761 *762 * @param matcher {@link} BaseMatcher763 * @return true if item selected, otherwise false.764 * <p>765 * Usage example: BaseMatcher&lt;String&gt; match=new766 * BaseMatcher&lt;String&gt;() { {@literal @}Override public boolean767 * matches(Object actual) { return actual.toString().contains(RequiredText);768 * } {@literal @}Override public void describeTo(Description description) {769 * } };770 */771 public boolean selectByMatcher(final BaseMatcher<String> matcher) {772 return (boolean) doAction(ACTION_NAME.SELECT_BY_MATCHER, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), matcher);773 }774 /**775 * Selects first value according to partial text value.776 *777 * @param partialSelectText select by partial text778 * @return true if item selected, otherwise false.779 */780 public boolean selectByPartialText(final String partialSelectText) {781 return (boolean) doAction(ACTION_NAME.SELECT_BY_PARTIAL_TEXT, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()),782 partialSelectText);783 }784 /**785 * Selects item by index in specified select element.786 *787 * @param index to select by788 * @return true if item selected, otherwise false.789 */790 public boolean select(final int index) {791 return (boolean) doAction(ACTION_NAME.SELECT_BY_INDEX, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), index);792 }793 // --------------------------------------------------------------------------794 // Base UI validations795 // --------------------------------------------------------------------------796 /**797 * Check that element present and visible.798 *799 * @return element existence status.800 */801 public boolean isElementPresent() {802 return isElementPresent(EXPLICIT_TIMEOUT);803 }804 /**805 * Check that element present and visible within specified timeout.806 *807 * @param timeout - timeout.808 * @return element existence status.809 */810 public boolean isElementPresent(long timeout) {811 // perform at once super-fast single selenium call and only if nothing found move to waitAction812 if (element != null) {813 try {814 if (element.isDisplayed()) {815 return true;816 }817 } catch (Exception e) {818 //do nothing as element is not found as expected here819 }820 }821 ExpectedCondition<?> waitCondition;822 823 // [VD] replace presenceOfElementLocated and visibilityOf conditions by single "visibilityOfElementLocated"824 // visibilityOf: Does not check for presence of the element as the error explains it.825 // visibilityOfElementLocated: Checks to see if the element is present and also visible. To check visibility, it makes sure that the element826 // has a height and width greater than 0.827 828 waitCondition = ExpectedConditions.visibilityOfElementLocated(getBy());829 return waitUntil(waitCondition, timeout);830 }831 /**832 * Check that element not present and not visible within specified timeout.833 *834 * @param timeout - timeout.835 * @return element existence status.836 */837 public boolean isElementNotPresent(long timeout) {838 return !isElementPresent(timeout);839 }840 /**841 * Checks that element clickable.842 *843 * @return element clickability status.844 */845 public boolean isClickable() {846 return isClickable(EXPLICIT_TIMEOUT);847 }848 /**849 * Check that element clickable within specified timeout.850 *851 * @param timeout - timeout.852 * @return element clickability status.853 */854 public boolean isClickable(long timeout) {855 ExpectedCondition<?> waitCondition;856 857 if (element != null) {858 waitCondition = ExpectedConditions.elementToBeClickable(element);859 } else {860 waitCondition = ExpectedConditions.elementToBeClickable(getBy());861 }862 863 return waitUntil(waitCondition, timeout);864 }865 /**866 * Checks that element visible.867 *868 * @return element visibility status.869 */870 public boolean isVisible() {871 return isVisible(EXPLICIT_TIMEOUT);872 }873 /**874 * Check that element visible within specified timeout.875 *876 * @param timeout - timeout.877 * @return element visibility status.878 */879 public boolean isVisible(long timeout) {880 ExpectedCondition<?> waitCondition;881 if (element != null) {882 waitCondition = ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(getBy()),883 ExpectedConditions.visibilityOf(element));884 } else {885 waitCondition = ExpectedConditions.visibilityOfElementLocated(getBy());886 }887 boolean res = false;888 try {889 res = waitUntil(waitCondition, timeout);890 } catch (StaleElementReferenceException e) {891 // there is no sense to continue as StaleElementReferenceException captured892 LOGGER.debug("waitUntil: StaleElementReferenceException", e);893 }894 895 return res;896 }897 898 /**899 * Check that element with text present.900 *901 * @param text of element to check.902 * @return element with text existence status.903 */904 public boolean isElementWithTextPresent(final String text) {905 return isElementWithTextPresent(text, EXPLICIT_TIMEOUT);906 }907 /**908 * Check that element with text present.909 *910 * @param text of element to check.911 * @param timeout - timeout.912 * @return element with text existence status.913 */914 public boolean isElementWithTextPresent(final String text, long timeout) {915 final String decryptedText = cryptoTool.decryptByPattern(text, CRYPTO_PATTERN);916 ExpectedCondition<Boolean> textCondition;917 if (element != null) {918 textCondition = ExpectedConditions.textToBePresentInElement(element, decryptedText);919 } else {920 textCondition = ExpectedConditions.textToBePresentInElementLocated(getBy(), decryptedText);921 }922 return waitUntil(textCondition, timeout);923 //TODO: restore below code as only projects are migrated to "isElementWithContainTextPresent"924// return waitUntil(ExpectedConditions.and(ExpectedConditions.presenceOfElementLocated(getBy()),925// ExpectedConditions.textToBe(getBy(), decryptedText)), timeout);926 }927 928 public void assertElementWithTextPresent(final String text) {929 assertElementWithTextPresent(text, EXPLICIT_TIMEOUT);930 }931 public void assertElementWithTextPresent(final String text, long timeout) {932 if (!isElementWithTextPresent(text, timeout)) {933 Assert.fail(Messager.ELEMENT_WITH_TEXT_NOT_PRESENT.getMessage(getNameWithLocator(), text));934 }935 }936 937 public void assertElementPresent() {938 assertElementPresent(EXPLICIT_TIMEOUT);939 }940 public void assertElementPresent(long timeout) {941 if (!isPresent(timeout)) {942 Assert.fail(Messager.ELEMENT_NOT_PRESENT.getMessage(getNameWithLocator()));943 }944 }945 /**946 * Find Extended Web Element on page using By starting search from this947 * object.948 *949 * @param by Selenium By locator950 * @return ExtendedWebElement if exists otherwise null.951 */952 public ExtendedWebElement findExtendedWebElement(By by) {953 return findExtendedWebElement(by, by.toString(), EXPLICIT_TIMEOUT);954 }955 /**956 * Find Extended Web Element on page using By starting search from this957 * object.958 *959 * @param by Selenium By locator960 * @param timeout to wait961 * @return ExtendedWebElement if exists otherwise null.962 */963 public ExtendedWebElement findExtendedWebElement(By by, long timeout) {964 return findExtendedWebElement(by, by.toString(), timeout);965 }966 /**967 * Find Extended Web Element on page using By starting search from this968 * object.969 *970 * @param by Selenium By locator971 * @param name Element name972 * @return ExtendedWebElement if exists otherwise null.973 */974 public ExtendedWebElement findExtendedWebElement(final By by, String name) {975 return findExtendedWebElement(by, name, EXPLICIT_TIMEOUT);976 }977 /**978 * Find Extended Web Element on page using By starting search from this979 * object.980 *981 * @param by Selenium By locator982 * @param name Element name983 * @param timeout Timeout to find984 * @return ExtendedWebElement if exists otherwise null.985 */986 public ExtendedWebElement findExtendedWebElement(final By by, String name, long timeout) {987 if (isPresent(by, timeout)) {988 return new ExtendedWebElement(by, name, this.driver, this.searchContext);989 } else {990 throw new NoSuchElementException(SpecialKeywords.NO_SUCH_ELEMENT_ERROR + by.toString());991 }992 }993 public List<ExtendedWebElement> findExtendedWebElements(By by) {994 return findExtendedWebElements(by, EXPLICIT_TIMEOUT);995 }996 public List<ExtendedWebElement> findExtendedWebElements(final By by, long timeout) {997 List<ExtendedWebElement> extendedWebElements = new ArrayList<ExtendedWebElement>();998 List<WebElement> webElements = new ArrayList<WebElement>();999 1000 if (isPresent(by, timeout)) {1001 webElements = getElement().findElements(by);1002 } else {1003 throw new NoSuchElementException(SpecialKeywords.NO_SUCH_ELEMENT_ERROR + by.toString());1004 }1005 int i = 1;1006 for (WebElement element : webElements) {1007 String name = "undefined";1008 try {1009 name = element.getText();1010 } catch (Exception e) {1011 /* do nothing */1012 LOGGER.debug("Error while getting text from element.", e);1013 }1014 // we can't initiate ExtendedWebElement using by as it belongs to the list of elements1015 extendedWebElements.add(new ExtendedWebElement(generateByForList(by, i), name, this.driver, this.searchContext));1016 i++;1017 }1018 return extendedWebElements;1019 }1020 public boolean waitUntilElementDisappear(final long timeout) {1021 try {1022 if (this.element == null) {1023 // if element not found it will cause NoSuchElementException1024 findElement();1025 } else {1026 // if element is stale, it will cause StaleElementReferenceException1027 this.element.isDisplayed();1028 }1029 return waitUntil(ExpectedConditions.or(ExpectedConditions.stalenessOf(this.element),1030 ExpectedConditions.invisibilityOf(this.element)),1031 timeout);1032 } catch (NoSuchElementException | StaleElementReferenceException e) {1033 // element not present so means disappear1034 return true;1035 }1036 }1037 public ExtendedWebElement format(Object... objects) {1038 String locator = by.toString();1039 By by = null;1040 if (locator.startsWith(LocatorType.ID.getStartsWith())) {1041 if (caseInsensitiveConverter != null) {1042 by = caseInsensitiveConverter.convert(by);1043 } else {1044 by = By.id(String.format(StringUtils.remove(locator, LocatorType.ID.getStartsWith()), objects));1045 }1046 }1047 if (locator.startsWith(LocatorType.NAME.getStartsWith())) {1048 if (caseInsensitiveConverter != null) {1049 by = caseInsensitiveConverter.convert(by);1050 } else {1051 by = By.id(String.format(StringUtils.remove(locator, LocatorType.NAME.getStartsWith()), objects));1052 }1053 }1054 if (locator.startsWith(LocatorType.XPATH.getStartsWith())) {1055 if (caseInsensitiveConverter != null) {1056 by = caseInsensitiveConverter.convert(by);1057 } else {1058 by = By.xpath(String.format(StringUtils.remove(locator, LocatorType.XPATH.getStartsWith()), objects));1059 }1060 }1061 if (locator.startsWith(LocatorType.LINKTEXT.getStartsWith())) {1062 if (caseInsensitiveConverter != null) {1063 by = caseInsensitiveConverter.convert(by);1064 } else {1065 by = By.xpath(String.format(StringUtils.remove(locator, LocatorType.LINKTEXT.getStartsWith()), objects));1066 }1067 }1068 if (locator.startsWith("partialLinkText: ")) {1069 by = By.partialLinkText(String.format(StringUtils.remove(locator, "partialLinkText: "), objects));1070 }1071 if (locator.startsWith("css: ")) {1072 by = By.cssSelector(String.format(StringUtils.remove(locator, "css: "), objects));1073 }1074 if (locator.startsWith("tagName: ")) {1075 by = By.tagName(String.format(StringUtils.remove(locator, "tagName: "), objects));1076 }1077 /*1078 * All ClassChain locators start from **. e.g FindBy(xpath = "**'/XCUIElementTypeStaticText[`name CONTAINS[cd] '%s'`]")1079 */1080 if (locator.startsWith("By.IosClassChain: **")) {1081 by = MobileBy.iOSClassChain(String.format(StringUtils.remove(locator, "By.IosClassChain: "), objects));1082 }1083 if (locator.startsWith("By.IosNsPredicate: **")) {1084 by = MobileBy.iOSNsPredicateString(String.format(StringUtils.remove(locator, "By.IosNsPredicate: "), objects));1085 }1086 if (locator.startsWith("By.AccessibilityId: ")) {1087 by = MobileBy.AccessibilityId(String.format(StringUtils.remove(locator, "By.AccessibilityId: "), objects));1088 }1089 if (locator.startsWith("By.Image: ")) {1090 String formattedLocator = String.format(StringUtils.remove(locator, "By.Image: "), objects);1091 Path path = Paths.get(formattedLocator);1092 LOGGER.debug("Formatted locator is : " + formattedLocator);1093 String base64image;1094 try {1095 base64image = new String(Base64.encode(Files.readAllBytes(path)));1096 } catch (IOException e) {1097 throw new RuntimeException(1098 "Error while reading image file after formatting. Formatted locator : " + formattedLocator, e);1099 }1100 LOGGER.debug("Base64 image representation has benn successfully obtained after formatting.");1101 by = MobileBy.image(base64image);1102 }1103 if (locator.startsWith("By.AndroidUIAutomator: ")) {1104 by = MobileBy.AndroidUIAutomator(String.format(StringUtils.remove(locator, "By.AndroidUIAutomator: "), objects));1105 LOGGER.debug("Formatted locator is : " + by.toString());1106 }1107 return new ExtendedWebElement(by, name, this.driver, this.searchContext, objects);1108 }1109 /**1110 * Pause for specified timeout.1111 * 1112 * @param timeout in seconds.1113 */1114 public void pause(long timeout) {1115 CommonUtils.pause(timeout);1116 }1117 public void pause(double timeout) {1118 CommonUtils.pause(timeout);1119 }1120 1121 public interface ActionSteps {1122 void doClick();1123 1124 void doClickByJs();1125 1126 void doClickByActions();1127 1128 void doDoubleClick();1129 void doRightClick();1130 1131 void doHover(Integer xOffset, Integer yOffset);1132 void doType(String text);1133 void doSendKeys(Keys keys);1134 void doAttachFile(String filePath);1135 void doCheck();1136 void doUncheck();1137 1138 boolean doIsChecked();1139 1140 String doGetText();1141 Point doGetLocation();1142 Dimension doGetSize();1143 String doGetAttribute(String name);1144 boolean doSelect(String text);1145 boolean doSelectValues(final String[] values);1146 boolean doSelectByMatcher(final BaseMatcher<String> matcher);1147 boolean doSelectByPartialText(final String partialSelectText);1148 boolean doSelectByIndex(final int index);1149 1150 String doGetSelectedValue();1151 1152 List<String> doGetSelectedValues();1153 }1154 private Object executeAction(ACTION_NAME actionName, ActionSteps actionSteps, Object... inputArgs) {1155 Object result = null;1156 switch (actionName) {1157 case CLICK:1158 actionSteps.doClick();1159 break;1160 case CLICK_BY_JS:1161 actionSteps.doClickByJs();1162 break;1163 case CLICK_BY_ACTIONS:1164 actionSteps.doClickByActions();1165 break;1166 case DOUBLE_CLICK:1167 actionSteps.doDoubleClick();1168 break;1169 case HOVER:1170 actionSteps.doHover((Integer) inputArgs[0], (Integer) inputArgs[1]);1171 break;1172 case RIGHT_CLICK:1173 actionSteps.doRightClick();1174 break;1175 case GET_TEXT:1176 result = actionSteps.doGetText();1177 break;1178 case GET_LOCATION:1179 result = actionSteps.doGetLocation();1180 break;1181 case GET_SIZE:1182 result = actionSteps.doGetSize();1183 break;1184 case GET_ATTRIBUTE:1185 result = actionSteps.doGetAttribute((String) inputArgs[0]);1186 break;1187 case SEND_KEYS:1188 actionSteps.doSendKeys((Keys) inputArgs[0]);1189 break;1190 case TYPE:1191 actionSteps.doType((String) inputArgs[0]);1192 break;1193 case ATTACH_FILE:1194 actionSteps.doAttachFile((String) inputArgs[0]);1195 break;1196 case CHECK:1197 actionSteps.doCheck();1198 break;1199 case UNCHECK:1200 actionSteps.doUncheck();1201 break;1202 case IS_CHECKED:1203 result = actionSteps.doIsChecked();1204 break;1205 case SELECT:1206 result = actionSteps.doSelect((String) inputArgs[0]);1207 break;1208 case SELECT_VALUES:1209 result = actionSteps.doSelectValues((String[]) inputArgs);1210 break;1211 case SELECT_BY_MATCHER:1212 result = actionSteps.doSelectByMatcher((BaseMatcher<String>) inputArgs[0]);1213 break;1214 case SELECT_BY_PARTIAL_TEXT:1215 result = actionSteps.doSelectByPartialText((String) inputArgs[0]);1216 break;1217 case SELECT_BY_INDEX:1218 result = actionSteps.doSelectByIndex((int) inputArgs[0]);1219 break;1220 case GET_SELECTED_VALUE:1221 result = actionSteps.doGetSelectedValue();1222 break;1223 case GET_SELECTED_VALUES:1224 result = actionSteps.doGetSelectedValues();1225 break;1226 default:1227 Assert.fail("Unsupported UI action name" + actionName.toString());1228 break;1229 }1230 return result;1231 }1232 /**1233 * doAction on element.1234 *1235 * @param actionName1236 * ACTION_NAME1237 * @param timeout1238 * long1239 * @param waitCondition1240 * to check element conditions before action1241 * @return1242 * Object1243 */1244 private Object doAction(ACTION_NAME actionName, long timeout, ExpectedCondition<?> waitCondition) {1245 // [VD] do not remove null args otherwise all actions without arguments will be broken!1246 Object nullArgs = null;1247 return doAction(actionName, timeout, waitCondition, nullArgs);1248 }1249 private Object doAction(ACTION_NAME actionName, long timeout, ExpectedCondition<?> waitCondition,1250 Object...inputArgs) {1251 1252 if (waitCondition != null) {1253 //do verification only if waitCondition is not null1254 if (!waitUntil(waitCondition, timeout)) {1255 //TODO: think about raising exception otherwise we do extra call and might wait and hangs especially for mobile/appium1256 LOGGER.error(Messager.ELEMENT_CONDITION_NOT_VERIFIED.getMessage(actionName.getKey(), getNameWithLocator()));1257 }1258 }1259 1260 if (isLocalized) {1261 isLocalized = false; // single verification is enough for this particular element1262 L10N.verify(this);1263 }1264 Object output = null;1265 try {1266 this.element = getElement();1267 output = overrideAction(actionName, inputArgs);1268 } catch (StaleElementReferenceException e) {1269 //TODO: analyze mobile testing for staled elements. Potentially it should be fixed by appium java client already1270 // sometime Appium instead printing valid StaleElementException generate java.lang.ClassCastException:1271 // com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to java.lang.String1272 LOGGER.debug("catched StaleElementReferenceException: ", e);1273 // try to find again using driver context and do action1274 element = this.findElement();1275 output = overrideAction(actionName, inputArgs);1276 }1277 return output;1278 }1279 // single place for all supported UI actions in carina core1280 private Object overrideAction(ACTION_NAME actionName, Object...inputArgs) {1281 Object output = executeAction(actionName, new ActionSteps() {1282 @Override1283 public void doClick() {1284 DriverListener.setMessages(Messager.ELEMENT_CLICKED.getMessage(getName()),1285 Messager.ELEMENT_NOT_CLICKED.getMessage(getNameWithLocator()));1286 element.click();1287 }1288 1289 @Override1290 public void doClickByJs() {1291 DriverListener.setMessages(Messager.ELEMENT_CLICKED.getMessage(getName()),1292 Messager.ELEMENT_NOT_CLICKED.getMessage(getNameWithLocator()));1293 LOGGER.info("Do click by JavascriptExecutor for element: " + getNameWithLocator());1294 JavascriptExecutor executor = (JavascriptExecutor) getDriver();1295 executor.executeScript("arguments[0].click();", element);1296 }1297 1298 @Override1299 public void doClickByActions() {1300 DriverListener.setMessages(Messager.ELEMENT_CLICKED.getMessage(getName()),1301 Messager.ELEMENT_NOT_CLICKED.getMessage(getNameWithLocator()));1302 LOGGER.info("Do click by Actions for element: " + getNameWithLocator());1303 Actions actions = new Actions(getDriver());1304 actions.moveToElement(element).click().perform();1305 } 1306 1307 @Override1308 public void doDoubleClick() {1309 DriverListener.setMessages(Messager.ELEMENT_DOUBLE_CLICKED.getMessage(getName()),1310 Messager.ELEMENT_NOT_DOUBLE_CLICKED.getMessage(getNameWithLocator()));1311 1312 WebDriver drv = getDriver();1313 Actions action = new Actions(drv);1314 action.moveToElement(element).doubleClick(element).build().perform();1315 }1316 1317 @Override1318 public void doHover(Integer xOffset, Integer yOffset) {1319 DriverListener.setMessages(Messager.ELEMENT_HOVERED.getMessage(getName()),1320 Messager.ELEMENT_NOT_HOVERED.getMessage(getNameWithLocator()));1321 1322 WebDriver drv = getDriver();1323 Actions action = new Actions(drv);1324 if (xOffset != null && yOffset!= null) {1325 action.moveToElement(element, xOffset, yOffset).build().perform();1326 } else {1327 action.moveToElement(element).build().perform();1328 }1329 }1330 1331 @Override1332 public void doSendKeys(Keys keys) {1333 DriverListener.setMessages(Messager.KEYS_SEND_TO_ELEMENT.getMessage(keys.toString(), getName()),1334 Messager.KEYS_NOT_SEND_TO_ELEMENT.getMessage(keys.toString(), getNameWithLocator()));1335 element.sendKeys(keys);1336 }1337 @Override1338 public void doType(String text) {1339 final String decryptedText = cryptoTool.decryptByPattern(text, CRYPTO_PATTERN);1340/* if (!element.getText().isEmpty()) {1341 DriverListener.setMessages(Messager.KEYS_CLEARED_IN_ELEMENT.getMessage(getName()),1342 Messager.KEYS_NOT_CLEARED_IN_ELEMENT.getMessage(getNameWithLocator()));1343 element.clear();1344 }1345*/1346 DriverListener.setMessages(Messager.KEYS_CLEARED_IN_ELEMENT.getMessage(getName()),1347 Messager.KEYS_NOT_CLEARED_IN_ELEMENT.getMessage(getNameWithLocator()));1348 element.clear();1349 String textLog = (!decryptedText.equals(text) ? "********" : text);1350 DriverListener.setMessages(Messager.KEYS_SEND_TO_ELEMENT.getMessage(textLog, getName()),1351 Messager.KEYS_NOT_SEND_TO_ELEMENT.getMessage(textLog, getNameWithLocator()));1352 element.sendKeys(decryptedText);1353 }1354 @Override1355 public void doAttachFile(String filePath) {1356 final String decryptedText = cryptoTool.decryptByPattern(filePath, CRYPTO_PATTERN);1357 String textLog = (!decryptedText.equals(filePath) ? "********" : filePath);1358 DriverListener.setMessages(Messager.FILE_ATTACHED.getMessage(textLog, getName()),1359 Messager.FILE_NOT_ATTACHED.getMessage(textLog, getNameWithLocator()));1360 ((JavascriptExecutor) getDriver()).executeScript("arguments[0].style.display = 'block';", element);1361 ((RemoteWebDriver) castDriver(getDriver())).setFileDetector(new LocalFileDetector());1362 element.sendKeys(decryptedText);1363 }1364 @Override1365 public String doGetText() {1366 String text = element.getText();1367 LOGGER.debug(Messager.ELEMENT_ATTRIBUTE_FOUND.getMessage("Text", text, getName()));1368 return text;1369 }1370 @Override1371 public Point doGetLocation() {1372 Point point = element.getLocation();1373 LOGGER.debug(Messager.ELEMENT_ATTRIBUTE_FOUND.getMessage("Location", point.toString(), getName()));1374 return point;1375 }1376 @Override1377 public Dimension doGetSize() {1378 Dimension dim = element.getSize();1379 LOGGER.debug(Messager.ELEMENT_ATTRIBUTE_FOUND.getMessage("Size", dim.toString(), getName()));1380 return dim;1381 }1382 @Override1383 public String doGetAttribute(String name) {1384 String attribute = element.getAttribute(name);1385 LOGGER.debug(Messager.ELEMENT_ATTRIBUTE_FOUND.getMessage(name, attribute, getName()));1386 return attribute;1387 }1388 @Override1389 public void doRightClick() {1390 DriverListener.setMessages(Messager.ELEMENT_RIGHT_CLICKED.getMessage(getName()),1391 Messager.ELEMENT_NOT_RIGHT_CLICKED.getMessage(getNameWithLocator()));1392 1393 WebDriver drv = getDriver();1394 Actions action = new Actions(drv);1395 action.moveToElement(element).contextClick(element).build().perform();1396 }1397 @Override1398 public void doCheck() {1399 DriverListener.setMessages(Messager.CHECKBOX_CHECKED.getMessage(getName()), null);1400 1401 boolean isSelected = element.isSelected();1402 if (element.getAttribute("checked") != null) {1403 isSelected |= element.getAttribute("checked").equalsIgnoreCase("true");1404 }1405 1406 if (!isSelected) {1407 click();1408 }1409 }1410 @Override1411 public void doUncheck() {1412 DriverListener.setMessages(Messager.CHECKBOX_UNCHECKED.getMessage(getName()), null);1413 1414 boolean isSelected = element.isSelected();1415 if (element.getAttribute("checked") != null) {1416 isSelected |= element.getAttribute("checked").equalsIgnoreCase("true");1417 }1418 1419 if (isSelected) {1420 click();1421 }1422 }1423 1424 @Override1425 public boolean doIsChecked() {1426 1427 boolean res = element.isSelected();1428 if (element.getAttribute("checked") != null) {1429 res |= element.getAttribute("checked").equalsIgnoreCase("true");1430 }1431 1432 return res;1433 }1434 1435 @Override1436 public boolean doSelect(String text) {1437 final String decryptedSelectText = cryptoTool.decryptByPattern(text, CRYPTO_PATTERN);1438 1439 String textLog = (!decryptedSelectText.equals(text) ? "********" : text);1440 1441 DriverListener.setMessages(Messager.SELECT_BY_TEXT_PERFORMED.getMessage(textLog, getName()),1442 Messager.SELECT_BY_TEXT_NOT_PERFORMED.getMessage(textLog, getNameWithLocator()));1443 1444 final Select s = new Select(getElement());1445 // [VD] do not use selectByValue as modern controls could have only visible value without value1446 s.selectByVisibleText(decryptedSelectText);1447 return true;1448 }1449 @Override1450 public boolean doSelectValues(String[] values) {1451 boolean result = true;1452 for (String value : values) {1453 if (!select(value)) {1454 result = false;1455 }1456 }1457 return result;1458 }1459 @Override1460 public boolean doSelectByMatcher(BaseMatcher<String> matcher) {1461 1462 DriverListener.setMessages(Messager.SELECT_BY_MATCHER_TEXT_PERFORMED.getMessage(matcher.toString(), getName()),1463 Messager.SELECT_BY_MATCHER_TEXT_NOT_PERFORMED.getMessage(matcher.toString(), getNameWithLocator()));1464 1465 final Select s = new Select(getElement());1466 String fullTextValue = null;1467 for (WebElement option : s.getOptions()) {1468 if (matcher.matches(option.getText())) {1469 fullTextValue = option.getText();1470 break;1471 }1472 }1473 s.selectByVisibleText(fullTextValue);1474 return true;1475 }1476 @Override1477 public boolean doSelectByPartialText(String partialSelectText) {1478 1479 DriverListener.setMessages(1480 Messager.SELECT_BY_TEXT_PERFORMED.getMessage(partialSelectText, getName()),1481 Messager.SELECT_BY_TEXT_NOT_PERFORMED.getMessage(partialSelectText, getNameWithLocator()));1482 1483 final Select s = new Select(getElement());1484 String fullTextValue = null;1485 for (WebElement option : s.getOptions()) {1486 if (option.getText().contains(partialSelectText)) {1487 fullTextValue = option.getText();1488 break;1489 }1490 }1491 s.selectByVisibleText(fullTextValue);1492 return true;1493 }1494 @Override1495 public boolean doSelectByIndex(int index) {1496 DriverListener.setMessages(1497 Messager.SELECT_BY_INDEX_PERFORMED.getMessage(String.valueOf(index), getName()),1498 Messager.SELECT_BY_INDEX_NOT_PERFORMED.getMessage(String.valueOf(index), getNameWithLocator()));1499 1500 1501 final Select s = new Select(getElement());1502 s.selectByIndex(index);1503 return true;1504 }1505 @Override1506 public String doGetSelectedValue() {1507 final Select s = new Select(getElement());1508 return s.getAllSelectedOptions().get(0).getText();1509 }1510 @Override1511 public List<String> doGetSelectedValues() {1512 final Select s = new Select(getElement());1513 List<String> values = new ArrayList<String>();1514 for (WebElement we : s.getAllSelectedOptions()) {1515 values.add(we.getText());1516 }1517 return values;1518 }1519 1520 }, inputArgs);1521 return output;1522 }1523 public WebDriver getDriver() {1524 if (driver == null) {1525 LOGGER.error("There is no any initialized driver for ExtendedWebElement: " + getNameWithLocator());1526 throw new RuntimeException(1527 "Driver isn't initialized. Review stacktrace to analyze why driver is not populated correctly via reflection!");1528 }1529 return driver;1530 }1531 1532 private WebDriver castDriver(WebDriver drv) {1533 if (drv instanceof EventFiringWebDriver) {1534 drv = ((EventFiringWebDriver) drv).getWrappedDriver();1535 }1536 return drv;1537 }1538 1539 //TODO: investigate how can we merge the similar functionality in ExtendedWebElement, DriverHelper and LocalizedAnnotations1540 public By generateByForList(By by, int index) {1541 String locator = by.toString();1542 By resBy = null;1543 if (locator.startsWith(LocatorType.ID.getStartsWith())) {1544 resBy = By.id(StringUtils.remove(locator, LocatorType.ID.getStartsWith()) + "[" + index + "]");1545 }1546 if (locator.startsWith(LocatorType.NAME.getStartsWith())) {1547 resBy = By.name(StringUtils.remove(locator, LocatorType.NAME.getStartsWith()) + "[" + index + "]");1548 }1549 if (locator.startsWith(LocatorType.XPATH.getStartsWith())) {1550 resBy = By.xpath(StringUtils.remove(locator, LocatorType.XPATH.getStartsWith()) + "[" + index + "]");1551 }1552 if (locator.startsWith(LocatorType.LINKTEXT.getStartsWith())) {1553 resBy = By.linkText(StringUtils.remove(locator, LocatorType.LINKTEXT.getStartsWith()) + "[" + index + "]");1554 }1555 if (locator.startsWith("partialLinkText: ")) {1556 resBy = By.partialLinkText(StringUtils.remove(locator, "partialLinkText: ") + "[" + index + "]");1557 }1558 if (locator.startsWith("css: ")) {1559 resBy = By.cssSelector(StringUtils.remove(locator, "css: ") + ":nth-child(" + index + ")");1560 }1561 1562 if (locator.startsWith("By.cssSelector: ")) {1563 resBy = By.cssSelector(StringUtils.remove(locator, "By.cssSelector: ") + ":nth-child(" + index + ")");1564 }1565 if (locator.startsWith("tagName: ")) {1566 resBy = By.tagName(StringUtils.remove(locator, "tagName: ") + "[" + index + "]");1567 }1568 /*1569 * All ClassChain locators start from **. e.g FindBy(xpath = "**'/XCUIElementTypeStaticText[`name CONTAINS[cd] '%s'`]")1570 */1571 if (locator.startsWith("By.IosClassChain: **")) {1572 resBy = MobileBy.iOSClassChain(StringUtils.remove(locator, "By.IosClassChain: ") + "[" + index + "]");1573 }1574 1575 if (locator.startsWith("By.IosNsPredicate: **")) {1576 resBy = MobileBy.iOSNsPredicateString(StringUtils.remove(locator, "By.IosNsPredicate: ") + "[" + index + "]");1577 }1578 if (locator.startsWith("By.AccessibilityId: ")) {1579 resBy = MobileBy.AccessibilityId(StringUtils.remove(locator, "By.AccessibilityId: ") + "[" + index + "]");1580 }1581 return resBy;1582 }1583 /**1584 * Get element waiting condition depends on element loading strategy1585 */1586 private ExpectedCondition<?> getDefaultCondition(By by) {1587 // generate the most popular waitCondition to check if element visible or present1588 ExpectedCondition<?> waitCondition = null;1589 // need to get root element from with we will try to find element by By1590 switch (loadingStrategy) {1591 case BY_PRESENCE: {1592 if (element != null) {1593 if (searchContext instanceof RemoteWebElement) {1594 WebElement contextElement = searchContext.findElement(By.xpath("."));1595 waitCondition = ExpectedConditions.or(ExpectedConditions.presenceOfNestedElementLocatedBy(contextElement, by),1596 ExpectedConditions.visibilityOf(element));1597 } else {1598 waitCondition = ExpectedConditions.or(ExpectedConditions.presenceOfElementLocated(by),1599 ExpectedConditions.visibilityOf(element));1600 }1601 } else {1602 if (searchContext instanceof RemoteWebElement) {1603 WebElement contextElement = searchContext.findElement(By.xpath("."));1604 waitCondition = ExpectedConditions.presenceOfNestedElementLocatedBy(contextElement, by);1605 } else {1606 waitCondition = ExpectedConditions.presenceOfElementLocated(by);1607 }1608 }1609 break;1610 }1611 case BY_VISIBILITY: {1612 if (element != null) {1613 if (searchContext instanceof RemoteWebElement) {1614 WebElement contextElement = searchContext.findElement(By.xpath("."));1615 waitCondition = ExpectedConditions.or(ExpectedConditions.visibilityOfNestedElementsLocatedBy(contextElement, by),1616 ExpectedConditions.visibilityOf(element));1617 } else {1618 waitCondition = ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(by),1619 ExpectedConditions.visibilityOf(element));1620 }1621 } else {1622 if (searchContext instanceof RemoteWebElement) {1623 WebElement contextElement = searchContext.findElement(By.xpath("."));1624 waitCondition = ExpectedConditions.visibilityOfNestedElementsLocatedBy(contextElement, by);1625 } else {1626 waitCondition = ExpectedConditions.visibilityOfElementLocated(by);1627 }1628 }1629 break;1630 }1631 case BY_PRESENCE_OR_VISIBILITY:1632 if (element != null) {1633 if (searchContext instanceof RemoteWebElement) {1634 WebElement contextElement = searchContext.findElement(By.xpath("."));1635 waitCondition = ExpectedConditions.or(ExpectedConditions.presenceOfNestedElementLocatedBy(contextElement, by),1636 ExpectedConditions.visibilityOfNestedElementsLocatedBy(contextElement, by),1637 ExpectedConditions.visibilityOf(element));1638 } else {1639 waitCondition = ExpectedConditions.or(ExpectedConditions.presenceOfElementLocated(by),1640 ExpectedConditions.visibilityOfElementLocated(by),1641 ExpectedConditions.visibilityOf(element));1642 }1643 } else {1644 if (searchContext instanceof RemoteWebElement) {1645 WebElement contextElement = searchContext.findElement(By.xpath("."));1646 waitCondition = ExpectedConditions.or(ExpectedConditions.presenceOfNestedElementLocatedBy(contextElement, by),1647 ExpectedConditions.visibilityOfNestedElementsLocatedBy(contextElement, by));1648 } else {1649 waitCondition = ExpectedConditions.or(ExpectedConditions.presenceOfElementLocated(by),1650 ExpectedConditions.visibilityOfElementLocated(by));1651 }1652 }1653 break;1654 }1655 return waitCondition;1656 }1657 1658 private long getRetryInterval(long timeout) {1659 long retryInterval = RETRY_TIME;1660 if (timeout >= 3 && timeout <= 10) {1661 retryInterval = 500;1662 }1663 if (timeout > 10) {1664 retryInterval = 1000;1665 }1666 return retryInterval;1667 }1668}...

Full Screen

Full Screen

Source:DriverHelper.java Github

copy

Full Screen

...875 * Accepts alert modal.876 */877 public void acceptAlert() {878 WebDriver drv = getDriver();879 long retryInterval = getRetryInterval(EXPLICIT_TIMEOUT);880 Wait<WebDriver> wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, retryInterval);881 try {882 wait.until((Function<WebDriver, Object>) dr -> isAlertPresent());883 drv.switchTo().alert().accept();884 Messager.ALERT_ACCEPTED.info("");885 } catch (Exception e) {886 Messager.ALERT_NOT_ACCEPTED.error("");887 }888 }889 /**890 * Cancels alert modal.891 */892 public void cancelAlert() {893 WebDriver drv = getDriver();894 long retryInterval = getRetryInterval(EXPLICIT_TIMEOUT);895 Wait<WebDriver> wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, retryInterval);896 try {897 wait.until((Function<WebDriver, Object>) dr -> isAlertPresent());898 drv.switchTo().alert().dismiss();899 Messager.ALERT_CANCELED.info("");900 } catch (Exception e) {901 Messager.ALERT_NOT_CANCELED.error("");902 }903 }904 /**905 * Checks that alert modal is shown.906 * 907 * @return whether the alert modal present.908 */909 public boolean isAlertPresent() {910 try {911 getDriver().switchTo().alert();912 return true;913 } catch (NoAlertPresentException Ex) {914 return false;915 }916 }917 // --------------------------------------------------------------------------918 // Methods from v1.0919 // --------------------------------------------------------------------------920 public boolean isPageOpened(final AbstractPage page) {921 return isPageOpened(page, EXPLICIT_TIMEOUT);922 }923 public boolean isPageOpened(final AbstractPage page, long timeout) {924 boolean result;925 final WebDriver drv = getDriver();926 927 long retryInterval = getRetryInterval(timeout); 928 Wait<WebDriver> wait = new WebDriverWait(drv, timeout, retryInterval);929 try {930 wait.until((Function<WebDriver, Object>) dr -> LogicUtils.isURLEqual(page.getPageURL(), drv.getCurrentUrl()));931 result = true;932 } catch (Exception e) {933 result = false;934 }935 if (!result) {936 LOGGER.warn(String.format("Actual URL differs from expected one. Expected '%s' but found '%s'",937 page.getPageURL(), drv.getCurrentUrl()));938 }939 return result;940 }941 /**942 * Executes a script on an element943 * 944 * Really should only be used when the web driver is sucking at exposing945 * functionality natively946 * 947 * @param script948 * The script to execute949 * @param element950 * The target of the script, referenced as arguments[0]951 * 952 * @return Object953 */954 public Object trigger(String script, WebElement element) {955 return ((JavascriptExecutor) getDriver()).executeScript(script, element);956 }957 /**958 * Executes a script959 * 960 * Really should only be used when the web driver is sucking at exposing961 * functionality natively962 * 963 * @param script964 * The script to execute965 * 966 * @return Object967 */968 public Object trigger(String script) {969 return ((JavascriptExecutor) getDriver()).executeScript(script);970 }971 /**972 * Opens a new tab for the given URL973 * 974 * @param url975 * The URL to976 * @throws RuntimeException977 * If unable to open tab978 */979 public void openTab(String url) {980 final String decryptedURL = cryptoTool.decryptByPattern(url, CRYPTO_PATTERN);981 String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";982 Object element = trigger(String.format(script, decryptedURL));983 if (element instanceof WebElement) {984 WebElement anchor = (WebElement) element;985 anchor.click();986 trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);987 } else {988 throw new RuntimeException("Unable to open tab");989 }990 }991 public void switchWindow() throws NoSuchWindowException {992 WebDriver drv = getDriver();993 Set<String> handles = drv.getWindowHandles();994 String current = drv.getWindowHandle();995 if (handles.size() > 1) {996 handles.remove(current);997 }998 String newTab = handles.iterator().next();999 drv.switchTo().window(newTab);1000 }1001 // --------------------------------------------------------------------------1002 // Base UI validations1003 // --------------------------------------------------------------------------1004 public void assertElementPresent(final ExtendedWebElement extWebElement) {1005 assertElementPresent(extWebElement, EXPLICIT_TIMEOUT);1006 }1007 public void assertElementPresent(final ExtendedWebElement extWebElement, long timeout) {1008 extWebElement.assertElementPresent(timeout);1009 }1010 public void assertElementWithTextPresent(final ExtendedWebElement extWebElement, final String text) {1011 assertElementWithTextPresent(extWebElement, text, EXPLICIT_TIMEOUT);1012 }1013 public void assertElementWithTextPresent(final ExtendedWebElement extWebElement, final String text, long timeout) {1014 extWebElement.assertElementWithTextPresent(text, timeout);1015 }1016 // --------------------------------------------------------------------------1017 // Helpers1018 // --------------------------------------------------------------------------1019 1020 /**1021 * Find Extended Web Element on page using By.1022 * 1023 * @deprecated1024 * @param by1025 * Selenium By locator1026 * @return ExtendedWebElement if exists otherwise null.1027 */1028 @Deprecated(since = "7.4.21", forRemoval = true)1029 public ExtendedWebElement findExtendedWebElement(By by) {1030 return findExtendedWebElement(by, by.toString(), EXPLICIT_TIMEOUT);1031 }1032 /**1033 * Find Extended Web Element on page using By.1034 *1035 * @deprecated1036 * @param by1037 * Selenium By locator1038 * @param timeout to wait1039 * @return ExtendedWebElement if exists otherwise null.1040 */1041 @Deprecated(since = "7.4.21", forRemoval = true)1042 public ExtendedWebElement findExtendedWebElement(By by, long timeout) {1043 return findExtendedWebElement(by, by.toString(), timeout);1044 }1045 /**1046 * Find Extended Web Element on page using By.1047 * 1048 * @deprecated1049 * @param by1050 * Selenium By locator1051 * @param name1052 * Element name1053 * @return ExtendedWebElement if exists otherwise null.1054 */1055 @Deprecated(since = "7.4.21", forRemoval = true)1056 public ExtendedWebElement findExtendedWebElement(final By by, String name) {1057 return findExtendedWebElement(by, name, EXPLICIT_TIMEOUT);1058 }1059 /**1060 * Find Extended Web Element on page using By.1061 *1062 * @deprecated1063 * @param by1064 * Selenium By locator1065 * @param name1066 * Element name1067 * @param timeout1068 * Timeout to find1069 * @return ExtendedWebElement if exists otherwise null.1070 */1071 @Deprecated(since = "7.4.21", forRemoval = true)1072 public ExtendedWebElement findExtendedWebElement(final By by, String name, long timeout) {1073 DriverListener.setMessages(Messager.ELEMENT_FOUND.getMessage(name),1074 Messager.ELEMENT_NOT_FOUND.getMessage(name));1075 1076 if (!waitUntil(ExpectedConditions.presenceOfElementLocated(by), timeout)) {1077 Messager.ELEMENT_NOT_FOUND.error(name);1078 return null;1079 }1080 return new ExtendedWebElement(by, name, getDriver(), getDriver());1081 }1082 /**1083 * Find List of Extended Web Elements on page using By and explicit timeout.1084 *1085 * @deprecated1086 * @param by1087 * Selenium By locator1088 * @return List of ExtendedWebElement.1089 */1090 @Deprecated(since = "7.4.21", forRemoval = true)1091 public List<ExtendedWebElement> findExtendedWebElements(By by) {1092 return findExtendedWebElements(by, EXPLICIT_TIMEOUT);1093 }1094 /**1095 * Find List of Extended Web Elements on page using By.1096 *1097 * @deprecated1098 * 1099 * @param by1100 * Selenium By locator1101 * @param timeout1102 * Timeout to find1103 * @return List of ExtendedWebElement.1104 */1105 @Deprecated(since = "7.4.21", forRemoval = true)1106 public List<ExtendedWebElement> findExtendedWebElements(final By by, long timeout) {1107 List<ExtendedWebElement> extendedWebElements = new ArrayList<ExtendedWebElement>();1108 List<WebElement> webElements = new ArrayList<WebElement>();1109 String name = "undefined";1110 if (!waitUntil(ExpectedConditions.presenceOfElementLocated(by), timeout)) {1111 Messager.ELEMENT_NOT_FOUND.info(name);1112 return extendedWebElements;1113 }1114 1115 webElements = getDriver().findElements(by);1116 int i = 1;1117 for (WebElement element : webElements) {1118 try {1119 name = element.getText();1120 } catch (Exception e) {1121 /* do nothing and keep 'undefined' for control name */1122 }1123 ExtendedWebElement tempElement = new ExtendedWebElement(element, name);1124 tempElement.setBy(tempElement.generateByForList(by, i));1125 extendedWebElements.add(tempElement); 1126 i++;1127 }1128 return extendedWebElements;1129 }1130 protected void setDriver(WebDriver driver) {1131 this.driver = driver;1132 }1133 public WebDriver getDriver() {1134 if (driver == null) {1135 long currentThreadId = Thread.currentThread().getId();1136 LOGGER.error("There is no any initialized driver for thread: " + currentThreadId);1137 throw new RuntimeException("Driver isn't initialized.");1138 }1139 return driver;1140 }1141 1142 /**1143 * Wait until any condition happens.1144 *1145 * @param condition - ExpectedCondition.1146 * @param timeout - timeout.1147 * @return true if condition happen.1148 */1149 public boolean waitUntil(ExpectedCondition<?> condition, long timeout) {1150 boolean result;1151 long startMillis = 0;1152 final WebDriver drv = getDriver();1153 1154 long retryInterval = getRetryInterval(timeout);1155 Wait<WebDriver> wait = new WebDriverWait(drv, timeout, retryInterval);1156 try {1157 startMillis = System.currentTimeMillis();1158 wait.until(condition);1159 result = true;1160 LOGGER.debug("waitUntil: finished true...");1161 } catch (NoSuchElementException | TimeoutException e) {1162 // don't write exception even in debug mode1163 LOGGER.debug("waitUntil: NoSuchElementException | TimeoutException e..." + condition.toString());1164 result = false;1165 } catch (Exception e) {1166 LOGGER.error("waitUntil: " + condition.toString(), e);1167 result = false;1168 } finally {1169 long timePassed = System.currentTimeMillis() - startMillis;1170 // timePassed is time in ms timeout in sec so we have to adjust1171 if (timePassed > 2 * timeout * 1000) {1172 LOGGER.error("Your retry_interval is too low: " + RETRY_TIME + " ms! Increase it or upgrade your hardware");1173 }1174 }1175 return result;1176 }1177 1178 //TODO: uncomment javadoc when T could be described correctly1179 /*1180 * Method to handle SocketException due to okhttp factory initialization (java client 6.*).1181 * Second execution of the same function works as expected.1182 * 1183 * @param T The expected class of the supplier.1184 * @param supplier Object 1185 * @return result Object 1186 */1187 public <T> T performIgnoreException(Supplier<T> supplier) {1188 try {1189 LOGGER.debug("Command will be performed with the exception ignoring");1190 return supplier.get();1191 } catch (WebDriverException e) {1192 LOGGER.info("Webdriver exception has been fired. One more attempt to execute action.", e);1193 LOGGER.info(supplier.toString());1194 return supplier.get();1195 }1196 1197 }1198 1199 private String getUrl() {1200 String url = "";1201 if (Configuration.getEnvArg(Parameter.URL.getKey()).isEmpty()) {1202 url = Configuration.get(Parameter.URL);1203 } else {1204 url = Configuration.getEnvArg(Parameter.URL.getKey());1205 }1206 return url;1207 }1208 1209 private static void setPageLoadTimeout(WebDriver drv, long timeout) {1210 try {1211 drv.manage().timeouts().pageLoadTimeout(timeout, TimeUnit.SECONDS);1212 } catch (UnsupportedCommandException e) {1213 //TODO: review upcoming appium 2.0 changes1214 LOGGER.debug("Appium: Not implemented yet for pageLoad timeout!");1215 }1216 1217 }1218 1219 private long getPageLoadTimeout() {1220 long timeout = 300;1221 // #1705: limit pageLoadTimeout driver timeout by idleTimeout1222// if (!R.CONFIG.get("capabilities.idleTimeout").isEmpty()) {1223// long idleTimeout = R.CONFIG.getLong("capabilities.idleTimeout");1224// if (idleTimeout < timeout) {1225// timeout = idleTimeout;1226// }1227// }1228 return timeout;1229 }1230 private long getRetryInterval(long timeout) {1231 long retryInterval = RETRY_TIME;1232 if (timeout >= 3 && timeout <= 10) {1233 retryInterval = 500;1234 }1235 if (timeout > 10) {1236 retryInterval = 1000;1237 }1238 return retryInterval;1239 }1240}...

Full Screen

Full Screen

getRetryInterval

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 org.openqa.selenium.support.PageFactory;5import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;6import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy;7import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy.OpeningStrategy;8import com.qaprosoft.carina.core.foundation.webdriver.listener.EventFiringDecorator;9@PageOpeningStrategy(OpeningStrategy.BY_ELEMENT)10public class HomePage extends HomePageBase {11 private ExtendedWebElement header;12 public HomePage(WebDriver driver) {13 super(driver);14 PageFactory.initElements(new EventFiringDecorator(driver), this);15 }16 public boolean isPageOpened() {17 return header.isPresent();18 }19}20package com.qaprosoft.carina.demo.gui.pages;21import org.openqa.selenium.WebDriver;22import org.openqa.selenium.support.FindBy;23import org.openqa.selenium.support.PageFactory;24import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;25import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy;26import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy.OpeningStrategy;27import com.qaprosoft.carina.core.foundation.webdriver.listener.EventFiringDecorator;28@PageOpeningStrategy(OpeningStrategy.BY_ELEMENT)29public class HomePage extends HomePageBase {30 private ExtendedWebElement header;31 public HomePage(WebDriver driver) {32 super(driver);33 PageFactory.initElements(new EventFiringDecorator(driver), this);34 }35 public boolean isPageOpened() {36 return header.isPresent();37 }38}39package com.qaprosoft.carina.demo.gui.pages;40import org.openqa.selenium.WebDriver;41import org.openqa.selenium.support.FindBy;42import org.openqa.selenium.support.PageFactory;43import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;44import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy;45import com.qaprosoft.carina.core.foundation

Full Screen

Full Screen

getRetryInterval

Using AI Code Generation

copy

Full Screen

1String retryInterval = DriverHelper.getRetryInterval();2System.out.println("Retry Interval: " + retryInterval);3String retryCount = DriverHelper.getRetryCount();4System.out.println("Retry Count: " + retryCount);5String retryTimeout = DriverHelper.getRetryTimeout();6System.out.println("Retry Timeout: " + retryTimeout);7String retryCount = DriverHelper.getRetryCount();8System.out.println("Retry Count: " + retryCount);9String retryTimeout = DriverHelper.getRetryTimeout();10System.out.println("Retry Timeout: " + retryTimeout);11String retryCount = DriverHelper.getRetryCount();12System.out.println("Retry Count: " + retryCount);13String retryTimeout = DriverHelper.getRetryTimeout();14System.out.println("Retry Timeout: " + retryTimeout);15String retryCount = DriverHelper.getRetryCount();16System.out.println("Retry Count: " + retryCount);17String retryTimeout = DriverHelper.getRetryTimeout();18System.out.println("Retry Timeout: " + retryTimeout);19String retryCount = DriverHelper.getRetryCount();20System.out.println("Retry Count: " + retryCount);21String retryTimeout = DriverHelper.getRetryTimeout();22System.out.println("Retry Timeout: " + retryTimeout);23String retryCount = DriverHelper.getRetryCount();24System.out.println("

Full Screen

Full Screen

getRetryInterval

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;2import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;3import org.openqa.selenium.By;4import org.openqa.selenium.WebDriver;5import java.util.List;6import java.util.concurrent.TimeUnit;7public class 1 extends DriverHelper {8 public 1(WebDriver driver) {9 super(driver);10 }11 public void waitForElementPresent(String locator, int timeout) {12 int retryInterval = getRetryInterval();13 int attempts = timeout / retryInterval;14 for (int i = 0; i < attempts; i++) {15 if (isElementPresent(locator)) {16 break;17 } else {18 pause(retryInterval);19 }20 }21 }22 public boolean isElementPresent(String locator) {23 List<ExtendedWebElement> elements = findExtendedWebElements(By.xpath(locator));24 return !elements.isEmpty();25 }26}27import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;28import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;29import org.openqa.selenium.By;30import org.openqa.selenium.WebDriver;31import java.util.List;32import java.util.concurrent.TimeUnit;33public class 2 extends DriverHelper {34 public 2(WebDriver driver) {35 super(driver);36 }37 public void waitForElementPresent(String locator, int timeout) {38 int retryInterval = getRetryInterval();39 int attempts = timeout / retryInterval;40 for (int i = 0; i < attempts; i++) {41 if (isElementPresent(locator)) {42 break;43 } else {44 pause(retryInterval);45 }46 }47 }48 public boolean isElementPresent(String locator) {49 List<ExtendedWebElement> elements = findExtendedWebElements(By.xpath(locator));50 return !elements.isEmpty();51 }52}53import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;54import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;55import org.openqa.selenium.By;56import org.openqa.selenium.WebDriver;57import java.util.List;58import java.util.concurrent.TimeUnit;59public class 3 extends DriverHelper {60 public 3(WebDriver driver) {

Full Screen

Full Screen

getRetryInterval

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.webdriver;2import org.apache.log4j.Logger;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.support.ui.ExpectedCondition;5import com.qaprosoft.carina.core.foundation.utils.Configuration;6import com.qaprosoft.carina.core.foundation.utils.R;7public class DriverHelper {8private static final Logger LOGGER = Logger.getLogger(DriverHelper.class);9private static final int DEFAULT_TIMEOUT = Configuration.getInt(Configuration.Parameter.EXPLICIT_TIMEOUT);10private static final int DEFAULT_RETRY_INTERVAL = Configuration.getInt(Configuration.Parameter.EXPLICIT_RETRY_INTERVAL);11private static final int DEFAULT_RETRY_ATTEMPTS = Configuration.getInt(Configuration.Parameter.EXPLICIT_RETRY_ATTEMPTS);12private WebDriver driver;13public DriverHelper(WebDriver driver) {14this.driver = driver;15}16public WebDriver getDriver() {17return driver;18}19public void setDriver(WebDriver driver) {20this.driver = driver;21}22public <T> T waitFor(ExpectedCondition<T> condition) {23return waitFor(condition, DEFAULT_TIMEOUT);24}25public <T> T waitFor(ExpectedCondition<T> condition, int timeout) {26return waitFor(condition, timeout, DEFAULT_RETRY_INTERVAL);27}28public <T> T waitFor(ExpectedCondition<T> condition, int timeout, int retryInterval) {29return waitFor(condition, timeout, retryInterval, DEFAULT_RETRY_ATTEMPTS);30}31public <T> T waitFor(ExpectedCondition<T> condition, int timeout, int retryInterval, int retryAttempts) {32return waitFor(condition, timeout, retryInterval, retryAttempts, false);33}34public <T> T waitFor(ExpectedCondition<T> condition, int timeout, int retryInterval, int retryAttempts, boolean throwException) {35return waitFor(condition, timeout, retryInterval, retryAttempts, throwException, false);36}37public <T> T waitFor(ExpectedCondition<T> condition, int timeout, int retryInterval, int retryAttempts, boolean throwException, boolean silent) {38return waitFor(condition, timeout, retryInterval, retryAttempts, throwException, silent, false);39}40public <T> T waitFor(ExpectedCondition<T> condition, int timeout, int retryInterval, int retryAttempts, boolean throwException, boolean silent, boolean debug) {41return waitFor(condition, timeout, retryInterval, retryAttempts, throwException, silent, debug, null);42}43public <T> T waitFor(ExpectedCondition<T> condition, int timeout, int retryInterval, int retryAttempts, boolean throwException, boolean silent, boolean debug, String customMessage) {44return waitFor(condition, timeout, retryInterval, retryAttempts, throw

Full Screen

Full Screen

getRetryInterval

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.webdriver;2import org.openqa.selenium.WebDriver;3public class DriverHelper {4 public static void main(String[] args) {5 WebDriver driver = null;6 long retryInterval = DriverHelper.getRetryInterval(driver);7 System.out.println("Retry Interval: " + retryInterval);8 }9}10package com.qaprosoft.carina.core.foundation.webdriver;11import org.openqa.selenium.WebDriver;12public class DriverHelper {13 public static void main(String[] args) {14 WebDriver driver = null;15 long retryInterval = DriverHelper.getRetryInterval(driver);16 System.out.println("Retry Interval: " + retryInterval);17 }18}19package com.qaprosoft.carina.core.foundation.webdriver;20import org.openqa.selenium.WebDriver;21public class DriverHelper {22 public static void main(String[] args) {23 WebDriver driver = null;24 long retryInterval = DriverHelper.getRetryInterval(driver);25 System.out.println("Retry Interval: " + retryInterval);26 }27}28package com.qaprosoft.carina.core.foundation.webdriver;29import org.openqa.selenium.WebDriver;30public class DriverHelper {31 public static void main(String[] args) {32 WebDriver driver = null;33 long retryInterval = DriverHelper.getRetryInterval(driver);34 System.out.println("Retry Interval: " + retryInterval);35 }36}37package com.qaprosoft.carina.core.foundation.webdriver;38import org.openqa.selenium.WebDriver;39public class DriverHelper {40 public static void main(String[] args) {41 WebDriver driver = null;42 long retryInterval = DriverHelper.getRetryInterval(driver);43 System.out.println("Retry Interval: " + retryInterval);44 }45}

Full Screen

Full Screen

getRetryInterval

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.demo;2import org.testng.annotations.Test;3import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;4public class Test1 {5 public void test() {6 DriverHelper driverHelper = new DriverHelper();7 int retryInterval = driverHelper.getRetryInterval();8 System.out.println("Retry Interval: " + retryInterval);9 }10}

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