Best Carina code snippet using com.qaprosoft.carina.core.foundation.webdriver.DriverHelper.call
Source:ExtendedWebElement.java
...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<String> match=new766 * BaseMatcher<String>() { {@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 /**1021 * Wait until element disappear1022 *1023 * @param timeout long1024 * @return boolean true if element disappeared and false if still visible1025 */1026 public boolean waitUntilElementDisappear(final long timeout) {1027 boolean res = false;1028 try {1029 if (this.element == null) {1030 // if element not found it will cause NoSuchElementException1031 findElement();1032 }1033 1034 // if element is stale, it will cause StaleElementReferenceException1035 if (this.element.isDisplayed()) {1036 LOGGER.info("Element {} detected. Waiting until disappear...", this.element.getTagName());1037 } else {1038 LOGGER.info("Element {} is not detected, i.e. disappeared", this.element.getTagName());1039 // no sense to continue as element is not displayed so return asap1040 return true;1041 }1042 1043 res = waitUntil(ExpectedConditions.or(ExpectedConditions.stalenessOf(this.element),1044 ExpectedConditions.invisibilityOf(this.element)),1045 timeout);1046 1047 } catch (NoSuchElementException | StaleElementReferenceException e) {1048 // element not present so means disappear1049 LOGGER.debug("Element disappeared as exception catched: {}", e.getMessage());1050 res = true;1051 }1052 return res;1053 }1054 public ExtendedWebElement format(Object... objects) {1055 String locator = by.toString();1056 By by = null;1057 if (locator.startsWith(LocatorType.ID.getStartsWith())) {1058 if (caseInsensitiveConverter != null) {1059 by = caseInsensitiveConverter.convert(by);1060 } else {1061 by = By.id(String.format(StringUtils.remove(locator, LocatorType.ID.getStartsWith()), objects));1062 }1063 }1064 if (locator.startsWith(LocatorType.NAME.getStartsWith())) {1065 if (caseInsensitiveConverter != null) {1066 by = caseInsensitiveConverter.convert(by);1067 } else {1068 by = By.id(String.format(StringUtils.remove(locator, LocatorType.NAME.getStartsWith()), objects));1069 }1070 }1071 if (locator.startsWith(LocatorType.XPATH.getStartsWith())) {1072 if (caseInsensitiveConverter != null) {1073 by = caseInsensitiveConverter.convert(by);1074 } else {1075 by = By.xpath(String.format(StringUtils.remove(locator, LocatorType.XPATH.getStartsWith()), objects));1076 }1077 }1078 if (locator.startsWith(LocatorType.LINKTEXT.getStartsWith())) {1079 if (caseInsensitiveConverter != null) {1080 by = caseInsensitiveConverter.convert(by);1081 } else {1082 by = By.xpath(String.format(StringUtils.remove(locator, LocatorType.LINKTEXT.getStartsWith()), objects));1083 }1084 }1085 if (locator.startsWith("partialLinkText: ")) {1086 by = By.partialLinkText(String.format(StringUtils.remove(locator, "partialLinkText: "), objects));1087 }1088 if (locator.startsWith("css: ")) {1089 by = By.cssSelector(String.format(StringUtils.remove(locator, "css: "), objects));1090 }1091 if (locator.startsWith("tagName: ")) {1092 by = By.tagName(String.format(StringUtils.remove(locator, "tagName: "), objects));1093 }1094 /*1095 * All ClassChain locators start from **. e.g FindBy(xpath = "**'/XCUIElementTypeStaticText[`name CONTAINS[cd] '%s'`]")1096 */1097 if (locator.startsWith("By.IosClassChain: **")) {1098 by = MobileBy.iOSClassChain(String.format(StringUtils.remove(locator, "By.IosClassChain: "), objects));1099 }1100 if (locator.startsWith("By.IosNsPredicate: **")) {1101 by = MobileBy.iOSNsPredicateString(String.format(StringUtils.remove(locator, "By.IosNsPredicate: "), objects));1102 }1103 if (locator.startsWith("By.AccessibilityId: ")) {1104 by = MobileBy.AccessibilityId(String.format(StringUtils.remove(locator, "By.AccessibilityId: "), objects));1105 }1106 if (locator.startsWith("By.Image: ")) {1107 String formattedLocator = String.format(StringUtils.remove(locator, "By.Image: "), objects);1108 Path path = Paths.get(formattedLocator);1109 LOGGER.debug("Formatted locator is : " + formattedLocator);1110 String base64image;1111 try {1112 base64image = new String(Base64.encode(Files.readAllBytes(path)));1113 } catch (IOException e) {1114 throw new RuntimeException(1115 "Error while reading image file after formatting. Formatted locator : " + formattedLocator, e);1116 }1117 LOGGER.debug("Base64 image representation has benn successfully obtained after formatting.");1118 by = MobileBy.image(base64image);1119 }1120 if (locator.startsWith("By.AndroidUIAutomator: ")) {1121 by = MobileBy.AndroidUIAutomator(String.format(StringUtils.remove(locator, "By.AndroidUIAutomator: "), objects));1122 LOGGER.debug("Formatted locator is : " + by.toString());1123 }1124 return new ExtendedWebElement(by, name, this.driver, this.searchContext, objects);1125 }1126 /**1127 * Pause for specified timeout.1128 * 1129 * @param timeout in seconds.1130 */1131 public void pause(long timeout) {1132 CommonUtils.pause(timeout);1133 }1134 public void pause(double timeout) {1135 CommonUtils.pause(timeout);1136 }1137 1138 public interface ActionSteps {1139 void doClick();1140 1141 void doClickByJs();1142 1143 void doClickByActions();1144 1145 void doDoubleClick();1146 void doRightClick();1147 1148 void doHover(Integer xOffset, Integer yOffset);1149 void doType(String text);1150 void doSendKeys(Keys keys);1151 void doAttachFile(String filePath);1152 void doCheck();1153 void doUncheck();1154 1155 boolean doIsChecked();1156 1157 String doGetText();1158 Point doGetLocation();1159 Dimension doGetSize();1160 String doGetAttribute(String name);1161 boolean doSelect(String text);1162 boolean doSelectValues(final String[] values);1163 boolean doSelectByMatcher(final BaseMatcher<String> matcher);1164 boolean doSelectByPartialText(final String partialSelectText);1165 boolean doSelectByIndex(final int index);1166 1167 String doGetSelectedValue();1168 1169 List<String> doGetSelectedValues();1170 }1171 private Object executeAction(ACTION_NAME actionName, ActionSteps actionSteps, Object... inputArgs) {1172 Object result = null;1173 switch (actionName) {1174 case CLICK:1175 actionSteps.doClick();1176 break;1177 case CLICK_BY_JS:1178 actionSteps.doClickByJs();1179 break;1180 case CLICK_BY_ACTIONS:1181 actionSteps.doClickByActions();1182 break;1183 case DOUBLE_CLICK:1184 actionSteps.doDoubleClick();1185 break;1186 case HOVER:1187 actionSteps.doHover((Integer) inputArgs[0], (Integer) inputArgs[1]);1188 break;1189 case RIGHT_CLICK:1190 actionSteps.doRightClick();1191 break;1192 case GET_TEXT:1193 result = actionSteps.doGetText();1194 break;1195 case GET_LOCATION:1196 result = actionSteps.doGetLocation();1197 break;1198 case GET_SIZE:1199 result = actionSteps.doGetSize();1200 break;1201 case GET_ATTRIBUTE:1202 result = actionSteps.doGetAttribute((String) inputArgs[0]);1203 break;1204 case SEND_KEYS:1205 actionSteps.doSendKeys((Keys) inputArgs[0]);1206 break;1207 case TYPE:1208 actionSteps.doType((String) inputArgs[0]);1209 break;1210 case ATTACH_FILE:1211 actionSteps.doAttachFile((String) inputArgs[0]);1212 break;1213 case CHECK:1214 actionSteps.doCheck();1215 break;1216 case UNCHECK:1217 actionSteps.doUncheck();1218 break;1219 case IS_CHECKED:1220 result = actionSteps.doIsChecked();1221 break;1222 case SELECT:1223 result = actionSteps.doSelect((String) inputArgs[0]);1224 break;1225 case SELECT_VALUES:1226 result = actionSteps.doSelectValues((String[]) inputArgs);1227 break;1228 case SELECT_BY_MATCHER:1229 result = actionSteps.doSelectByMatcher((BaseMatcher<String>) inputArgs[0]);1230 break;1231 case SELECT_BY_PARTIAL_TEXT:1232 result = actionSteps.doSelectByPartialText((String) inputArgs[0]);1233 break;1234 case SELECT_BY_INDEX:1235 result = actionSteps.doSelectByIndex((int) inputArgs[0]);1236 break;1237 case GET_SELECTED_VALUE:1238 result = actionSteps.doGetSelectedValue();1239 break;1240 case GET_SELECTED_VALUES:1241 result = actionSteps.doGetSelectedValues();1242 break;1243 default:1244 Assert.fail("Unsupported UI action name" + actionName.toString());1245 break;1246 }1247 return result;1248 }1249 /**1250 * doAction on element.1251 *1252 * @param actionName1253 * ACTION_NAME1254 * @param timeout1255 * long1256 * @param waitCondition1257 * to check element conditions before action1258 * @return1259 * Object1260 */1261 private Object doAction(ACTION_NAME actionName, long timeout, ExpectedCondition<?> waitCondition) {1262 // [VD] do not remove null args otherwise all actions without arguments will be broken!1263 Object nullArgs = null;1264 return doAction(actionName, timeout, waitCondition, nullArgs);1265 }1266 private Object doAction(ACTION_NAME actionName, long timeout, ExpectedCondition<?> waitCondition,1267 Object...inputArgs) {1268 1269 if (waitCondition != null) {1270 //do verification only if waitCondition is not null1271 if (!waitUntil(waitCondition, timeout)) {1272 //TODO: think about raising exception otherwise we do extra call and might wait and hangs especially for mobile/appium1273 LOGGER.error(Messager.ELEMENT_CONDITION_NOT_VERIFIED.getMessage(actionName.getKey(), getNameWithLocator()));1274 }1275 }1276 1277 if (isLocalized) {1278 isLocalized = false; // single verification is enough for this particular element1279 L10N.verify(this);1280 }1281 Object output = null;1282 try {1283 this.element = getElement();1284 output = overrideAction(actionName, inputArgs);1285 } catch (StaleElementReferenceException e) {1286 //TODO: analyze mobile testing for staled elements. Potentially it should be fixed by appium java client already...
Source:DriverHelper.java
...155 Assert.fail("Undefined error on open url detected: " + e.getMessage(), e);156 } finally {157 //restore default pageLoadTimeout driver timeout158 setPageLoadTimeout(drv, getPageLoadTimeout());159 LOGGER.debug("finished driver.get call.");160 }161 }162 protected void setPageURL(String relURL) {163 String baseURL;164 // if(!"NULL".equalsIgnoreCase(Configuration.get(Parameter.ENV)))165 if (!Configuration.get(Parameter.ENV).isEmpty()) {166 baseURL = Configuration.getEnvArg("base");167 } else {168 baseURL = Configuration.get(Parameter.URL);169 }170 this.pageURL = baseURL + relURL;171 }172 protected void setPageAbsoluteURL(String url) {173 this.pageURL = url;174 }175 public String getPageURL() {176 return this.pageURL;177 } 178 // --------------------------------------------------------------------------179 // Base UI interaction operations180 // --------------------------------------------------------------------------181 /**182 * Method which quickly looks for all element and check that they present183 * during EXPLICIT_TIMEOUT184 *185 * @param elements186 * ExtendedWebElement...187 * @return boolean return true only if all elements present.188 */189 public boolean allElementsPresent(ExtendedWebElement... elements) {190 return allElementsPresent(EXPLICIT_TIMEOUT, elements);191 }192 /**193 * Method which quickly looks for all element and check that they present194 * during timeout sec195 *196 * @param timeout long197 * @param elements198 * ExtendedWebElement...199 * @return boolean return true only if all elements present.200 */201 public boolean allElementsPresent(long timeout, ExtendedWebElement... elements) {202 int index = 0;203 boolean present = true;204 boolean ret = true;205 int counts = 1;206 timeout = timeout / counts;207 if (timeout < 1)208 timeout = 1;209 while (present && index++ < counts) {210 for (int i = 0; i < elements.length; i++) {211 present = elements[i].isElementPresent(timeout);212 if (!present) {213 LOGGER.error(elements[i].getNameWithLocator() + " is not present.");214 ret = false;215 }216 }217 }218 return ret;219 }220 /**221 * Method which quickly looks for all element lists and check that they222 * contain at least one element during SHORT_TIMEOUT223 *224 * @param elements225 * List<ExtendedWebElement>...226 * @return boolean227 */228 @SuppressWarnings("unchecked")229 public boolean allElementListsAreNotEmpty(List<ExtendedWebElement>... elements) {230 return allElementListsAreNotEmpty(SHORT_TIMEOUT, elements);231 }232 /**233 * Method which quickly looks for all element lists and check that they234 * contain at least one element during timeout235 *236 * @param timeout long237 * @param elements238 * List<ExtendedWebElement>...239 * @return boolean return true only if All Element lists contain at least240 * one element241 */242 @SuppressWarnings("unchecked")243 public boolean allElementListsAreNotEmpty(long timeout, List<ExtendedWebElement>... elements) {244 boolean ret;245 int counts = 3;246 timeout = timeout / counts;247 if (timeout < 1)248 timeout = 1;249 for (int i = 0; i < elements.length; i++) {250 boolean present = false;251 int index = 0;252 while (!present && index++ < counts) {253 try {254 present = elements[i].get(0).isElementPresent(timeout);255 } catch (Exception e) {256 present = false;257 }258 }259 ret = (elements[i].size() > 0);260 if (!ret) {261 LOGGER.error("List of elements[" + i + "] from elements " + Arrays.toString(elements) + " is empty.");262 return false;263 }264 }265 return true;266 }267 /**268 * Method which quickly looks for any element presence during269 * SHORT_TIMEOUT270 *271 * @param elements ExtendedWebElement...272 * @return true if any of elements was found.273 */274 public boolean isAnyElementPresent(ExtendedWebElement... elements) {275 return isAnyElementPresent(SHORT_TIMEOUT, elements);276 }277 /**278 * Method which quickly looks for any element presence during timeout sec279 *280 * @param timeout long281 * @param elements282 * ExtendedWebElement...283 * @return true if any of elements was found.284 */285 public boolean isAnyElementPresent(long timeout, ExtendedWebElement... elements) {286 int index = 0;287 int counts = 10;288 timeout = timeout / counts;289 if (timeout < 1)290 timeout = 1;291 while (index++ < counts) {292 for (int i = 0; i < elements.length; i++) {293 if (elements[i].isElementPresent(timeout)) {294 LOGGER.debug(elements[i].getNameWithLocator() + " is present");295 return true;296 }297 }298 }299 300 LOGGER.error("Unable to find any element from array: " + Arrays.toString(elements));301 return false;302 }303 /**304 * return Any Present Element from the list which present during305 * SHORT_TIMEOUT306 *307 * @param elements ExtendedWebElement...308 * @return ExtendedWebElement309 */310 public ExtendedWebElement returnAnyPresentElement(ExtendedWebElement... elements) {311 return returnAnyPresentElement(SHORT_TIMEOUT, elements);312 }313 /**314 * return Any Present Element from the list which present during timeout sec315 *316 * @param timeout long317 * @param elements318 * ExtendedWebElement...319 * @return ExtendedWebElement320 */321 public ExtendedWebElement returnAnyPresentElement(long timeout, ExtendedWebElement... elements) {322 int index = 0;323 int counts = 10;324 timeout = timeout / counts;325 if (timeout < 1)326 timeout = 1;327 while (index++ < counts) {328 for (int i = 0; i < elements.length; i++) {329 if (elements[i].isElementPresent(timeout)) {330 LOGGER.debug(elements[i].getNameWithLocator() + " is present");331 return elements[i];332 }333 }334 }335 //throw exception anyway if nothing was returned inside for cycle336 LOGGER.error("All elements are not present");337 throw new RuntimeException("Unable to find any element from array: " + Arrays.toString(elements));338 }339 /**340 * Check that element with text present.341 * 342 * @param extWebElement to check if element with text is present343 * @param text344 * of element to check.345 * @return element with text existence status.346 */347 public boolean isElementWithTextPresent(final ExtendedWebElement extWebElement, final String text) {348 return isElementWithTextPresent(extWebElement, text, EXPLICIT_TIMEOUT);349 }350 /**351 * Check that element with text present.352 * 353 * @param extWebElement to check if element with text is present354 * @param text355 * of element to check.356 * @param timeout Long357 * @return element with text existence status.358 */359 public boolean isElementWithTextPresent(final ExtendedWebElement extWebElement, final String text, long timeout) {360 return extWebElement.isElementWithTextPresent(text, timeout);361 }362 /**363 * Check that element not present on page.364 * 365 * @param extWebElement to check if element is not present366 * 367 * @return element non-existence status.368 */369 public boolean isElementNotPresent(final ExtendedWebElement extWebElement) {370 return isElementNotPresent(extWebElement, EXPLICIT_TIMEOUT);371 }372 /**373 * Check that element not present on page.374 * 375 * @param extWebElement to check if element is not present376 * @param timeout to wait377 * 378 * @return element non-existence status.379 */380 public boolean isElementNotPresent(final ExtendedWebElement extWebElement, long timeout) {381 return extWebElement.isElementNotPresent(timeout);382 }383 /**384 * Check that element not present on page.385 * 386 * @param element to check if element is not present387 * @param controlInfo String388 * 389 * @return element non-existence status.390 */391 public boolean isElementNotPresent(String controlInfo, final WebElement element) {392 return isElementNotPresent(new ExtendedWebElement(element, controlInfo));393 }394 /**395 * Clicks on element.396 * 397 * @param elements ExtendedWebElements to click398 *399 */400 public void clickAny(ExtendedWebElement... elements) {401 clickAny(EXPLICIT_TIMEOUT, elements);402 }403 /**404 * Clicks on element.405 * 406 * @param elements ExtendedWebElements to click407 * @param timeout to wait408 *409 */410 public void clickAny(long timeout, ExtendedWebElement... elements) {411 // Method which quickly looks for any element and click during timeout412 // sec413 WebDriver drv = getDriver();414 ActionPoller<WebElement> actionPoller = ActionPoller.builder();415 Optional<WebElement> searchableElement = actionPoller.task(() -> {416 WebElement possiblyFoundElement = null;417 for (ExtendedWebElement element : elements) {418 List<WebElement> foundElements = drv.findElements(element.getBy());419 if (foundElements.size() > 0) {420 possiblyFoundElement = foundElements.get(0);421 break;422 }423 }424 return possiblyFoundElement;425 })426 .until(Objects::nonNull)427 .pollEvery(0, ChronoUnit.SECONDS)428 .stopAfter(timeout, ChronoUnit.SECONDS)429 .execute();430 if (searchableElement.isEmpty()) {431 throw new RuntimeException("Unable to click onto any elements from array: " + Arrays.toString(elements));432 }433 searchableElement.get()434 .click();435 }436 437 /*438 * Get and return the source of the last loaded page.439 * @return String440 */441 public String getPageSource() {442 WebDriver drv = getDriver();443 Messager.GET_PAGE_SOURCE.info();444 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)445 .pollingEvery(Duration.ofMillis(5000)) // there is no sense to refresh url address too often446 .withTimeout(Duration.ofSeconds(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT)))447 .ignoring(WebDriverException.class)448 .ignoring(JavascriptException.class); // org.openqa.selenium.JavascriptException: javascript error: Cannot read property 'outerHTML' of null449 String res = "";450 try {451 res = wait.until(new Function<WebDriver, String>() {452 public String apply(WebDriver driver) {453 return drv.getPageSource();454 }455 });456 } catch (ScriptTimeoutException | TimeoutException e) {457 Messager.FAIL_GET_PAGE_SOURCE.error();458 }459 Messager.GET_PAGE_SOURCE.info();460 return res;461 }462 463 /*464 * Add cookie object into the driver465 * @param Cookie466 */467 public void addCookie(Cookie cookie) {468 WebDriver drv = getDriver();469 DriverListener.setMessages(Messager.ADD_COOKIE.getMessage(cookie.getName()), 470 Messager.FAIL_ADD_COOKIE.getMessage(cookie.getName()));471 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)472 .pollingEvery(Duration.ofMillis(Configuration.getInt(Parameter.RETRY_INTERVAL)))473 .withTimeout(Duration.ofSeconds(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT)))474 .ignoring(WebDriverException.class)475 .ignoring(JsonException.class); // org.openqa.selenium.json.JsonException: Expected to read a START_MAP but instead have: END. Last 0 characters rea476 wait.until(new Function<WebDriver, Boolean>() {477 public Boolean apply(WebDriver driver) {478 drv.manage().addCookie(cookie);479 return true;480 }481 });482 }483 484 /**485 * Get a string representing the current URL that the browser is looking at.486 * @return url.487 */488 public String getCurrentUrl() {489 return getCurrentUrl(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT));490 }491 492 /**493 * Get a string representing the current URL that the browser is looking at.494 * @param timeout long495 * @return validation result.496 */497 public String getCurrentUrl(long timeout) {498 WebDriver drv = getDriver();499 500 // explicitly limit time for the getCurrentUrl operation501 Future<?> future = Executors.newSingleThreadExecutor().submit(new Callable<String>() {502 public String call() throws Exception {503 //organize fluent waiter for getting url504 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)505 .pollingEvery(Duration.ofMillis(Configuration.getInt(Parameter.RETRY_INTERVAL)))506 .withTimeout(Duration.ofSeconds(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT)))507 .ignoring(WebDriverException.class)508 .ignoring(JsonException.class); // org.openqa.selenium.json.JsonException: Expected to read a START_MAP but instead have: END. Last 0 characters rea509 return wait.until(new Function<WebDriver, String>() {510 public String apply(WebDriver driver) {511 return drv.getCurrentUrl();512 }513 });514 }515 });516 517 String url = "";518 try {519 url = (String) future.get(timeout, TimeUnit.SECONDS);520 } catch (java.util.concurrent.TimeoutException e) {521 LOGGER.debug("Unable to get driver url during " + timeout + "sec!", e);522 } catch (InterruptedException e) {523 LOGGER.debug("Unable to get driver url during " + timeout + "sec!", e);524 Thread.currentThread().interrupt();525 } catch (ExecutionException e) {526 LOGGER.error("ExecutionException error on get driver url!", e);527 } catch (Exception e) {528 LOGGER.error("Undefined error on get driver url detected!", e);529 }530 531 return url;532 } 533 /**534 * Checks that current URL is as expected.535 * 536 * @param expectedURL537 * Expected Url538 * @return validation result.539 */540 public boolean isUrlAsExpected(String expectedURL) {541 return isUrlAsExpected(expectedURL, Configuration.getInt(Parameter.EXPLICIT_TIMEOUT)); 542 }543 /**544 * Checks that current URL is as expected.545 * 546 * @param expectedURL547 * Expected Url548 * @param timeout long549 * @return validation result.550 */551 public boolean isUrlAsExpected(String expectedURL, long timeout) {552 String decryptedURL = cryptoTool.decryptByPattern(expectedURL, CRYPTO_PATTERN);553 decryptedURL = getEnvArgURL(decryptedURL);554 555 String actualUrl = getCurrentUrl(timeout);556 557 if (LogicUtils.isURLEqual(decryptedURL, actualUrl)) {558 Messager.EXPECTED_URL.info(actualUrl);559 return true;560 } else {561 Messager.UNEXPECTED_URL.error(expectedURL, actualUrl);562 return false;563 } 564 }565 566 567 /**568 * Get full or relative URL considering Env argument569 * 570 * @param decryptedURL String571 * @return url572 */573 private String getEnvArgURL(String decryptedURL) {574 if (!(decryptedURL.contains("http:") || decryptedURL.contains("https:"))) {575 if (Configuration.getEnvArg(Parameter.URL.getKey()).isEmpty()) {576 decryptedURL = Configuration.get(Parameter.URL) + decryptedURL;577 } else {578 decryptedURL = Configuration.getEnvArg(Parameter.URL.getKey()) + decryptedURL;579 }580 }581 return decryptedURL;582 }583 /**584 *585 * @return String saved in clipboard586 */587 public String getClipboardText() {588 String clipboardText = "";589 try {590 LOGGER.debug("Trying to get clipboard from remote machine with hub...");591 String url = getSelenoidClipboardUrl(driver);592 String username = getField(url, 1);593 String password = getField(url, 2);594 HttpURLConnection.setFollowRedirects(false);595 HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();596 con.setRequestMethod("GET");597 if (!username.isEmpty() && !password.isEmpty()) {598 String usernameColonPassword = username + ":" + password;599 String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());600 con.addRequestProperty("Authorization", basicAuthPayload);601 }602 int status = con.getResponseCode();603 if (200 <= status && status <= 299) {604 BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));605 String inputLine;606 StringBuffer content = new StringBuffer();607 while ((inputLine = br.readLine()) != null) {608 content.append(inputLine);609 }610 br.close();611 clipboardText = content.toString();612 } else {613 LOGGER.debug("Trying to get clipboard from local java machine...");614 clipboardText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);615 }616 } catch (Exception ex) {617 ex.printStackTrace();618 }619 clipboardText = clipboardText.replaceAll("\n", "");620 LOGGER.info("Clipboard: " + clipboardText);621 return clipboardText;622 }623 private String getSelenoidClipboardUrl(WebDriver driver) {624 String seleniumHost = Configuration.getSeleniumUrl().replace("wd/hub", "clipboard/");625 if (seleniumHost.isEmpty()){626 seleniumHost = Configuration.getEnvArg(Parameter.URL.getKey()).replace("wd/hub", "clipboard/");627 }628 WebDriver drv = (driver instanceof EventFiringWebDriver) ? ((EventFiringWebDriver) driver).getWrappedDriver() : driver;629 String sessionId = ((RemoteWebDriver) drv).getSessionId().toString();630 String url = seleniumHost + sessionId;631 LOGGER.debug("url: " + url);632 return url;633 }634 private String getField(String url, int position) {635 Pattern pattern = Pattern.compile(".*:\\/\\/(.*):(.*)@");636 Matcher matcher = pattern.matcher(url);637 return matcher.find() ? matcher.group(position) : "";638 }639 /**640 * Pause for specified timeout.641 * 642 * @param timeout643 * in seconds.644 */645 public void pause(long timeout) {646 CommonUtils.pause(timeout);647 }648 public void pause(Double timeout) {649 CommonUtils.pause(timeout);650 }651 652 /**653 * Return page title.654 * 655 * @return title String.656 */657 public String getTitle() {658 return getTitle(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT));659 }660 661 /**662 * Return page title.663 * 664 * @param timeout long665 * @return title String.666 */667 public String getTitle(long timeout) {668 669 WebDriver drv = getDriver();670 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)671 .pollingEvery(Duration.ofMillis(RETRY_TIME))672 .withTimeout(Duration.ofSeconds(timeout))673 .ignoring(WebDriverException.class)674 .ignoring(JavascriptException.class); // org.openqa.selenium.JavascriptException: javascript error: Cannot read property 'outerHTML' of null675 String res = "";676 try {677 res = wait.until(new Function<WebDriver, String>() {678 public String apply(WebDriver driver) {679 return drv.getTitle();680 }681 });682 } catch (ScriptTimeoutException | TimeoutException e) {683 Messager.FAIL_GET_TITLE.error();684 }685 return res;686 } 687 /**688 * Checks that page title is as expected.689 * 690 * @param expectedTitle691 * Expected title692 * @return validation result.693 */694 public boolean isTitleAsExpected(final String expectedTitle) {695 final String decryptedExpectedTitle = cryptoTool.decryptByPattern(expectedTitle, CRYPTO_PATTERN);696 String title = getTitle(EXPLICIT_TIMEOUT);697 boolean result = title.contains(decryptedExpectedTitle);698 if (result) {699 Messager.TITLE_CORRECT.info(expectedTitle);700 } else {701 Messager.TITLE_NOT_CORRECT.error(expectedTitle, title);702 }703 704 return result;705 }706 /**707 * Checks that page suites to expected pattern.708 * 709 * @param expectedPattern710 * Expected Pattern711 * @return validation result.712 */713 public boolean isTitleAsExpectedPattern(String expectedPattern) {714 final String decryptedExpectedPattern = cryptoTool.decryptByPattern(expectedPattern, CRYPTO_PATTERN);715 716 String actual = getTitle(EXPLICIT_TIMEOUT);717 Pattern p = Pattern.compile(decryptedExpectedPattern);718 Matcher m = p.matcher(actual);719 boolean result = m.find();720 if (result) {721 Messager.TITLE_CORRECT.info(actual);722 } else {723 Messager.TITLE_NOT_CORRECT.error(expectedPattern, actual); 724 }725 726 return result;727 }728 /**729 * Go back in browser.730 */731 public void navigateBack() {732 getDriver().navigate().back();733 Messager.BACK.info();734 }735 /**736 * Refresh browser.737 */738 public void refresh() {739 refresh(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT));740 }741 /**742 * Refresh browser.743 * 744 * @param timeout long745 */746 public void refresh(long timeout) {747 WebDriver drv = getDriver();748 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)749 .pollingEvery(Duration.ofMillis(5000)) // there is no sense to refresh url address too often750 .withTimeout(Duration.ofSeconds(timeout))751 .ignoring(WebDriverException.class)752 .ignoring(JsonException.class); // org.openqa.selenium.json.JsonException: Expected to read a START_MAP but instead have: END. Last 0 characters read753 754 try {755 wait.until(new Function<WebDriver, Void>() {756 public Void apply(WebDriver driver) {757 drv.navigate().refresh();758 return null;759 }760 });761 } catch (ScriptTimeoutException | TimeoutException e) {762 Messager.FAIL_REFRESH.error();763 }764 Messager.REFRESH.info();765 }766 public void pressTab() {767 Actions builder = new Actions(getDriver());768 builder.sendKeys(Keys.TAB).perform();769 }770 /**771 * Drags and drops element to specified place.772 * 773 * @param from774 * - element to drag.775 * @param to776 * - element to drop to.777 */778 public void dragAndDrop(final ExtendedWebElement from, final ExtendedWebElement to) {779 if (from.isElementPresent() && to.isElementPresent()) {780 WebDriver drv = getDriver();781 if (!drv.toString().contains("safari")) {782 Actions builder = new Actions(drv);783 Action dragAndDrop = builder.clickAndHold(from.getElement()).moveToElement(to.getElement())784 .release(to.getElement()).build();785 dragAndDrop.perform();786 } else {787 WebElement LocatorFrom = from.getElement();788 WebElement LocatorTo = to.getElement();789 String xto = Integer.toString(LocatorTo.getLocation().x);790 String yto = Integer.toString(LocatorTo.getLocation().y);791 ((JavascriptExecutor) driver)792 .executeScript(793 "function simulate(f,c,d,e){var b,a=null;for(b in eventMatchers)if(eventMatchers[b].test(c)){a=b;break}if(!a)return!1;document.createEvent?(b=document.createEvent(a),a==\"HTMLEvents\"?b.initEvent(c,!0,!0):b.initMouseEvent(c,!0,!0,document.defaultView,0,d,e,d,e,!1,!1,!1,!1,0,null),f.dispatchEvent(b)):(a=document.createEventObject(),a.detail=0,a.screenX=d,a.screenY=e,a.clientX=d,a.clientY=e,a.ctrlKey=!1,a.altKey=!1,a.shiftKey=!1,a.metaKey=!1,a.button=1,f.fireEvent(\"on\"+c,a));return!0} var eventMatchers={HTMLEvents:/^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,MouseEvents:/^(?:click|dblclick|mouse(?:down|up|over|move|out))$/}; "794 + "simulate(arguments[0],\"mousedown\",0,0); simulate(arguments[0],\"mousemove\",arguments[1],arguments[2]); simulate(arguments[0],\"mouseup\",arguments[1],arguments[2]); ",795 LocatorFrom, xto, yto);796 }797 Messager.ELEMENTS_DRAGGED_AND_DROPPED.info(from.getName(), to.getName());798 } else {799 Messager.ELEMENTS_NOT_DRAGGED_AND_DROPPED.error(from.getNameWithLocator(), to.getNameWithLocator());800 }801 }802 /**803 * Drags and drops element to specified place. Elements Need To have an id.804 *805 * @param from806 * - the element to drag.807 * @param to808 * - the element to drop to.809 */810 public void dragAndDropHtml5(final ExtendedWebElement from, final ExtendedWebElement to) {811 String source = "#" + from.getAttribute("id");812 String target = "#" + to.getAttribute("id");813 if (source.isEmpty() || target.isEmpty()) {814 Messager.ELEMENTS_NOT_DRAGGED_AND_DROPPED.error(from.getNameWithLocator(), to.getNameWithLocator());815 } else {816 jQuerify(driver);817 String javaScript = "(function( $ ) { $.fn.simulateDragDrop = function(options) { return this.each(function() { new $.simulateDragDrop(this, options); }); }; $.simulateDragDrop = function(elem, options) { this.options = options; this.simulateEvent(elem, options); }; $.extend($.simulateDragDrop.prototype, { simulateEvent: function(elem, options) { /*Simulating drag start*/ var type = 'dragstart'; var event = this.createEvent(type); this.dispatchEvent(elem, type, event); /*Simulating drop*/ type = 'drop'; var dropEvent = this.createEvent(type, {}); dropEvent.dataTransfer = event.dataTransfer; this.dispatchEvent($(options.dropTarget)[0], type, dropEvent); /*Simulating drag end*/ type = 'dragend'; var dragEndEvent = this.createEvent(type, {}); dragEndEvent.dataTransfer = event.dataTransfer; this.dispatchEvent(elem, type, dragEndEvent); }, createEvent: function(type) { var event = document.createEvent(\"CustomEvent\"); event.initCustomEvent(type, true, true, null); event.dataTransfer = { data: { }, setData: function(type, val){ this.data[type] = val; }, getData: function(type){ return this.data[type]; } }; return event; }, dispatchEvent: function(elem, type, event) { if(elem.dispatchEvent) { elem.dispatchEvent(event); }else if( elem.fireEvent ) { elem.fireEvent(\"on\"+type, event); } } });})(jQuery);";;818 ((JavascriptExecutor)driver)819 .executeScript(javaScript + "$('" + source + "')" +820 ".simulateDragDrop({ dropTarget: '" + target + "'});");821 Messager.ELEMENTS_DRAGGED_AND_DROPPED.info(from.getName(), to.getName());822 }823 }824 private static void jQuerify(WebDriver driver) {825 String jQueryLoader = "(function(jqueryUrl, callback) {\n" +826 " if (typeof jqueryUrl != 'string') {\n" +827 " jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';\n" +828 " }\n" +829 " if (typeof jQuery == 'undefined') {\n" +830 " var script = document.createElement('script');\n" +831 " var head = document.getElementsByTagName('head')[0];\n" +832 " var done = false;\n" +833 " script.onload = script.onreadystatechange = (function() {\n" +834 " if (!done && (!this.readyState || this.readyState == 'loaded'\n" +835 " || this.readyState == 'complete')) {\n" +836 " done = true;\n" +837 " script.onload = script.onreadystatechange = null;\n" +838 " head.removeChild(script);\n" +839 " callback();\n" +840 " }\n" +841 " });\n" +842 " script.src = jqueryUrl;\n" +843 " head.appendChild(script);\n" +844 " }\n" +845 " else {\n" +846 " callback();\n" +847 " }\n" +848 "})(arguments[0], arguments[arguments.length - 1]);";849 driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);850 JavascriptExecutor js = (JavascriptExecutor) driver;851 js.executeAsyncScript(jQueryLoader);852 }853 /**854 * Performs slider move for specified offset.855 * 856 * @param slider857 * slider858 * @param moveX859 * move x860 * @param moveY...
Source:IAndroidUtils.java
...788 * @param link789 * - URL to trigger790 */791 default public void openURL(String link) {792 // TODO: #1380 make openURL call from this mobile interface in DriverHelper793 UTILS_LOGGER.info("Following link will be triggered via ADB: " + link);794 String command = String.format(SHELL_OPEN_URL_CMD.concat(" %s"), link);795 executeShell(command);796 }797 /**798 * With this method user is able to trigger a deeplink (link to specific place799 * within the application)800 * 801 * @param link String802 * @param packageName String803 */804 default public void triggerDeeplink(String link, String packageName) {805 Map<String, Object> preparedCommand = ImmutableMap.of("url", link, "package", packageName);806 try {...
call
Using AI Code Generation
1import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.support.ui.ExpectedConditions;4import org.openqa.selenium.support.ui.WebDriverWait;5import org.testng.Assert;6import org.testng.annotations.Test;7public class Test1 {8 public void test1() {9 WebDriver driver = DriverHelper.getDriver();10 WebDriverWait wait = new WebDriverWait(driver, 10);11 wait.until(ExpectedConditions.titleContains("Google"));12 Assert.assertTrue(driver.getTitle().contains("Google"));13 }14}15import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;16import org.openqa.selenium.WebDriver;17import org.openqa.selenium.support.ui.ExpectedConditions;18import org.openqa.selenium.support.ui.WebDriverWait;19import org.testng.Assert;20import org.testng.annotations.Test;21public class Test2 {22 public void test2() {23 WebDriver driver = DriverHelper.getDriver();24 WebDriverWait wait = new WebDriverWait(driver, 10);25 wait.until(ExpectedConditions.titleContains("Google"));26 Assert.assertTrue(driver.getTitle().contains("Google"));27 }28}29import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;30import org.openqa.selenium.WebDriver;31import org.openqa.selenium.support.ui.ExpectedConditions;32import org.openqa.selenium.support.ui.WebDriverWait;33import org.testng.Assert;34import org.testng.annotations.Test;35public class Test3 {36 public void test3() {37 WebDriver driver = DriverHelper.getDriver();38 WebDriverWait wait = new WebDriverWait(driver, 10);39 wait.until(ExpectedConditions.titleContains("Google"));40 Assert.assertTrue(driver.getTitle().contains("Google"));41 }42}43import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;44import org.openqa.selenium.WebDriver;45import org.openqa.selenium.support.ui.ExpectedConditions;46import org.openqa.selenium.support.ui.WebDriverWait;47import org.testng.Assert;48import org.testng.annotations.Test;49public class Test4 {50 public void test4() {
call
Using AI Code Generation
1package com.qaprosoft.carina.demo.gui.pages;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.support.FindBy;4import org.openqa.selenium.support.events.EventFiringWebDriver;5import org.openqa.selenium.support.ui.ExpectedConditions;6import org.openqa.selenium.support.ui.WebDriverWait;7import org.openqa.selenium.WebElement;8import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;9import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy;10import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy.PageOpeningType;11import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory;12import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory.Strategy;13import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory.StrategyType;14import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory.TimeOut;15import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory.TimeOutType;16import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory.TimeOutValue;17import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory.WaitType;18import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory.WaitTypeType;19import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategyFactory.WaitValue;20import com.qaprosoft.carina.core.gui.AbstractPage;21@Strategy(StrategyType.CUSTOM)22@TimeOut(TimeOutType.CUSTOM)23@TimeOutValue(timeOutValue = 5)24@WaitType(WaitTypeType.CUSTOM)25@WaitValue(waitValue = 15)26public class HomePage extends AbstractPage {27 private ExtendedWebElement signIn;28 private ExtendedWebElement logo;29 public HomePage(WebDriver driver) {30 super(driver);31 PageOpeningStrategy pageOpeningStrategy = PageOpeningStrategyFactory.getStrategy(this);32 pageOpeningStrategy.openPage();33 }34 public boolean isPageOpened() {35 return logo.isElementPresent();36 }37 public void clickSignIn() {38 signIn.click();39 }40}
call
Using AI Code Generation
1import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;2import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;3import org.openqa.selenium.WebDriver;4public class 1 {5public static void main(String[] args) {6 WebDriver driver = new DriverHelper().getDriver();7 element.click();8}9}10import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;11import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;12import org.openqa.selenium.WebDriver;13public class 2 {14public static void main(String[] args) {15 WebDriver driver = new DriverHelper().getDriver();16 element.click();17}18}19import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;20import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;21import org.openqa.selenium.WebDriver;22public class 3 {23public static void main(String[] args) {24 WebDriver driver = new DriverHelper().getDriver();25 element.click();26}27}28import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;29import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;30import org.openqa.selenium.WebDriver;31public class 4 {32public static void main(String[] args) {33 WebDriver driver = new DriverHelper().getDriver();34 element.click();35}36}37import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;38import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;39import org.openqa.selenium.WebDriver;40public class 5 {41public static void main(String[]
call
Using AI Code Generation
1import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;2import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;3ExtendedWebElement element = new ExtendedWebElement();4element.click();5import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;6ExtendedWebElement element = new ExtendedWebElement();7element.click();8import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;9ExtendedWebElement element = new ExtendedWebElement();10element.click();11import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;12ExtendedWebElement element = new ExtendedWebElement();13element.click();14import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;15ExtendedWebElement element = new ExtendedWebElement();16element.click();17import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;18ExtendedWebElement element = new ExtendedWebElement();19element.click();20import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;21ExtendedWebElement element = new ExtendedWebElement();22element.click();23import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;24ExtendedWebElement element = new ExtendedWebElement();25element.click();26import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;27ExtendedWebElement element = new ExtendedWebElement();28element.click();
call
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver;2import org.apache.log4j.Logger;3import org.openqa.selenium.WebDriver;4public class DriverHelper {5 private static final Logger LOGGER = Logger.getLogger(DriverHelper.class);6 private static final ThreadLocal<DriverHelper> INSTANCE = new ThreadLocal<DriverHelper>() {7 protected DriverHelper initialValue() {8 return new DriverHelper();9 }10 };11 private WebDriver driver;12 private DriverHelper() {13 this.driver = WebDriverPool.getDriver();14 }15 public static DriverHelper getInstance() {16 return INSTANCE.get();17 }18 public WebDriver getDriver() {19 return driver;20 }21 public void setDriver(WebDriver driver) {22 this.driver = driver;23 }24 public void quit() {25 LOGGER.info("Quitting driver...");26 WebDriverPool.quitDriver();27 INSTANCE.remove();28 }29}30package com.qaprosoft.carina.core.foundation.webdriver;31import org.openqa.selenium.WebDriver;32public class DriverHelperTest {33 public static void main(String[] args) {34 DriverHelper driverHelper = DriverHelper.getInstance();35 WebDriver driver = driverHelper.getDriver();36 }37}
call
Using AI Code Generation
1package com.qaprosoft.carina.demo.gui.pages.android;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.support.FindBy;4import org.openqa.selenium.support.events.EventFiringWebDriver;5import org.openqa.selenium.support.ui.ExpectedConditions;6import org.openqa.selenium.support.ui.WebDriverWait;7import org.testng.Assert;8import org.testng.annotations.Test;9import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;10import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;11import com.qaprosoft.carina.demo.gui.pages.common.HomeBasePage;12import com.qaprosoft.carina.demo.gui.pages.common.LoginBasePage;13import com.qaprosoft.carina.demo.gui.pages.common.NewsBasePage;14import com.qaprosof
call
Using AI Code Generation
1import org.testng.annotations.Test;2import org.testng.Assert;3import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;4public class Test1 {5 public void test1() {6 Assert.assertTrue(true);7 }8}9import org.testng.annotations.Test;10import org.testng.Assert;11import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;12public class Test2 {13 public void test2() {14 DriverHelper.call("com.qaprosoft.carina
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!