How to use DriverListener class of com.qaprosoft.carina.core.foundation.webdriver.listener package

Best Carina code snippet using com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener

Source:ExtendedWebElement.java Github

copy

Full Screen

...69import com.qaprosoft.carina.core.foundation.utils.common.CommonUtils;70import com.qaprosoft.carina.core.foundation.utils.resources.L10N;71import com.qaprosoft.carina.core.foundation.webdriver.IDriverPool;72import com.qaprosoft.carina.core.foundation.webdriver.decorator.annotations.CaseInsensitiveXPath;73import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;74import com.qaprosoft.carina.core.foundation.webdriver.locator.ExtendedElementLocator;75import com.qaprosoft.carina.core.foundation.webdriver.locator.LocatorType;76import com.qaprosoft.carina.core.foundation.webdriver.locator.converter.LocatorConverter;77import com.qaprosoft.carina.core.foundation.webdriver.locator.converter.caseinsensitive.CaseInsensitiveConverter;78import com.qaprosoft.carina.core.foundation.webdriver.locator.converter.caseinsensitive.ParamsToConvert;79import com.qaprosoft.carina.core.foundation.webdriver.locator.converter.caseinsensitive.Platform;80import com.sun.jersey.core.util.Base64;81import io.appium.java_client.MobileBy;82public class ExtendedWebElement implements IWebElement {83 private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());84 private static final long EXPLICIT_TIMEOUT = Configuration.getLong(Parameter.EXPLICIT_TIMEOUT);85 private static final long RETRY_TIME = Configuration.getLong(Parameter.RETRY_INTERVAL);86 87 // we should keep both properties: driver and searchContext obligatory88 // driver is used for actions, javascripts execution etc89 // searchContext is used for searching element by default90 private WebDriver driver;91 private SearchContext searchContext;92 private CryptoTool cryptoTool = new CryptoTool(Configuration.getCryptoParams());93 private static Pattern CRYPTO_PATTERN = Pattern.compile(SpecialKeywords.CRYPT);94 private WebElement element = null;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&lt;String&gt; match=new766 * BaseMatcher&lt;String&gt;() { {@literal @}Override public boolean767 * matches(Object actual) { return actual.toString().contains(RequiredText);768 * } {@literal @}Override public void describeTo(Description description) {769 * } };770 */771 public boolean selectByMatcher(final BaseMatcher<String> matcher) {772 return (boolean) doAction(ACTION_NAME.SELECT_BY_MATCHER, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), matcher);773 }774 /**775 * Selects first value according to partial text value.776 *777 * @param partialSelectText select by partial text778 * @return true if item selected, otherwise false.779 */780 public boolean selectByPartialText(final String partialSelectText) {781 return (boolean) doAction(ACTION_NAME.SELECT_BY_PARTIAL_TEXT, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()),782 partialSelectText);783 }784 /**785 * Selects item by index in specified select element.786 *787 * @param index to select by788 * @return true if item selected, otherwise false.789 */790 public boolean select(final int index) {791 return (boolean) doAction(ACTION_NAME.SELECT_BY_INDEX, EXPLICIT_TIMEOUT, getDefaultCondition(getBy()), index);792 }793 // --------------------------------------------------------------------------794 // Base UI validations795 // --------------------------------------------------------------------------796 /**797 * Check that element present and visible.798 *799 * @return element existence status.800 */801 public boolean isElementPresent() {802 return isElementPresent(EXPLICIT_TIMEOUT);803 }804 /**805 * Check that element present and visible within specified timeout.806 *807 * @param timeout - timeout.808 * @return element existence status.809 */810 public boolean isElementPresent(long timeout) {811 // perform at once super-fast single selenium call and only if nothing found move to waitAction812 if (element != null) {813 try {814 if (element.isDisplayed()) {815 return true;816 }817 } catch (Exception e) {818 //do nothing as element is not found as expected here819 }820 }821 ExpectedCondition<?> waitCondition;822 823 // [VD] replace presenceOfElementLocated and visibilityOf conditions by single "visibilityOfElementLocated"824 // visibilityOf: Does not check for presence of the element as the error explains it.825 // visibilityOfElementLocated: Checks to see if the element is present and also visible. To check visibility, it makes sure that the element826 // has a height and width greater than 0.827 828 waitCondition = ExpectedConditions.visibilityOfElementLocated(getBy());829 return waitUntil(waitCondition, timeout);830 }831 /**832 * Check that element not present and not visible within specified timeout.833 *834 * @param timeout - timeout.835 * @return element existence status.836 */837 public boolean isElementNotPresent(long timeout) {838 return !isElementPresent(timeout);839 }840 /**841 * Checks that element clickable.842 *843 * @return element clickability status.844 */845 public boolean isClickable() {846 return isClickable(EXPLICIT_TIMEOUT);847 }848 /**849 * Check that element clickable within specified timeout.850 *851 * @param timeout - timeout.852 * @return element clickability status.853 */854 public boolean isClickable(long timeout) {855 ExpectedCondition<?> waitCondition;856 857 if (element != null) {858 waitCondition = ExpectedConditions.elementToBeClickable(element);859 } else {860 waitCondition = ExpectedConditions.elementToBeClickable(getBy());861 }862 863 return waitUntil(waitCondition, timeout);864 }865 /**866 * Checks that element visible.867 *868 * @return element visibility status.869 */870 public boolean isVisible() {871 return isVisible(EXPLICIT_TIMEOUT);872 }873 /**874 * Check that element visible within specified timeout.875 *876 * @param timeout - timeout.877 * @return element visibility status.878 */879 public boolean isVisible(long timeout) {880 ExpectedCondition<?> waitCondition;881 if (element != null) {882 waitCondition = ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(getBy()),883 ExpectedConditions.visibilityOf(element));884 } else {885 waitCondition = ExpectedConditions.visibilityOfElementLocated(getBy());886 }887 boolean res = false;888 try {889 res = waitUntil(waitCondition, timeout);890 } catch (StaleElementReferenceException e) {891 // there is no sense to continue as StaleElementReferenceException captured892 LOGGER.debug("waitUntil: StaleElementReferenceException", e);893 }894 895 return res;896 }897 898 /**899 * Check that element with text present.900 *901 * @param text of element to check.902 * @return element with text existence status.903 */904 public boolean isElementWithTextPresent(final String text) {905 return isElementWithTextPresent(text, EXPLICIT_TIMEOUT);906 }907 /**908 * Check that element with text present.909 *910 * @param text of element to check.911 * @param timeout - timeout.912 * @return element with text existence status.913 */914 public boolean isElementWithTextPresent(final String text, long timeout) {915 final String decryptedText = cryptoTool.decryptByPattern(text, CRYPTO_PATTERN);916 ExpectedCondition<Boolean> textCondition;917 if (element != null) {918 textCondition = ExpectedConditions.textToBePresentInElement(element, decryptedText);919 } else {920 textCondition = ExpectedConditions.textToBePresentInElementLocated(getBy(), decryptedText);921 }922 return waitUntil(textCondition, timeout);923 //TODO: restore below code as only projects are migrated to "isElementWithContainTextPresent"924// return waitUntil(ExpectedConditions.and(ExpectedConditions.presenceOfElementLocated(getBy()),925// ExpectedConditions.textToBe(getBy(), decryptedText)), timeout);926 }927 928 public void assertElementWithTextPresent(final String text) {929 assertElementWithTextPresent(text, EXPLICIT_TIMEOUT);930 }931 public void assertElementWithTextPresent(final String text, long timeout) {932 if (!isElementWithTextPresent(text, timeout)) {933 Assert.fail(Messager.ELEMENT_WITH_TEXT_NOT_PRESENT.getMessage(getNameWithLocator(), text));934 }935 }936 937 public void assertElementPresent() {938 assertElementPresent(EXPLICIT_TIMEOUT);939 }940 public void assertElementPresent(long timeout) {941 if (!isPresent(timeout)) {942 Assert.fail(Messager.ELEMENT_NOT_PRESENT.getMessage(getNameWithLocator()));943 }944 }945 /**946 * Find Extended Web Element on page using By starting search from this947 * object.948 *949 * @param by Selenium By locator950 * @return ExtendedWebElement if exists otherwise null.951 */952 public ExtendedWebElement findExtendedWebElement(By by) {953 return findExtendedWebElement(by, by.toString(), EXPLICIT_TIMEOUT);954 }955 /**956 * Find Extended Web Element on page using By starting search from this957 * object.958 *959 * @param by Selenium By locator960 * @param timeout to wait961 * @return ExtendedWebElement if exists otherwise null.962 */963 public ExtendedWebElement findExtendedWebElement(By by, long timeout) {964 return findExtendedWebElement(by, by.toString(), timeout);965 }966 /**967 * Find Extended Web Element on page using By starting search from this968 * object.969 *970 * @param by Selenium By locator971 * @param name Element name972 * @return ExtendedWebElement if exists otherwise null.973 */974 public ExtendedWebElement findExtendedWebElement(final By by, String name) {975 return findExtendedWebElement(by, name, EXPLICIT_TIMEOUT);976 }977 /**978 * Find Extended Web Element on page using By starting search from this979 * object.980 *981 * @param by Selenium By locator982 * @param name Element name983 * @param timeout Timeout to find984 * @return ExtendedWebElement if exists otherwise null.985 */986 public ExtendedWebElement findExtendedWebElement(final By by, String name, long timeout) {987 if (isPresent(by, timeout)) {988 return new ExtendedWebElement(by, name, this.driver, this.searchContext);989 } else {990 throw new NoSuchElementException(SpecialKeywords.NO_SUCH_ELEMENT_ERROR + by.toString());991 }992 }993 public List<ExtendedWebElement> findExtendedWebElements(By by) {994 return findExtendedWebElements(by, EXPLICIT_TIMEOUT);995 }996 public List<ExtendedWebElement> findExtendedWebElements(final By by, long timeout) {997 List<ExtendedWebElement> extendedWebElements = new ArrayList<ExtendedWebElement>();998 List<WebElement> webElements = new ArrayList<WebElement>();999 1000 if (isPresent(by, timeout)) {1001 webElements = getElement().findElements(by);1002 } else {1003 throw new NoSuchElementException(SpecialKeywords.NO_SUCH_ELEMENT_ERROR + by.toString());1004 }1005 int i = 1;1006 for (WebElement element : webElements) {1007 String name = "undefined";1008 try {1009 name = element.getText();1010 } catch (Exception e) {1011 /* do nothing */1012 LOGGER.debug("Error while getting text from element.", e);1013 }1014 // we can't initiate ExtendedWebElement using by as it belongs to the list of elements1015 extendedWebElements.add(new ExtendedWebElement(generateByForList(by, i), name, this.driver, this.searchContext));1016 i++;1017 }1018 return extendedWebElements;1019 }1020 public boolean waitUntilElementDisappear(final long timeout) {1021 try {1022 if (this.element == null) {1023 // if element not found it will cause NoSuchElementException1024 findElement();1025 } else {1026 // if element is stale, it will cause StaleElementReferenceException1027 this.element.isDisplayed();1028 }1029 return waitUntil(ExpectedConditions.or(ExpectedConditions.stalenessOf(this.element),1030 ExpectedConditions.invisibilityOf(this.element)),1031 timeout);1032 } catch (NoSuchElementException | StaleElementReferenceException e) {1033 // element not present so means disappear1034 return true;1035 }1036 }1037 public ExtendedWebElement format(Object... objects) {1038 String locator = by.toString();1039 By by = null;1040 if (locator.startsWith(LocatorType.ID.getStartsWith())) {1041 if (caseInsensitiveConverter != null) {1042 by = caseInsensitiveConverter.convert(by);1043 } else {1044 by = By.id(String.format(StringUtils.remove(locator, LocatorType.ID.getStartsWith()), objects));1045 }1046 }1047 if (locator.startsWith(LocatorType.NAME.getStartsWith())) {1048 if (caseInsensitiveConverter != null) {1049 by = caseInsensitiveConverter.convert(by);1050 } else {1051 by = By.id(String.format(StringUtils.remove(locator, LocatorType.NAME.getStartsWith()), objects));1052 }1053 }1054 if (locator.startsWith(LocatorType.XPATH.getStartsWith())) {1055 if (caseInsensitiveConverter != null) {1056 by = caseInsensitiveConverter.convert(by);1057 } else {1058 by = By.xpath(String.format(StringUtils.remove(locator, LocatorType.XPATH.getStartsWith()), objects));1059 }1060 }1061 if (locator.startsWith(LocatorType.LINKTEXT.getStartsWith())) {1062 if (caseInsensitiveConverter != null) {1063 by = caseInsensitiveConverter.convert(by);1064 } else {1065 by = By.xpath(String.format(StringUtils.remove(locator, LocatorType.LINKTEXT.getStartsWith()), objects));1066 }1067 }1068 if (locator.startsWith("partialLinkText: ")) {1069 by = By.partialLinkText(String.format(StringUtils.remove(locator, "partialLinkText: "), objects));1070 }1071 if (locator.startsWith("css: ")) {1072 by = By.cssSelector(String.format(StringUtils.remove(locator, "css: "), objects));1073 }1074 if (locator.startsWith("tagName: ")) {1075 by = By.tagName(String.format(StringUtils.remove(locator, "tagName: "), objects));1076 }1077 /*1078 * All ClassChain locators start from **. e.g FindBy(xpath = "**'/XCUIElementTypeStaticText[`name CONTAINS[cd] '%s'`]")1079 */1080 if (locator.startsWith("By.IosClassChain: **")) {1081 by = MobileBy.iOSClassChain(String.format(StringUtils.remove(locator, "By.IosClassChain: "), objects));1082 }1083 if (locator.startsWith("By.IosNsPredicate: **")) {1084 by = MobileBy.iOSNsPredicateString(String.format(StringUtils.remove(locator, "By.IosNsPredicate: "), objects));1085 }1086 if (locator.startsWith("By.AccessibilityId: ")) {1087 by = MobileBy.AccessibilityId(String.format(StringUtils.remove(locator, "By.AccessibilityId: "), objects));1088 }1089 if (locator.startsWith("By.Image: ")) {1090 String formattedLocator = String.format(StringUtils.remove(locator, "By.Image: "), objects);1091 Path path = Paths.get(formattedLocator);1092 LOGGER.debug("Formatted locator is : " + formattedLocator);1093 String base64image;1094 try {1095 base64image = new String(Base64.encode(Files.readAllBytes(path)));1096 } catch (IOException e) {1097 throw new RuntimeException(1098 "Error while reading image file after formatting. Formatted locator : " + formattedLocator, e);1099 }1100 LOGGER.debug("Base64 image representation has benn successfully obtained after formatting.");1101 by = MobileBy.image(base64image);1102 }1103 if (locator.startsWith("By.AndroidUIAutomator: ")) {1104 by = MobileBy.AndroidUIAutomator(String.format(StringUtils.remove(locator, "By.AndroidUIAutomator: "), objects));1105 LOGGER.debug("Formatted locator is : " + by.toString());1106 }1107 return new ExtendedWebElement(by, name, this.driver, this.searchContext, objects);1108 }1109 /**1110 * Pause for specified timeout.1111 * 1112 * @param timeout in seconds.1113 */1114 public void pause(long timeout) {1115 CommonUtils.pause(timeout);1116 }1117 public void pause(double timeout) {1118 CommonUtils.pause(timeout);1119 }1120 1121 public interface ActionSteps {1122 void doClick();1123 1124 void doClickByJs();1125 1126 void doClickByActions();1127 1128 void doDoubleClick();1129 void doRightClick();1130 1131 void doHover(Integer xOffset, Integer yOffset);1132 void doType(String text);1133 void doSendKeys(Keys keys);1134 void doAttachFile(String filePath);1135 void doCheck();1136 void doUncheck();1137 1138 boolean doIsChecked();1139 1140 String doGetText();1141 Point doGetLocation();1142 Dimension doGetSize();1143 String doGetAttribute(String name);1144 boolean doSelect(String text);1145 boolean doSelectValues(final String[] values);1146 boolean doSelectByMatcher(final BaseMatcher<String> matcher);1147 boolean doSelectByPartialText(final String partialSelectText);1148 boolean doSelectByIndex(final int index);1149 1150 String doGetSelectedValue();1151 1152 List<String> doGetSelectedValues();1153 }1154 private Object executeAction(ACTION_NAME actionName, ActionSteps actionSteps, Object... inputArgs) {1155 Object result = null;1156 switch (actionName) {1157 case CLICK:1158 actionSteps.doClick();1159 break;1160 case CLICK_BY_JS:1161 actionSteps.doClickByJs();1162 break;1163 case CLICK_BY_ACTIONS:1164 actionSteps.doClickByActions();1165 break;1166 case DOUBLE_CLICK:1167 actionSteps.doDoubleClick();1168 break;1169 case HOVER:1170 actionSteps.doHover((Integer) inputArgs[0], (Integer) inputArgs[1]);1171 break;1172 case RIGHT_CLICK:1173 actionSteps.doRightClick();1174 break;1175 case GET_TEXT:1176 result = actionSteps.doGetText();1177 break;1178 case GET_LOCATION:1179 result = actionSteps.doGetLocation();1180 break;1181 case GET_SIZE:1182 result = actionSteps.doGetSize();1183 break;1184 case GET_ATTRIBUTE:1185 result = actionSteps.doGetAttribute((String) inputArgs[0]);1186 break;1187 case SEND_KEYS:1188 actionSteps.doSendKeys((Keys) inputArgs[0]);1189 break;1190 case TYPE:1191 actionSteps.doType((String) inputArgs[0]);1192 break;1193 case ATTACH_FILE:1194 actionSteps.doAttachFile((String) inputArgs[0]);1195 break;1196 case CHECK:1197 actionSteps.doCheck();1198 break;1199 case UNCHECK:1200 actionSteps.doUncheck();1201 break;1202 case IS_CHECKED:1203 result = actionSteps.doIsChecked();1204 break;1205 case SELECT:1206 result = actionSteps.doSelect((String) inputArgs[0]);1207 break;1208 case SELECT_VALUES:1209 result = actionSteps.doSelectValues((String[]) inputArgs);1210 break;1211 case SELECT_BY_MATCHER:1212 result = actionSteps.doSelectByMatcher((BaseMatcher<String>) inputArgs[0]);1213 break;1214 case SELECT_BY_PARTIAL_TEXT:1215 result = actionSteps.doSelectByPartialText((String) inputArgs[0]);1216 break;1217 case SELECT_BY_INDEX:1218 result = actionSteps.doSelectByIndex((int) inputArgs[0]);1219 break;1220 case GET_SELECTED_VALUE:1221 result = actionSteps.doGetSelectedValue();1222 break;1223 case GET_SELECTED_VALUES:1224 result = actionSteps.doGetSelectedValues();1225 break;1226 default:1227 Assert.fail("Unsupported UI action name" + actionName.toString());1228 break;1229 }1230 return result;1231 }1232 /**1233 * doAction on element.1234 *1235 * @param actionName1236 * ACTION_NAME1237 * @param timeout1238 * long1239 * @param waitCondition1240 * to check element conditions before action1241 * @return1242 * Object1243 */1244 private Object doAction(ACTION_NAME actionName, long timeout, ExpectedCondition<?> waitCondition) {1245 // [VD] do not remove null args otherwise all actions without arguments will be broken!1246 Object nullArgs = null;1247 return doAction(actionName, timeout, waitCondition, nullArgs);1248 }1249 private Object doAction(ACTION_NAME actionName, long timeout, ExpectedCondition<?> waitCondition,1250 Object...inputArgs) {1251 1252 if (waitCondition != null) {1253 //do verification only if waitCondition is not null1254 if (!waitUntil(waitCondition, timeout)) {1255 //TODO: think about raising exception otherwise we do extra call and might wait and hangs especially for mobile/appium1256 LOGGER.error(Messager.ELEMENT_CONDITION_NOT_VERIFIED.getMessage(actionName.getKey(), getNameWithLocator()));1257 }1258 }1259 1260 if (isLocalized) {1261 isLocalized = false; // single verification is enough for this particular element1262 L10N.verify(this);1263 }1264 Object output = null;1265 try {1266 this.element = getElement();1267 output = overrideAction(actionName, inputArgs);1268 } catch (StaleElementReferenceException e) {1269 //TODO: analyze mobile testing for staled elements. Potentially it should be fixed by appium java client already1270 // sometime Appium instead printing valid StaleElementException generate java.lang.ClassCastException:1271 // com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to java.lang.String1272 LOGGER.debug("catched StaleElementReferenceException: ", e);1273 // try to find again using driver context and do action1274 element = this.findElement();1275 output = overrideAction(actionName, inputArgs);1276 }1277 return output;1278 }1279 // single place for all supported UI actions in carina core1280 private Object overrideAction(ACTION_NAME actionName, Object...inputArgs) {1281 Object output = executeAction(actionName, new ActionSteps() {1282 @Override1283 public void doClick() {1284 DriverListener.setMessages(Messager.ELEMENT_CLICKED.getMessage(getName()),1285 Messager.ELEMENT_NOT_CLICKED.getMessage(getNameWithLocator()));1286 element.click();1287 }1288 1289 @Override1290 public void doClickByJs() {1291 DriverListener.setMessages(Messager.ELEMENT_CLICKED.getMessage(getName()),1292 Messager.ELEMENT_NOT_CLICKED.getMessage(getNameWithLocator()));1293 LOGGER.info("Do click by JavascriptExecutor for element: " + getNameWithLocator());1294 JavascriptExecutor executor = (JavascriptExecutor) getDriver();1295 executor.executeScript("arguments[0].click();", element);1296 }1297 1298 @Override1299 public void doClickByActions() {1300 DriverListener.setMessages(Messager.ELEMENT_CLICKED.getMessage(getName()),1301 Messager.ELEMENT_NOT_CLICKED.getMessage(getNameWithLocator()));1302 LOGGER.info("Do click by Actions for element: " + getNameWithLocator());1303 Actions actions = new Actions(getDriver());1304 actions.moveToElement(element).click().perform();1305 } 1306 1307 @Override1308 public void doDoubleClick() {1309 DriverListener.setMessages(Messager.ELEMENT_DOUBLE_CLICKED.getMessage(getName()),1310 Messager.ELEMENT_NOT_DOUBLE_CLICKED.getMessage(getNameWithLocator()));1311 1312 WebDriver drv = getDriver();1313 Actions action = new Actions(drv);1314 action.moveToElement(element).doubleClick(element).build().perform();1315 }1316 1317 @Override1318 public void doHover(Integer xOffset, Integer yOffset) {1319 DriverListener.setMessages(Messager.ELEMENT_HOVERED.getMessage(getName()),1320 Messager.ELEMENT_NOT_HOVERED.getMessage(getNameWithLocator()));1321 1322 WebDriver drv = getDriver();1323 Actions action = new Actions(drv);1324 if (xOffset != null && yOffset!= null) {1325 action.moveToElement(element, xOffset, yOffset).build().perform();1326 } else {1327 action.moveToElement(element).build().perform();1328 }1329 }1330 1331 @Override1332 public void doSendKeys(Keys keys) {1333 DriverListener.setMessages(Messager.KEYS_SEND_TO_ELEMENT.getMessage(keys.toString(), getName()),1334 Messager.KEYS_NOT_SEND_TO_ELEMENT.getMessage(keys.toString(), getNameWithLocator()));1335 element.sendKeys(keys);1336 }1337 @Override1338 public void doType(String text) {1339 final String decryptedText = cryptoTool.decryptByPattern(text, CRYPTO_PATTERN);1340/* if (!element.getText().isEmpty()) {1341 DriverListener.setMessages(Messager.KEYS_CLEARED_IN_ELEMENT.getMessage(getName()),1342 Messager.KEYS_NOT_CLEARED_IN_ELEMENT.getMessage(getNameWithLocator()));1343 element.clear();1344 }1345*/1346 DriverListener.setMessages(Messager.KEYS_CLEARED_IN_ELEMENT.getMessage(getName()),1347 Messager.KEYS_NOT_CLEARED_IN_ELEMENT.getMessage(getNameWithLocator()));1348 element.clear();1349 String textLog = (!decryptedText.equals(text) ? "********" : text);1350 DriverListener.setMessages(Messager.KEYS_SEND_TO_ELEMENT.getMessage(textLog, getName()),1351 Messager.KEYS_NOT_SEND_TO_ELEMENT.getMessage(textLog, getNameWithLocator()));1352 element.sendKeys(decryptedText);1353 }1354 @Override1355 public void doAttachFile(String filePath) {1356 final String decryptedText = cryptoTool.decryptByPattern(filePath, CRYPTO_PATTERN);1357 String textLog = (!decryptedText.equals(filePath) ? "********" : filePath);1358 DriverListener.setMessages(Messager.FILE_ATTACHED.getMessage(textLog, getName()),1359 Messager.FILE_NOT_ATTACHED.getMessage(textLog, getNameWithLocator()));1360 ((JavascriptExecutor) getDriver()).executeScript("arguments[0].style.display = 'block';", element);1361 ((RemoteWebDriver) castDriver(getDriver())).setFileDetector(new LocalFileDetector());1362 element.sendKeys(decryptedText);1363 }1364 @Override1365 public String doGetText() {1366 String text = element.getText();1367 LOGGER.debug(Messager.ELEMENT_ATTRIBUTE_FOUND.getMessage("Text", text, getName()));1368 return text;1369 }1370 @Override1371 public Point doGetLocation() {1372 Point point = element.getLocation();1373 LOGGER.debug(Messager.ELEMENT_ATTRIBUTE_FOUND.getMessage("Location", point.toString(), getName()));1374 return point;1375 }1376 @Override1377 public Dimension doGetSize() {1378 Dimension dim = element.getSize();1379 LOGGER.debug(Messager.ELEMENT_ATTRIBUTE_FOUND.getMessage("Size", dim.toString(), getName()));1380 return dim;1381 }1382 @Override1383 public String doGetAttribute(String name) {1384 String attribute = element.getAttribute(name);1385 LOGGER.debug(Messager.ELEMENT_ATTRIBUTE_FOUND.getMessage(name, attribute, getName()));1386 return attribute;1387 }1388 @Override1389 public void doRightClick() {1390 DriverListener.setMessages(Messager.ELEMENT_RIGHT_CLICKED.getMessage(getName()),1391 Messager.ELEMENT_NOT_RIGHT_CLICKED.getMessage(getNameWithLocator()));1392 1393 WebDriver drv = getDriver();1394 Actions action = new Actions(drv);1395 action.moveToElement(element).contextClick(element).build().perform();1396 }1397 @Override1398 public void doCheck() {1399 DriverListener.setMessages(Messager.CHECKBOX_CHECKED.getMessage(getName()), null);1400 1401 boolean isSelected = element.isSelected();1402 if (element.getAttribute("checked") != null) {1403 isSelected |= element.getAttribute("checked").equalsIgnoreCase("true");1404 }1405 1406 if (!isSelected) {1407 click();1408 }1409 }1410 @Override1411 public void doUncheck() {1412 DriverListener.setMessages(Messager.CHECKBOX_UNCHECKED.getMessage(getName()), null);1413 1414 boolean isSelected = element.isSelected();1415 if (element.getAttribute("checked") != null) {1416 isSelected |= element.getAttribute("checked").equalsIgnoreCase("true");1417 }1418 1419 if (isSelected) {1420 click();1421 }1422 }1423 1424 @Override1425 public boolean doIsChecked() {1426 1427 boolean res = element.isSelected();1428 if (element.getAttribute("checked") != null) {1429 res |= element.getAttribute("checked").equalsIgnoreCase("true");1430 }1431 1432 return res;1433 }1434 1435 @Override1436 public boolean doSelect(String text) {1437 final String decryptedSelectText = cryptoTool.decryptByPattern(text, CRYPTO_PATTERN);1438 1439 String textLog = (!decryptedSelectText.equals(text) ? "********" : text);1440 1441 DriverListener.setMessages(Messager.SELECT_BY_TEXT_PERFORMED.getMessage(textLog, getName()),1442 Messager.SELECT_BY_TEXT_NOT_PERFORMED.getMessage(textLog, getNameWithLocator()));1443 1444 final Select s = new Select(getElement());1445 // [VD] do not use selectByValue as modern controls could have only visible value without value1446 s.selectByVisibleText(decryptedSelectText);1447 return true;1448 }1449 @Override1450 public boolean doSelectValues(String[] values) {1451 boolean result = true;1452 for (String value : values) {1453 if (!select(value)) {1454 result = false;1455 }1456 }1457 return result;1458 }1459 @Override1460 public boolean doSelectByMatcher(BaseMatcher<String> matcher) {1461 1462 DriverListener.setMessages(Messager.SELECT_BY_MATCHER_TEXT_PERFORMED.getMessage(matcher.toString(), getName()),1463 Messager.SELECT_BY_MATCHER_TEXT_NOT_PERFORMED.getMessage(matcher.toString(), getNameWithLocator()));1464 1465 final Select s = new Select(getElement());1466 String fullTextValue = null;1467 for (WebElement option : s.getOptions()) {1468 if (matcher.matches(option.getText())) {1469 fullTextValue = option.getText();1470 break;1471 }1472 }1473 s.selectByVisibleText(fullTextValue);1474 return true;1475 }1476 @Override1477 public boolean doSelectByPartialText(String partialSelectText) {1478 1479 DriverListener.setMessages(1480 Messager.SELECT_BY_TEXT_PERFORMED.getMessage(partialSelectText, getName()),1481 Messager.SELECT_BY_TEXT_NOT_PERFORMED.getMessage(partialSelectText, getNameWithLocator()));1482 1483 final Select s = new Select(getElement());1484 String fullTextValue = null;1485 for (WebElement option : s.getOptions()) {1486 if (option.getText().contains(partialSelectText)) {1487 fullTextValue = option.getText();1488 break;1489 }1490 }1491 s.selectByVisibleText(fullTextValue);1492 return true;1493 }1494 @Override1495 public boolean doSelectByIndex(int index) {1496 DriverListener.setMessages(1497 Messager.SELECT_BY_INDEX_PERFORMED.getMessage(String.valueOf(index), getName()),1498 Messager.SELECT_BY_INDEX_NOT_PERFORMED.getMessage(String.valueOf(index), getNameWithLocator()));1499 1500 1501 final Select s = new Select(getElement());1502 s.selectByIndex(index);1503 return true;1504 }1505 @Override1506 public String doGetSelectedValue() {1507 final Select s = new Select(getElement());1508 return s.getAllSelectedOptions().get(0).getText();1509 }1510 @Override...

Full Screen

Full Screen

Source:DriverListener.java Github

copy

Full Screen

...36 * IMPORTANT! Please avoid any driver calls with extra listeners (recursive exception generation)37 * 38 * @author Alex Khursevich (alex@qaprosoft.com)39 */40public class DriverListener implements WebDriverEventListener, IDriverPool {41 private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());42 private final static ThreadLocal<String> currentPositiveMessage = new ThreadLocal<String>();43 private final static ThreadLocal<String> currentNegativeMessage = new ThreadLocal<String>();44 @Override45 public void afterAlertAccept(WebDriver driver) {46 onAfterAction("Alert accepted", driver);47 }48 @Override49 public void afterAlertDismiss(WebDriver driver) {50 onAfterAction("Alert dismissed", driver);51 }52 @Override53 public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] value) {54 captureScreenshot(String.format("Text '%s' typed", charArrayToString(value)), driver, element, false);55 }56 @Override57 public void afterClickOn(WebElement element, WebDriver driver) {58 String comment = "Element clicked";59 captureScreenshot(comment, driver, element, false);60 }61 @Override62 public void afterFindBy(By by, WebElement element, WebDriver driver) {63 // Do nothing64 }65 @Override66 public void afterNavigateBack(WebDriver driver) {67 onAfterAction("Navigated back", driver);68 }69 @Override70 public void afterNavigateForward(WebDriver driver) {71 onAfterAction("Navigated forward", driver);72 }73 @Override74 public void afterNavigateRefresh(WebDriver driver) {75 onAfterAction("Page refreshed", driver);76 }77 @Override78 public void afterNavigateTo(String url, WebDriver driver) {79 String comment = String.format("URL '%s' opened", url);80 onAfterAction(comment, driver);81 }82 @Override83 public void afterScript(String script, WebDriver driver) {84 // Do nothing85 }86 @Override87 public void beforeAlertAccept(WebDriver driver) {88 // Do nothing89 }90 @Override91 public void beforeAlertDismiss(WebDriver driver) {92 // Do nothing93 }94 @Override95 public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] value) {96 // Do nothing97 }98 @Override99 public void beforeClickOn(WebElement element, WebDriver driver) {100 // Do nothing101 }102 @Override103 public void beforeFindBy(By by, WebElement element, WebDriver driver) {104 // Do nothing105 }106 @Override107 public void beforeNavigateBack(WebDriver driver) {108 // Do nothing109 }110 @Override111 public void beforeNavigateForward(WebDriver driver) {112 // Do nothing113 }114 @Override115 public void beforeNavigateRefresh(WebDriver driver) {116 // Do nothing117 }118 @Override119 public void beforeNavigateTo(String script, WebDriver driver) {120 // Do nothing121 }122 @Override123 public void beforeScript(String script, WebDriver driver) {124 // Do nothing125 }126 @Override127 public void onException(Throwable thr, WebDriver driver) {128 // [VD] make below code as much safety as possible otherwise potential recursive failure could occur with driver related issue.129 // most suspicious are capture screenshots, generating dumps etc130 if (thr == null131 || thr.getMessage() == null132 || thr.getMessage().contains("Method has not yet been implemented") 133 || thr.getMessage().contains("Expected to read a START_MAP but instead have: END. Last 0 characters read")134 || thr.getMessage().contains("Unable to determine type from: <. Last 1 characters read")135 || thr.getMessage().contains("script timeout")136 || thr.getMessage().contains("javascript error: Cannot read property 'outerHTML' of null")137 || thr.getMessage().contains("javascript error: Cannot read property 'scrollHeight' of null")138 || thr.getMessage().contains("Method is not implemented")139 || thr.getMessage().contains("An element could not be located on the page using the given search parameters")140 || thr.getMessage().contains("no such element: Unable to locate element")141 || thr.getMessage().contains("Failed to execute command screen image")142 // carina has a lot of extra verifications to solve all stale reference issue and finally perform an action so ignore such exception in listener!143 || thr.getMessage().contains("StaleElementReferenceException")144 || thr.getMessage().contains("stale_element_reference.html")) {145 // do nothing146 return;147 }148 // handle use-case when application crashed on iOS but tests continue to execute something because doesn't raise valid exception149 // Example:150 // 10:25:20 2018-09-14 10:29:39 DriverListener [TestNG-31] [ERROR]151 // [iPhone_6s] An unknown server-side error occurred while152 // processing the command. Original error: The application under153 // test with bundle id 'Q5AWL8WCY6' is not running,154 // possibly crashed (WARNING: The server did not provide any155 // stacktrace information)156 // TODO: investigate if we run @AfterMethod etc system events after this crash157 if (thr.getMessage().contains("is not running, possibly crashed")) {158 throw new RuntimeException(thr);159 }160 // hopefully castDriver below resolve root cause of the recursive onException calls but keep below to ensure161 if (thr.getStackTrace() != null162 && (Arrays.toString(thr.getStackTrace())163 .contains("com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener.onException")164 || Arrays.toString(thr.getStackTrace()).contains("Unable to capture screenshot due to the WebDriverException"))) {165 LOGGER.error("Do not generate screenshot for invalid driver!");166 // prevent recursive crash for onException167 return;168 }169 LOGGER.debug("DriverListener->onException starting..." + thr.getMessage());170 driver = castDriver(driver);171 try {172 // 1. if you see mess with afterTest carina actions and Timer startup failure you should follow steps #2+ to determine root cause.173 // Driver initialization 'default' FAILED! Retry 1 of 1 time - Operation already started: mobile_driverdefault174 // 2. carefully track all preliminary exception for the same thread to detect 1st problematic exception175 // 3. 99% those root exception means that we should prohibit screenshot generation for such use-case176 // 4. if 3rd one is true just update Screenshot.isCaptured() adding part of the exception to the list177 // handle cases which should't be captured178 if (Screenshot.isCaptured(thr.getMessage())) {179 captureScreenshot(thr.getMessage(), driver, null, true);180 }181 } catch (Exception e) {182 if (!e.getMessage().isEmpty()183 && (e.getMessage().contains("Method has not yet been implemented") || (e.getMessage().contains("Method is not implemented")))) {184 LOGGER.debug("Unrecognized exception detected in DriverListener->onException!", e);185 } else {186 LOGGER.error("Unrecognized exception detected in DriverListener->onException!", e);187 }188 } catch (Throwable e) {189 LOGGER.error("Take a look to the logs above for current thread and add exception into the exclusion for Screenshot.isCaptured().", e);190 }191 LOGGER.debug("DriverListener->onException finished.");192 }193 /**194 * Converts char sequence to string.195 * 196 * @param csa - char sequence array197 * @return string representation198 */199 private String charArrayToString(CharSequence[] csa) {200 String s = StringUtils.EMPTY;201 if (csa != null) {202 StringBuilder sb = new StringBuilder();203 for (CharSequence cs : csa) {204 sb.append(String.valueOf(cs));205 }206 s = sb.toString();207 }208 return s;209 }210 @Override211 public void afterSwitchToWindow(String arg0, WebDriver driver) {212 // do nothing213 }214 @Override215 public void beforeSwitchToWindow(String arg0, WebDriver driver) {216 // Do nothing217 }218 @Override219 public <X> void afterGetScreenshotAs(OutputType<X> arg0, X arg1) {220 // do nothing221 }222 @Override223 public <X> void beforeGetScreenshotAs(OutputType<X> arg0) {224 // Do nothing225 }226 @Override227 public void afterGetText(WebElement element, WebDriver driver, String arg2) {228 // do nothing229 }230 @Override231 public void beforeGetText(WebElement element, WebDriver driver) {232 // do nothing233 }234 private void captureScreenshot(String comment, WebDriver driver, WebElement element, boolean errorMessage) {235 driver = castDriver(driver);236 if (getMessage(errorMessage) != null) {237 comment = getMessage(errorMessage);238 }239 try {240 if (errorMessage) {241 LOGGER.error(comment);242 String screenName = Screenshot.captureByRule(driver, comment, true); // in case of failure try full size if allowed243 // do not generate UI dump if no screenshot244 if (!screenName.isEmpty()) {245 generateDump(driver, screenName);246 }247 } else {248 LOGGER.info(comment);249 Screenshot.captureByRule(driver, comment);250 }251 } catch (Exception e) {252 LOGGER.debug("Unrecognized failure detected in DriverListener->captureScreenshot!", e);253 } finally {254 resetMessages();255 }256 }257 private void generateDump(WebDriver driver, String screenName) {258 // XML layout extraction259 File uiDumpFile = getDevice(driver).generateUiDump(screenName);260 if (uiDumpFile != null) {261 // use the same naming but with zip extension. Put into the test artifacts folder262 String dumpArtifact = ReportContext.getArtifactsFolder().getAbsolutePath() + "/" + screenName.replace(".png", ".zip");263 LOGGER.debug("UI Dump artifact: " + dumpArtifact);264 // build path to screenshot using name265 File screenFile = new File(ReportContext.getTestDir().getAbsolutePath() + "/" + screenName);266 // archive page source dump and screenshot both together...

Full Screen

Full Screen

Source:DriverFactory.java Github

copy

Full Screen

...30import com.qaprosoft.carina.core.foundation.utils.R;31import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.DesktopFactory;32import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.MobileFactory;33import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.WindowsFactory;34import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;35import com.zebrunner.agent.core.webdriver.RemoteWebDriverFactory;36/**37 * DriverFactory produces driver instance with desired capabilities according to38 * configuration.39 *40 * @author Alexey Khursevich (hursevich@gmail.com)41 */42public class DriverFactory {43 private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());44 public static WebDriver create(String testName, DesiredCapabilities capabilities, String seleniumHost) {45 LOGGER.debug("DriverFactory start...");46 AbstractFactory factory;47 URL seleniumUrl = RemoteWebDriverFactory.getSeleniumHubUrl();48 if (seleniumUrl != null) {49 // override existing selenium_url in config50 R.CONFIG.put(Parameter.SELENIUM_URL.getKey(), seleniumUrl.toString());51 }52 String driverType = Configuration.getDriverType(capabilities);53 switch (driverType) {54 case SpecialKeywords.DESKTOP:55 factory = new DesktopFactory();56 break;57 case SpecialKeywords.MOBILE:58 factory = new MobileFactory();59 break;60 case SpecialKeywords.WINDOWS:61 factory = new WindowsFactory();62 break;63 default:64 throw new RuntimeException("Unsupported driver_type: " + driverType);65 }66 LOGGER.info("Starting driver session...");67 WebDriver driver = factory.create(testName, capabilities, seleniumHost);68 driver = factory.registerListeners(driver, getEventListeners());69 LOGGER.info("Driver session started.");70 LOGGER.debug("DriverFactory finish...");71 return driver;72 }73 74 /**75 * Reads 'driver_event_listeners' configuration property and initializes76 * appropriate array of driver event listeners.77 * 78 * @return array of driver listeners79 */80 private static WebDriverEventListener[] getEventListeners() {81 List<WebDriverEventListener> listeners = new ArrayList<>();82 try {83 //explicitly add default carina com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener84 DriverListener driverListener = new DriverListener();85 listeners.add(driverListener);86 String listenerClasses = Configuration.get(Parameter.DRIVER_EVENT_LISTENERS);87 if (!StringUtils.isEmpty(listenerClasses)) {88 for (String listenerClass : listenerClasses.split(",")) {89 Class<?> clazz = Class.forName(listenerClass);90 if (WebDriverEventListener.class.isAssignableFrom(clazz)) {91 WebDriverEventListener listener = (WebDriverEventListener) clazz.newInstance();92 listeners.add(listener);93 LOGGER.debug("Webdriver event listener registered: " + clazz.getName());94 }95 }96 }97 98 } catch (Exception e) {...

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;2import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;3import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;4import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;5import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;6import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;7import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;8import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;9import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;10import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;11import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;12import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;13import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;14import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;15import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.webdriver.listener;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.support.events.EventFiringWebDriver;4public class DriverListener extends EventFiringWebDriver {5 public DriverListener(WebDriver driver) {6 super(driver);7 }8}9package com.qaprosoft.carina.core.foundation.webdriver.listener;10import org.openqa.selenium.WebDriver;11import org.openqa.selenium.support.events.EventFiringWebDriver;12public class DriverListener extends EventFiringWebDriver {13 public DriverListener(WebDriver driver) {14 super(driver);15 }16}17package com.qaprosoft.carina.core.foundation.webdriver.listener;18import org.openqa.selenium.WebDriver;19import org.openqa.selenium.support.events.EventFiringWebDriver;20public class DriverListener extends EventFiringWebDriver {21 public DriverListener(WebDriver driver) {22 super(driver);23 }24}25package com.qaprosoft.carina.core.foundation.webdriver.listener;26import org.openqa.selenium.WebDriver;27import org.openqa.selenium.support.events.EventFiringWebDriver;28public class DriverListener extends EventFiringWebDriver {29 public DriverListener(WebDriver driver) {30 super(driver);31 }32}33package com.qaprosoft.carina.core.foundation.webdriver.listener;34import org.openqa.selenium.WebDriver;35import org.openqa.selenium.support.events.EventFiringWebDriver;36public class DriverListener extends EventFiringWebDriver {37 public DriverListener(WebDriver driver) {38 super(driver);39 }40}41package com.qaprosoft.carina.core.foundation.webdriver.listener;42import org.openqa.selenium.WebDriver;43import org.openqa.selenium.support.events.EventFiringWebDriver;44public class DriverListener extends EventFiringWebDriver {45 public DriverListener(WebDriver driver) {46 super(driver);47 }48}49package com.qaprosoft.carina.core.foundation.webdriver.listener;50import org.openqa.selenium.WebDriver;

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.webdriver.listener;2import com.qaprosoft.carina.core.foundation.utils.Configuration;3import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter;4import com.qaprosoft.carina.core.foundation.utils.R;5import com.qaprosoft.carina.core.foundation.utils.ownership.MethodOwner;6import org.openqa.selenium.By;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.support.events.AbstractWebDriverEventListener;10import org.slf4j.Logger;11import org.slf4j.LoggerFactory;12import java.io.File;13import java.io.IOException;14import java.util.ArrayList;15import java.util.List;16public class DriverListener extends AbstractWebDriverEventListener {17 private static final Logger LOGGER = LoggerFactory.getLogger(DriverListener.class);18 private static final String SCREENSHOTS_FOLDER = "screenshots";19 private static final String SCREENSHOTS_EXTENSION = ".png";20 private static final String SCREENSHOTS_PATH = SCREENSHOTS_FOLDER + File.separator;21 private static final String SCREENSHOTS_NAME = "screenshot-";22 private static final String SCREENSHOTS_FULL_PATH = R.CONFIG.get(Parameter.OUTPUT_FOLDER) + File.separator + SCREENSHOTS_PATH;23 private static final String HTML_FOLDER = "html";24 private static final String HTML_EXTENSION = ".html";25 private static final String HTML_PATH = HTML_FOLDER + File.separator;26 private static final String HTML_NAME = "html-";27 private static final String HTML_FULL_PATH = R.CONFIG.get(Parameter.OUTPUT_FOLDER) + File.separator + HTML_PATH;28 private static final String TEXT_FOLDER = "text";29 private static final String TEXT_EXTENSION = ".txt";30 private static final String TEXT_PATH = TEXT_FOLDER + File.separator;31 private static final String TEXT_NAME = "text-";32 private static final String TEXT_FULL_PATH = R.CONFIG.get(Parameter.OUTPUT_FOLDER) + File.separator + TEXT_PATH;

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1public class DriverListener implements ITestListener {2 private static final Logger LOGGER = Logger.getLogger(DriverListener.class);3 public void onTestStart(ITestResult result) {4 LOGGER.info("onTestStart: " + result.getName());5 }6 public void onTestSuccess(ITestResult result) {7 LOGGER.info("onTestSuccess: " + result.getName());8 }9 public void onTestFailure(ITestResult result) {10 LOGGER.info("onTestFailure: " + result.getName());11 }12 public void onTestSkipped(ITestResult result) {13 LOGGER.info("onTestSkipped: " + result.getName());14 }15 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {16 LOGGER.info("onTestFailedButWithinSuccessPercentage: " + result.getName());17 }18 public void onStart(ITestContext context) {19 LOGGER.info("onStart: " + context.getName());20 }21 public void onFinish(ITestContext context) {22 LOGGER.info("onFinish: " + context.getName());23 }24}25public class Listener extends DriverListener {26 private static final Logger LOGGER = Logger.getLogger(Listener.class);27 public void onTestStart(ITestResult result) {28 LOGGER.info("onTestStart: " + result.getName());29 }30 public void onTestSuccess(ITestResult result) {31 LOGGER.info("onTestSuccess: " + result.getName());32 }33 public void onTestFailure(ITestResult result) {34 LOGGER.info("onTestFailure: " + result.getName());35 }36 public void onTestSkipped(ITestResult result) {37 LOGGER.info("onTestSkipped: " + result.getName());38 }39 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {40 LOGGER.info("onTestFailedButWithinSuccessPercentage: " + result.getName());41 }42 public void onStart(ITestContext context) {43 LOGGER.info("onStart: " + context.getName());44 }45 public void onFinish(ITestContext context) {

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;2import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener.EventFiringWebDriverFactory;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.support.events.EventFiringWebDriver;5public class 1 {6 public static void main(String[] args) {7 EventFiringWebDriver driver = EventFiringWebDriverFactory.getEventFiringWebDriver(new ChromeDriver());8 DriverListener driverListener = new DriverListener();9 driver.register(driverListener);10 }11}12import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;13import org.openqa.selenium.WebDriver;14import org.openqa.selenium.support.events.EventFiringWebDriver;15public class 2 {16 public static void main(String[] args) {17 WebDriver driver = new ChromeDriver();18 DriverListener driverListener = new DriverListener();19 EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver);20 eventFiringWebDriver.register(driverListener);21 }22}23import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;24import org.openqa.selenium.WebDriver;25import org.openqa.selenium.support.events.EventFiringWebDriver;26public class 3 {27 public static void main(String[] args) {28 WebDriver driver = new ChromeDriver();29 DriverListener driverListener = new DriverListener();30 EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver);31 eventFiringWebDriver.register(driverListener);32 }33}34import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;35import org.openqa.selenium.WebDriver;36import org.openqa.selenium.support.events.EventFiringWebDriver;37public class 4 {38 public static void main(String[] args) {39 WebDriver driver = new ChromeDriver();40 DriverListener driverListener = new DriverListener();41 EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver);42 eventFiringWebDriver.register(driverListener);

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.chrome.ChromeDriver;3import org.openqa.selenium.firefox.FirefoxDriver;4import org.openqa.selenium.support.events.EventFiringWebDriver;5import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;6public class DriverListenerTest {7 public static void main(String[] args) {8 WebDriver driver = new FirefoxDriver();9 EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver);10 eventDriver.register(new DriverListener());11 eventDriver.quit();12 }13}14 eventDriver.register(new DriverListener());

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1DriverListener driverListener = new DriverListener();2driver.addListener(driverListener);3DriverListener driverListener = new DriverListener();4driver.addListener(driverListener);5DriverListener driverListener = new DriverListener();6driver.addListener(driverListener);7DriverListener driverListener = new DriverListener();8driver.addListener(driverListener);9DriverListener driverListener = new DriverListener();10driver.addListener(driverListener);11DriverListener driverListener = new DriverListener();12driver.addListener(driverListener);13DriverListener driverListener = new DriverListener();14driver.addListener(driverListener);15DriverListener driverListener = new DriverListener();16driver.addListener(driverListener);17DriverListener driverListener = new DriverListener();18driver.addListener(driverListener);19DriverListener driverListener = new DriverListener();20driver.addListener(driverListener);21DriverListener driverListener = new DriverListener();22driver.addListener(driverListener);23DriverListener driverListener = new DriverListener();

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.webdriver.listener;2import org.openqa.selenium.WebDriver;3import org.testng.ITestContext;4import org.testng.ITestResult;5import org.testng.annotations.AfterMethod;6import org.testng.annotations.BeforeMethod;7import org.testng.annotations.Listeners;8import org.testng.annotations.Test;9import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;10import com.qaprosoft.carina.core.foundation.webdriver.DriverPool;11@Listeners(DriverListener.class)12public class DriverListenerTest extends DriverHelper{13 public void beforeMethod(ITestResult result) {14 System.out.println("beforeMethod: " + result.getMethod().getMethodName());15 }16 public void afterMethod(ITestResult result) {17 System.out.println("afterMethod: " + result.getMethod().getMethodName());18 }19 public void test1() {20 WebDriver driver = getDriver();21 System.out.println("test1: " + driver);22 }23 public void test2() {24 WebDriver driver = getDriver();25 System.out.println("test2: " + driver);26 }27 public void test3() {28 WebDriver driver = getDriver();29 System.out.println("test3: " + driver);30 }31 public void test4() {32 WebDriver driver = getDriver();33 System.out.println("test4: " + driver);34 }35 public void test5() {36 WebDriver driver = getDriver();37 System.out.println("test5: " + driver);38 }39 public void test6() {40 WebDriver driver = getDriver();41 System.out.println("test6: " + driver);42 }43 public void test7() {44 WebDriver driver = getDriver();45 System.out.println("test7: " + driver);46 }47 public void test8() {48 WebDriver driver = getDriver();49 System.out.println("test8: " + driver);50 }51 public void test9() {52 WebDriver driver = getDriver();53 System.out.println("test9: " + driver);54 }55 public void test10() {56 WebDriver driver = getDriver();57 System.out.println("test10: " + driver);58 }

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1public class 1 {2 private static final Logger LOGGER = Logger.getLogger(1.class);3 public static void main(String[] args) {4 DriverListener driverListener = new DriverListener();5 WebDriver driver = driverListener.getDriver();6 driver.quit();7 }8}9public class 2 {10 private static final Logger LOGGER = Logger.getLogger(2.class);11 public static void main(String[] args) {12 DriverListener driverListener = new DriverListener();13 WebDriver driver = driverListener.getDriver();14 driver.quit();15 }16}17public class 3 {18 private static final Logger LOGGER = Logger.getLogger(3.class);19 public static void main(String[] args) {20 DriverListener driverListener = new DriverListener();21 WebDriver driver = driverListener.getDriver();22 driver.quit();23 }24}25public class 4 {26 private static final Logger LOGGER = Logger.getLogger(4.class);27 public static void main(String[] args) {28 DriverListener driverListener = new DriverListener();29 WebDriver driver = driverListener.getDriver();30 driver.quit();31 }32}33public class 5 {34 private static final Logger LOGGER = Logger.getLogger(5.class);35 public static void main(String[] args) {36 DriverListener driverListener = new DriverListener();37 WebDriver driver = driverListener.getDriver();38 driver.quit();39 }40}

Full Screen

Full Screen

DriverListener

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.webdriver.listener;2import org.testng.annotations.Test;3public class TestDriverListener {4 public void testDriverListener() {5 DriverListener driverListener = new DriverListener();6 driverListener.beforeInvocation(null, null);7 driverListener.afterInvocation(null, null);8 }9}10package com.qaprosoft.carina.core.foundation.webdriver.listener2;11import org.testng.annotations.Test;12import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;13public class TestDriverListener {14 public void testDriverListener() {15 DriverListener driverListener = new DriverListener();16 driverListener.beforeInvocation(null, null);17 driverListener.afterInvocation(null, null);18 }19}20package com.qaprosoft.carina.core.foundation.webdriver.listener3;21import org.testng.annotations.Test;22import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;23public class TestDriverListener {24 public void testDriverListener() {25 DriverListener driverListener = new DriverListener();26 driverListener.beforeInvocation(null, null);27 driverListener.afterInvocation(null, null);28 }29}30package com.qaprosoft.carina.core.foundation.webdriver.listener4;31import org.testng.annotations.Test;32import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;33public class TestDriverListener {34 public void testDriverListener() {35 DriverListener driverListener = new DriverListener();

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful