Best Carina code snippet using com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocator.isLocalized
Source:ExtendedWebElement.java
...95 private String name;96 private By by;97 private boolean caseInsensitive;98 private ElementLoadingStrategy loadingStrategy = ElementLoadingStrategy.valueOf(Configuration.get(Parameter.ELEMENT_LOADING_STRATEGY));99 private boolean isLocalized = false;100 // Converted array of objects to String for dynamic element locators101 private String formatValues = "";102 private LocatorConverter caseInsensitiveConverter;103 104 public ExtendedWebElement(By by, String name, WebDriver driver, SearchContext searchContext) {105 if (by == null) {106 throw new RuntimeException("By couldn't be null!");107 }108 if (driver == null) {109 throw new RuntimeException("driver couldn't be null!");110 }111 if (searchContext == null) {112 throw new RuntimeException("review stacktrace to analyze why searchContext is null");113 }114 this.by = by;115 this.name = name;116 this.driver = driver;117 this.searchContext = searchContext;118 }119 public ExtendedWebElement(By by, String name, WebDriver driver, SearchContext searchContext, Object[] formatValues) {120 this(by, name, driver, searchContext);121 this.formatValues = Arrays.toString(formatValues);122 }123 public ExtendedWebElement(WebElement element, String name, By by) {124 this(element, name);125 this.by = by;126 }127 public ExtendedWebElement(WebElement element, String name) {128 this.name = name;129 this.element = element;130 131 //read searchContext from not null elements only132 if (element == null) {133 // it seems like we have to specify WebElement or By annotation! Add verification that By is valid in this case!134 if (getBy() == null) {135 try {136 throw new RuntimeException("review stacktrace to analyze why tempBy is not populated correctly via reflection!");137 } catch (Throwable thr) {138 LOGGER.warn("getBy() is null!", thr);139 }140 }141 return;142 }143 try {144 Field locatorField, searchContextField, byContextField, caseInsensitiveContextField = null;145 SearchContext tempSearchContext = null;146 if (element.getClass().toString().contains("EventFiringWebDriver$EventFiringWebElement")) {147 // reuse reflection to get internal fields148 locatorField = element.getClass().getDeclaredField("underlyingElement");149 locatorField.setAccessible(true);150 element = (RemoteWebElement) locatorField.get(element);151 }152 if (element instanceof RemoteWebElement) {153 tempSearchContext = ((RemoteWebElement) element).getWrappedDriver();154 } else if (element instanceof Proxy) {155 InvocationHandler innerProxy = Proxy.getInvocationHandler(((Proxy) element));156 locatorField = innerProxy.getClass().getDeclaredField("locator");157 locatorField.setAccessible(true);158 ExtendedElementLocator locator = (ExtendedElementLocator) locatorField.get(innerProxy);159 this.isLocalized = locator.isLocalized();160 if (isLocalized) {161 this.name = locator.getClassName() + "." + name;162 }163 searchContextField = locator.getClass().getDeclaredField("searchContext");164 searchContextField.setAccessible(true);165 this.searchContext = tempSearchContext = (SearchContext) searchContextField.get(locator);166 caseInsensitiveContextField = locator.getClass().getDeclaredField("caseInsensitive");167 caseInsensitiveContextField.setAccessible(true);168 this.caseInsensitive = (Boolean) caseInsensitiveContextField.get(locator);169 byContextField = locator.getClass().getDeclaredField("by");170 byContextField.setAccessible(true);171 //TODO: identify if it is a child element and172 // 1. get rootBy173 // 2. append current "by" to the rootBy174 // -> it should allow to search via regular driver and fluent waits - getBy()175 this.by = (By) byContextField.get(locator);176 while (tempSearchContext instanceof Proxy) {177 innerProxy = Proxy.getInvocationHandler(((Proxy) tempSearchContext));178 locatorField = innerProxy.getClass().getDeclaredField("locator");179 locatorField.setAccessible(true);180 locator = (ExtendedElementLocator) locatorField.get(innerProxy);181 // #1691 fix L10N Localized annotation does not work when elements are nested and the182 // parent element does not have an annotation.183 //this.isLocalized = locator.isLocalized();184 searchContextField = locator.getClass().getDeclaredField("searchContext");185 searchContextField.setAccessible(true);186 tempSearchContext = (SearchContext) searchContextField.get(locator);187 caseInsensitiveContextField = locator.getClass().getDeclaredField("caseInsensitive");188 caseInsensitiveContextField.setAccessible(true);189 this.caseInsensitive = (Boolean) caseInsensitiveContextField.get(locator);190 if (this.caseInsensitive) {191 CaseInsensitiveXPath csx = locator.getCaseInsensitiveXPath();192 Platform platform = Objects.equals(Configuration.getMobileApp(), "") ? Platform.WEB : Platform.MOBILE;193 caseInsensitiveConverter = new CaseInsensitiveConverter(194 new ParamsToConvert(csx.id(), csx.name(), csx.text(), csx.classAttr()), platform);195 }196 }197 }198 if (tempSearchContext instanceof EventFiringWebDriver) {199 EventFiringWebDriver eventFirDriver = (EventFiringWebDriver) tempSearchContext;200 this.driver = eventFirDriver.getWrappedDriver();201 //TODO: [VD] it seems like method more and more complex. Let's analyze and avoid return from this line202 return;203 }204 if (tempSearchContext != null && tempSearchContext.getClass().toString().contains("EventFiringWebDriver$EventFiringWebElement")) {205 // reuse reflection to get internal fields206 locatorField = tempSearchContext.getClass().getDeclaredField("underlyingElement");207 locatorField.setAccessible(true);208 this.searchContext = tempSearchContext = (RemoteWebElement) locatorField.get(tempSearchContext);209 }210 if (tempSearchContext instanceof RemoteWebElement) {211// this.driver = ((RemoteWebElement) searchContext).getWrappedDriver();212 tempSearchContext = ((RemoteWebElement) tempSearchContext).getWrappedDriver();213 }214 if (tempSearchContext != null && tempSearchContext instanceof RemoteWebDriver) {215 SessionId sessionId = ((RemoteWebDriver) tempSearchContext).getSessionId();216 if (this.searchContext == null) {217 // do not override if it was already initialized as it has218 // real searchContext which shouldn't be replaced by actual driver219 this.searchContext = tempSearchContext; 220 }221 //this.driver = (WebDriver) tempSearchContext;222 // that's the only place to use DriverPool to get driver.223 try {224 //try to search securely in driver pool by sessionId225 this.driver = IDriverPool.getDriver(sessionId);226 } catch (DriverPoolException ex) {227 // seems like driver started outside of IDriverPool so try to register it as well228 this.driver = (WebDriver) tempSearchContext;229 }230 } else {231 LOGGER.error("Undefined error for searchContext: " + tempSearchContext.toString());232 }233 } catch (NoSuchFieldException e) {234 e.printStackTrace();235 } catch (IllegalAccessException e) {236 e.printStackTrace();237 } catch (ClassCastException e) {238 e.printStackTrace();239 } catch (Throwable thr) {240 thr.printStackTrace();241 LOGGER.error("Unable to get Driver, searchContext and By via reflection!", thr);242 } finally {243 if (this.searchContext == null) {244 throw new RuntimeException("review stacktrace to analyze why searchContext is not populated correctly via reflection!");245 }246 }247 }248 public WebElement getElement() {249 if (this.element == null) {250 this.element = this.findElement();251 }252 253 return this.element;254 }255 /**256 * Reinitializes the element257 *258 * @throws NoSuchElementException if the element is not found259 */260 public void refresh() {261 // try to override element262 element = this.findElement();263 }264 265 /**266 * Check that element present or visible.267 *268 * @return element presence status.269 */270 public boolean isPresent() {271 return isPresent(EXPLICIT_TIMEOUT);272 }273 274 /**275 * Check that element present or visible within specified timeout.276 *277 * @param timeout - timeout.278 * @return element existence status.279 */280 public boolean isPresent(long timeout) {281 return isPresent(getBy(), timeout);282 }283 284 /**285 * Check that element with By present within specified timeout.286 *287 * @param by288 * - By.289 * @param timeout290 * - timeout.291 * @return element existence status.292 */293 public boolean isPresent(By by, long timeout) {294 boolean res = false;295 try {296 res = waitUntil(getDefaultCondition(by), timeout);297 } catch (StaleElementReferenceException e) {298 // there is no sense to continue as StaleElementReferenceException captured299 LOGGER.debug("waitUntil: StaleElementReferenceException", e);300 }301 return res;302 }303 304 305 /**306 * Wait until any condition happens.307 *308 * @param condition - ExpectedCondition.309 * @param timeout - timeout.310 * @return true if condition happen.311 */312 private boolean waitUntil(ExpectedCondition<?> condition, long timeout) {313 if (timeout < 1) {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<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 already1287 // sometime Appium instead printing valid StaleElementException generate java.lang.ClassCastException:1288 // com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to java.lang.String1289 LOGGER.debug("catched StaleElementReferenceException: ", e);1290 // try to find again using driver context and do action1291 element = this.findElement();1292 output = overrideAction(actionName, inputArgs);...
Source:ExtendedElementLocator.java
...116 }117 public SearchContext getSearchContext() {118 return searchContext;119 }120 public boolean isLocalized() {121 return localized;122 }123 public boolean isCaseInsensitive() {124 return caseInsensitive;125 }126 public String getClassName() {127 return className;128 }129 public CaseInsensitiveXPath getCaseInsensitiveXPath() {130 return caseInsensitiveXPath;131 }132}...
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver.locator;2import org.openqa.selenium.By;3import org.openqa.selenium.SearchContext;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.support.pagefactory.ElementLocator;6import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;7import org.openqa.selenium.support.pagefactory.internal.LocatingElementListHandler;8import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler;9import java.lang.reflect.Field;10import java.lang.reflect.InvocationHandler;11import java.lang.reflect.InvocationTargetException;12import java.lang.reflect.Method;13import java.lang.reflect.Proxy;14import java.util.List;15public class ExtendedElementLocatorFactory implements ElementLocatorFactory {16 private final SearchContext searchContext;17 public ExtendedElementLocatorFactory(SearchContext searchContext) {18 this.searchContext = searchContext;19 }20 public ElementLocator createLocator(Field field) {21 return new ExtendedElementLocator(searchContext, field);22 }23 public static class ExtendedElementLocator implements ElementLocator {24 private final SearchContext searchContext;25 private final boolean shouldCache;26 private final By by;27 private WebElement cachedElement;28 private List<WebElement> cachedElementList;29 public ExtendedElementLocator(SearchContext searchContext, Field field) {30 this.searchContext = searchContext;31 ExtendedFindBy find = field.getAnnotation(ExtendedFindBy.class);32 if (find == null) {33 throw new RuntimeException("Cannot find @ExtendedFindBy annotation on " + field);34 }35 shouldCache = find.shouldCache();36 by = find.buildBy();37 }38 public WebElement findElement() {39 if (cachedElement != null && shouldCache) {40 return cachedElement;41 }42 WebElement element = searchContext.findElement(by);43 if (shouldCache) {44 cachedElement = element;45 }46 return element;47 }48 public List<WebElement> findElements() {49 if (cachedElementList != null && shouldCache) {50 return cachedElementList;51 }52 List<WebElement> elements = searchContext.findElements(by);53 if (shouldCache) {54 cachedElementList = elements;55 }56 return elements;57 }58 public boolean isLocalized() {59 return !findElements().isEmpty();60 }61 }62 public static class ExtendedFieldDecorator implements org.openqa.selenium.support.pagefactory.FieldDecorator {63 private final SearchContext searchContext;64 public ExtendedFieldDecorator(SearchContext searchContext) {
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver.locator;2import org.openqa.selenium.By;3import org.openqa.selenium.SearchContext;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.support.pagefactory.ElementLocator;6import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;7import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElementList;8public class ExtendedElementLocator implements ElementLocator {9 private ExtendedElementLocatorFactory factory;10 private SearchContext searchContext;11 private By by;12 private boolean isElement;13 private boolean isElementList;14 public ExtendedElementLocator(ExtendedElementLocatorFactory factory, SearchContext searchContext, By by) {15 this.factory = factory;16 this.searchContext = searchContext;17 this.by = by;18 this.isElement = ExtendedWebElement.class.isAssignableFrom(factory.getField().getType());19 this.isElementList = ExtendedWebElementList.class.isAssignableFrom(factory.getField().getType());20 }21 public WebElement findElement() {22 if (isElement) {23 return new ExtendedWebElement(factory.getDriver(), searchContext, by);24 } else {25 return searchContext.findElement(by);26 }27 }28 public java.util.List<WebElement> findElements() {29 if (isElementList) {30 return new ExtendedWebElementList(factory.getDriver(), searchContext, by);31 } else {32 return searchContext.findElements(by);33 }34 }35 public By getBy() {36 return by;37 }38}39package com.qaprosoft.carina.core.foundation.webdriver.locator;40import org.openqa.selenium.By;41import org.openqa.selenium.SearchContext;42import org.openqa.selenium.WebElement;43import org.openqa.selenium.support.pagefactory.ElementLocator;44import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;45import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElementList;46public class ExtendedElementLocator implements ElementLocator {47 private ExtendedElementLocatorFactory factory;48 private SearchContext searchContext;49 private By by;50 private boolean isElement;51 private boolean isElementList;52 public ExtendedElementLocator(ExtendedElementLocatorFactory factory, SearchContext searchContext, By by) {53 this.factory = factory;54 this.searchContext = searchContext;55 this.by = by;
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver.locator;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.support.pagefactory.ElementLocator;6import com.qaprosoft.carina.core.foundation.utils.Configuration;7import com.qaprosoft.carina.core.foundation.utils.R;8public class ExtendedElementLocator implements ElementLocator {9 private final WebDriver driver;10 private final By by;11 public ExtendedElementLocator(WebDriver driver, By by) {12 this.driver = driver;13 this.by = by;14 }15 public WebElement findElement() {16 return driver.findElement(by);17 }18 public java.util.List<WebElement> findElements() {19 return driver.findElements(by);20 }21 public By getBy() {22 return by;23 }24 public static boolean isLocalized(String locator) {25 return locator.startsWith(Configuration.get(Configuration.Parameter.LOCALIZATOR_PREFIX));26 }27 public static By getLocalizedBy(String locator) {28 String key = locator.replaceFirst(Configuration.get(Configuration.Parameter.LOCALIZATOR_PREFIX), "");29 String value = R.TESTDATA.get(key);30 if (value == null) {31 throw new RuntimeException("Unable to find localized locator: " + locator);32 }33 return By.xpath(value);34 }35}36package com.qaprosoft.carina.core.foundation.webdriver.locator;37import org.openqa.selenium.By;38import org.openqa.selenium.WebDriver;39import org.openqa.selenium.WebElement;40import org.openqa.selenium.support.pagefactory.ElementLocator;41import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;42import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;43public class ExtendedElementLocatorFactory implements ElementLocatorFactory {44 private final WebDriver driver;45 public ExtendedElementLocatorFactory(WebDriver driver) {46 this.driver = driver;47 }48 public ElementLocator createLocator(org.openqa.selenium.By by) {49 return new ExtendedElementLocator(driver, by);50 }51 public WebElement createWebElement(org.openqa.selenium.By by) {52 return new ExtendedWebElement(driver, by);53 }54}
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver.locator;2import org.openqa.selenium.WebElement;3import org.openqa.selenium.support.pagefactory.ElementLocator;4import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;5public class ExtendedElementLocator implements ElementLocator {6 private final ElementLocator locator;7 public ExtendedElementLocator(ElementLocator locator) {8 this.locator = locator;9 }10 public WebElement findElement() {11 WebElement element = locator.findElement();12 return new ExtendedWebElement(element);13 }14 public java.util.List<WebElement> findElements() {15 java.util.List<WebElement> elements = locator.findElements();16 java.util.List<WebElement> extendedElements = new java.util.ArrayList<WebElement>();17 for (WebElement element : elements) {18 extendedElements.add(new ExtendedWebElement(element));19 }20 return extendedElements;21 }22}23package com.qaprosoft.carina.core.foundation.webdriver.decorator;24import java.lang.reflect.InvocationHandler;25import java.lang.reflect.Method;26import java.lang.reflect.Proxy;27import java.util.List;28import org.openqa.selenium.By;29import org.openqa.selenium.JavascriptExecutor;30import org.openqa.selenium.NoSuchElementException;31import org.openqa.selenium.SearchContext;32import org.openqa.selenium.StaleElementReferenceException;33import org.openqa.selenium.WebDriver;34import org.openqa.selenium.WebElement;35import org.openqa.selenium.internal.WrapsDriver;36import org.openqa.selenium.internal.WrapsElement;37import org.openqa.selenium.remote.RemoteWebDriver;38import org.openqa.selenium.support.pagefactory.ElementLocator;39import org.openqa.selenium.support.ui.ExpectedCondition;40import org.openqa.selenium.support.ui.FluentWait;41import org.openqa.selenium.support.ui.Select;42import org.openqa.selenium.support.ui.Wait;43import org.slf4j.Logger;44import org.slf4j.LoggerFactory;45import com.qaprosoft.carina.core.foundation.commons.SpecialKeywords;46import com.qaprosoft.carina.core.foundation.commons.SpecialKeywords.PageType;47import com.qaprosoft.carina.core.foundation.exception.DriverNotInitializedException;48import com.qaprosoft.carina.core.foundation.exception.NotImplementedException;49import com.qaprosoft.carina.core.foundation.webdriver.DriverPool;50import com.qaprosoft.carina.core.foundation.webdriver.Screenshot;51import com.qaprosoft.carina.core.foundation.webdriver.decorator.factory.ExtendedElementFactory;52import com.qaprosoft.carina.core.foundation.webdriver.listener.EventF
isLocalized
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.WebElement;3import org.openqa.selenium.support.pagefactory.ElementLocator;4import org.testng.Assert;5import org.testng.annotations.Test;6import com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocator;7public class LocalizationTest {8 public void testLocalization() {9 WebElement element = new WebElement() {10 public void click() {11 }12 public void submit() {13 }14 public void sendKeys(CharSequence... keysToSend) {15 }16 public void clear() {17 }18 public String getTagName() {19 return null;20 }21 public String getAttribute(String name) {22 return null;23 }24 public boolean isSelected() {25 return false;26 }27 public boolean isEnabled() {28 return false;29 }30 public String getText() {31 return null;32 }33 public java.util.List<WebElement> findElements(By by) {34 return null;35 }36 public WebElement findElement(By by) {37 return null;38 }39 public boolean isDisplayed() {40 return false;41 }42 public Point getLocation() {43 return null;44 }45 public Dimension getSize() {46 return null;47 }48 public Rectangle getRect() {49 return null;50 }51 public String getCssValue(String propertyName) {52 return null;53 }54 public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {55 return null;56 }57 };58 ElementLocator locator = new ExtendedElementLocator(element, "test");59 Assert.assertEquals(locator.isLocalized(), true);60 }61}62import org.openqa.selenium.By;63import org.openqa.selenium.WebElement;64import org.openqa.selenium.support.pagefactory.ElementLocator;65import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;66import org.testng.Assert;67import org.testng.annotations.Test;68import com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocatorFactory;69public class LocalizationTest {
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver.locator;2import java.lang.reflect.Field;3import org.openqa.selenium.support.pagefactory.ElementLocator;4public class ExtendedElementLocator implements ElementLocator {5 private final Field field;6 public ExtendedElementLocator(Field field) {7 this.field = field;8 }9 public String toString() {10 return "ExtendedElementLocator [field=" + field + "]";11 }12 public boolean isLocalized() {13 return (field.getAnnotation(ExtendedFindBy.class) != null);14 }15}16package com.qaprosoft.carina.core.foundation.webdriver.locator;17import java.lang.reflect.Field;18import org.openqa.selenium.support.pagefactory.ElementLocator;19import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;20public class ExtendedElementLocatorFactory implements ElementLocatorFactory {21 private final Field field;22 public ExtendedElementLocatorFactory(Field field) {23 this.field = field;24 }25 public ElementLocator createLocator(Field field) {26 return new ExtendedElementLocator(field);27 }28 public boolean isLocalized() {29 return (field.getAnnotation(ExtendedFindBy.class) != null);30 }31}32package com.qaprosoft.carina.core.foundation.webdriver.locator;33import java.lang.reflect.Field;34import java.lang.reflect.InvocationTargetException;35import java.lang.reflect.Method;36import org.openqa.selenium.By;37import org.openqa.selenium.SearchContext;38import org.openqa.selenium.WebElement;39import org.openqa.selenium.support.pagefactory.Annotations;40import org.openqa.selenium.support.pagefactory.DefaultElementLocator;41import org.openqa.selenium.support.pagefactory.ElementLocator;42import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;43public class ExtendedElementLocatorFactory implements ElementLocatorFactory {44 private final SearchContext searchContext;45 public ExtendedElementLocatorFactory(SearchContext searchContext) {46 this.searchContext = searchContext;47 }48 public ElementLocator createLocator(Field field) {49 return new ExtendedElementLocator(searchContext, field);50 }51 public boolean isLocalized() {52 return (field.getAnnotation(ExtendedFindBy.class) != null);53 }54}
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.demo;2import java.io.File;3import java.io.IOException;4import java.lang.reflect.Field;5import java.util.ArrayList;6import java.util.List;7import org.apache.log4j.Logger;8import org.openqa.selenium.By;9import org.openqa.selenium.WebDriver;10import org.openqa.selenium.WebElement;11import org.openqa.selenium.support.FindBy;12import org.openqa.selenium.support.PageFactory;13import org.openqa.selenium.support.pagefactory.Annotations;14import org.openqa.selenium.support.pagefactory.DefaultElementLocatorFactory;15import org.openqa.selenium.support.pagefactory.ElementLocator;16import org.openqa.selenium.support.pagefactory.FieldDecorator;17import org.testng.Assert;18import org.testng.annotations.Test;19import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedElementLocatorFactory;20import com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocator;21import com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocatorFactory;22import com.qaprosoft.carina.core.fo
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver.locator;2import java.lang.reflect.Field;3import java.util.ArrayList;4import java.util.List;5import java.util.Locale;6import org.apache.log4j.Logger;7import org.openqa.selenium.By;8import org.openqa.selenium.SearchContext;9import org.openqa.selenium.WebElement;10import org.openqa.selenium.support.pagefactory.Annotations;11import org.openqa.selenium.support.pagefactory.ElementLocator;12import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;13import com.qaprosoft.carina.core.foundation.commons.SpecialKeywords;14import com.qaprosoft.carina.core.foundation.utils.Configuration;15public class ExtendedElementLocatorFactory implements ElementLocatorFactory {16 private static final Logger LOGGER = Logger.getLogger(ExtendedElementLocatorFactory.class);17 private final SearchContext searchContext;18 public ExtendedElementLocatorFactory(SearchContext searchContext) {19 this.searchContext = searchContext;20 }21 public ElementLocator createLocator(Field field) {22 return new ExtendedElementLocator(searchContext, field);23 }24 private class ExtendedElementLocator implements ElementLocator {25 private final SearchContext searchContext;26 private final boolean shouldCache;27 private final By by;28 private final String name;29 private final String type;30 private final String pageName;31 private final String locale;32 public ExtendedElementLocator(SearchContext searchContext, Field field) {33 this.searchContext = searchContext;34 this.locale = Configuration.get(Configuration.Parameter.LOCALE);35 Annotations annotations = new Annotations(field);36 this.shouldCache = annotations.isLookupCached();37 this.name = annotations.buildBy().toString();38 this.type = field.getType().getName();39 this.pageName = field.getDeclaringClass().getName();40 this.by = buildByFromShortFindBy(annotations);41 }42 public WebElement findElement() {43 if (shouldCache) {44 return new ExtendedWebElement(searchContext.findElement(by), name, type, pageName, locale);45 } else {46 return new ExtendedWebElement(searchContext, by, name, type, pageName, locale);47 }48 }49 public List<WebElement> findElements() {50 List<WebElement> elements = searchContext.findElements(by);51 List<WebElement> extendedElements = new ArrayList<WebElement>();52 for (WebElement element : elements) {53 extendedElements.add(new ExtendedWebElement(element, name,
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver.decorator;2import java.lang.reflect.Field;3import java.util.List;4import org.openqa.selenium.By;5import org.openqa.selenium.SearchContext;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.support.pagefactory.ElementLocator;8import org.openqa.selenium.support.pagefactory.FieldDecorator;9import org.slf4j.Logger;10import org.slf4j.LoggerFactory;11import com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocator;12import com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocatorFactory;13import com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocatorFactory.LocatorType;14 * interface {@link org.openqa.selenium.WebElement} and decorate it with the15public class ExtendedFieldDecorator implements FieldDecorator {16 private static final Logger LOGGER = LoggerFactory.getLogger(ExtendedFieldDecorator.class);17 private final ExtendedElementLocatorFactory factory;18 public ExtendedFieldDecorator(SearchContext searchContext) {19 this.factory = new ExtendedElementLocatorFactory(searchContext);20 }21 public Object decorate(ClassLoader loader, Field field) {22 if (!WebElement.class.isAssignableFrom(field.getType()) && !List.class.isAssignableFrom(field.getType())) {23 return null;24 }25 ElementLocator locator = factory.createLocator(field);26 if (locator instanceof ExtendedElementLocator) {27 ExtendedElementLocator extendedLocator = (ExtendedElementLocator) locator;28 if (extendedLocator.getLocatorType() == LocatorType.XPATH) {29 String xpath = extendedLocator.getXpath();30 if (xpath.contains("{") && xpath.contains("}")) {31 LOGGER.debug("Try to localize xpath: " + xpath);
isLocalized
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.webdriver.locator;2import org.openqa.selenium.By;3import org.openqa.selenium.SearchContext;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.support.pagefactory.ElementLocator;6import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;7import com.qaprosoft.carina.core.foundation.utils.Configuration;8import com.qaprosoft.carina.core.foundation.utils.R;9import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;10public class ExtendedElementLocatorFactory implements ElementLocatorFactory {11private final SearchContext searchContext;12private final WebDriver driver;13public ExtendedElementLocatorFactory(WebDriver driver) {14this.searchContext = driver;15this.driver = driver;16}17public ExtendedElementLocatorFactory(SearchContext searchContext) {18this.searchContext = searchContext;19this.driver = null;20}21public ElementLocator createLocator(Field field) {22return new ExtendedElementLocator(searchContext, field, driver);23}24}25package com.qaprosoft.carina.core.foundation.webdriver.locator;26import org.apache.log4j.Logger;27import org.openqa.selenium.By;28import org.openqa.selenium.SearchContext;29import org.openqa.selenium.WebDriver;30import org.openqa.selenium.support.pagefactory.Annotations;31import org.openqa.selenium.support.pagefactory.ElementLocator;32import com.qaprosoft.carina.core.foundation.utils.Configuration;33import com.qaprosoft.carina.core.foundation.utils.R;34import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;35public class ExtendedElementLocator implements ElementLocator {36private static final Logger LOGGER = Logger.getLogger(ExtendedElementLocator.class);37private final SearchContext searchContext;38private final boolean shouldCache;39private final By by;40private final WebDriver driver;41private ExtendedWebElement cachedElement;42private ExtendedWebElement[] cachedElementList;43public ExtendedElementLocator(SearchContext searchContext, Field field, WebDriver driver) {44this.searchContext = searchContext;45this.driver = driver;46Annotations annotations = new Annotations(field);47shouldCache = annotations.isLookupCached();48by = isLocalized(field) ? getLocalizedBy(annotations)
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!!