/** * 1. map elements of interest to their name * 2. reload elements from the page every time `map` is called * * E.g., Say ELEMENT_LOCATORS=id * and <input id="username" type="text"></input> * then nameElementMap will contain "username" => WebElement */ @Override protected void map(AbstractPage p) { getBys(); List<WebElement> elements = new ArrayList<WebElement>(); for (By by : bys) { elements.addAll(driver.findElements(by)); } PageFactory.initElements(driver, this); String[] tokens = locators.split(","); for(WebElement w: elements) { for (String s : tokens) { try{ String attr = w.getAttribute(s);//throws StaleElementReferenceException if (attr != null) { nameElementMap.put(attr, w); } }catch(StaleElementReferenceException se){ //ignoring elements which have become stale because //a stale object shouldn't have to be referenced //by an automation script } } } }
/** * Clicks button at the bottom of edit Window and expect for dialog to disappear. * * @param buttonText button label * @return Returns this dialog instance. */ public AemDialog clickDialogFooterButton(final String buttonText) { final WebElement footerButton = getFooterButtonWebElement(buttonText); bobcatWait.withTimeout(Timeouts.BIG).until((ExpectedCondition<Object>) input -> { try { footerButton.click(); footerButton.isDisplayed(); return Boolean.FALSE; } catch (NoSuchElementException | StaleElementReferenceException | ElementNotVisibleException e) { LOG.debug("Dialog footer button is not available: {}", e); return Boolean.TRUE; } }, 2); bobcatWait.withTimeout(Timeouts.MEDIUM).until(CommonExpectedConditions.noAemAjax()); return this; }
@Override public void selectRandom() { int count = 0; while (count < 5) { try { final org.openqa.selenium.support.ui.Select wrapped = wrappedSelect(); int optionsSize = getOptions().size(); if (optionsSize > 1) { int optionIndex = nextInt(optionsSize); while (getOptions().get(optionIndex).isSelected()) { optionIndex = nextInt(optionsSize); } wrapped.selectByIndex(optionIndex); } break; } catch (StaleElementReferenceException e) { TestUtils.waitForSomeTime(1000, EXPLANATION_MESSAGE_FOR_WAIT); } } }
@Override public void mark(WebElement ele, File file) throws IOException { BufferedImage bufImg = ImageIO.read(file); try { WebElement webEle = (WebElement) ele; Point loc = webEle.getLocation(); Dimension size = webEle.getSize(); Graphics2D g = bufImg.createGraphics(); g.setColor(Color.red); g.drawRect(loc.getX(), loc.getY(), size.getWidth(), size.getHeight()); } catch(StaleElementReferenceException se) { } }
/** * This is the method that intercepts component container methods in "enhanced" model objects. * * @param obj "enhanced" object upon which the method was invoked * @param method {@link Method} object for the invoked method * @param args method invocation arguments * @return {@code anything} (the result of invoking the intercepted method) * @throws Exception {@code anything} (exception thrown by the intercepted method) */ @RuntimeType @BindingPriority(Integer.MAX_VALUE) public Object intercept(@This Object obj, @Origin Method method, @AllArguments Object[] args) throws Exception { try { return method.invoke(getWrappedElement(), args); } catch (InvocationTargetException ite) { Throwable t = ite.getCause(); if (t instanceof StaleElementReferenceException) { try { StaleElementReferenceException sere = (StaleElementReferenceException) t; return method.invoke(refreshReference(sere).getWrappedElement(), args); } catch (NullPointerException npe) { throw deferredException(); } } throw UncheckedThrow.throwUnchecked(t); } }
/** * Returns a 'wait' proxy that refreshes the wrapped reference of the specified robust element. * * @param wrapper robust element wrapper * @return wrapped element reference (refreshed) */ private static Coordinator<RobustElementWrapper> referenceIsRefreshed(final RobustElementWrapper wrapper) { return new Coordinator<RobustElementWrapper>() { @Override public RobustElementWrapper apply(SearchContext context) { try { return acquireReference(wrapper); } catch (StaleElementReferenceException e) { ((WrapsContext) context).refreshContext(((WrapsContext) context).acquiredAt()); return acquireReference(wrapper); } } @Override public String toString() { return "element reference to be refreshed"; } }; }
/** * Returns a 'wait' proxy that switches focus to the specified context * * @param context search context on which to focus * @return target search context */ static Coordinator<SearchContext> contextIsSwitched(final ComponentContainer context) { return new Coordinator<SearchContext>() { @Override public SearchContext apply(SearchContext ignore) { if (context.parent != null) { context.parent.switchTo(); } try { return context.switchToContext(); } catch (StaleElementReferenceException e) { return context.refreshContext(context.acquiredAt()); } } @Override public String toString() { return "context to be switched"; } }; }
/** * Returns a 'wait' proxy that determines if the first element matched by the specified locator is visible * * @param locator web element locator * @return web element reference; 'null' if the indicated element is absent or hidden */ public static Coordinator<WebElement> visibilityOfElementLocated(final By locator) { return new Coordinator<WebElement>() { @Override public WebElement apply(SearchContext context) { try { return elementIfVisible(context.findElement(locator)); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of element located by " + locator; } }; }
/** * Returns a 'wait' proxy that determines if any element matched by the specified locator is visible * * @param locator web element locator * @return web element reference; 'null' if no matching elements are visible */ public static Coordinator<WebElement> visibilityOfAnyElementLocated(final By locator) { return new Coordinator<WebElement>() { @Override public WebElement apply(SearchContext context) { try { List<WebElement> visible = context.findElements(locator); return (WebDriverUtils.filterHidden(visible)) ? null : visible.get(0); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of element located by " + locator; } }; }
/** * Returns a 'wait' proxy that determines if an element is either hidden or non-existent. * * @param locator web element locator * @return 'true' if the element is hidden or non-existent; otherwise 'false' */ public static Coordinator<Boolean> invisibilityOfElementLocated(final By locator) { return new Coordinator<Boolean>() { @Override public Boolean apply(SearchContext context) { try { return !(context.findElement(locator).isDisplayed()); } catch (NoSuchElementException | StaleElementReferenceException e) { // NoSuchElementException: The element is not present in DOM. // StaleElementReferenceException: Implies that element no longer exists in the DOM. return true; } } @Override public String toString() { return "element to no longer be visible: " + locator; } }; }
public static void waitFor(WebDriver driver, long timeout, By... elements) throws TimeoutException, InterruptedException { try { WaitUtil.waitFor(() -> elementsPresent(driver, elements), null, 1000L, timeout); } catch (TimeoutException ex) { try { for (By element : elements) { WebElement webElement = driver.findElement(element); if (!webElement.isDisplayed()) { throw new TimeoutException("Timeout exception during waiting for web element: " + webElement.getText()); } } } catch (NoSuchElementException | StaleElementReferenceException x) { throw new TimeoutException("Timeout exception during waiting for web element: " + x.getMessage()); } } }
private void clickButton(final String buttonLabel) { final WebElement button = bobcatWait.withTimeout(Timeouts.BIG).until(input -> window.findElement( By.xpath(String.format(BUTTON_XPATH_FORMATTED, buttonLabel)))); bobcatWait.withTimeout(Timeouts.MEDIUM).until(ExpectedConditions.elementToBeClickable(button)); bobcatWait.withTimeout(Timeouts.BIG).until(input -> { boolean confirmationWindowClosed; try { button.click(); confirmationWindowClosed = !window.isDisplayed(); } catch (NoSuchElementException | StaleElementReferenceException e) { LOG.debug("Confirmation window is not available", e); confirmationWindowClosed = true; } return confirmationWindowClosed; }); }
private ExpectedCondition<Boolean> dynamicRedrawFinishes(final WebElement element) { return new ExpectedCondition<Boolean>() { int retries = 3; @Override public Boolean apply(WebDriver ignored) { try { element.isEnabled(); } catch (StaleElementReferenceException expected) { if (retries > 0) { retries--; dynamicRedrawFinishes(element); } else { throw expected; } } return true; } }; }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void onFailure(QAFExtendedWebElement element, CommandTracker commandTracker) { commandTracker.setStage(Stage.executingOnFailure); commandTracker.setEndTime(System.currentTimeMillis()); if (commandTracker.getException() instanceof StaleElementReferenceException) { logger.warn(commandTracker.getException().getMessage()); element.setId("-1"); Map parameters = commandTracker.getParameters(); parameters.put("id", element.getId()); commandTracker.setException(null); commandTracker.setStage(Stage.executingMethod); element.execute(commandTracker.command, parameters); commandTracker.setEndTime(System.currentTimeMillis()); } for (QAFWebElementCommandListener listener : listners) { // whether handled previous listener if (!commandTracker.hasException()) { break; } logger.debug("Executing listener " + listener.getClass().getName()); listener.onFailure(element, commandTracker); } }
public Set<Link> getLinks() { Set<Link> links = new HashSet<Link>(); String currentLoc = this.getUrl(); List<WebElement> anchors = this.driver .findElements(By.tagName("a")); for(WebElement a : anchors) { try { Link l = new Link(a.getText(), a.getAttribute("href")); if(l.valid(currentLoc)) { links.add(l); } } catch (final StaleElementReferenceException sre) { //stale link, ignore it //More here: //http://www.seleniumhq.org/exceptions/stale_element_reference.jsp } } return links; }
public ManageFilesystemPage setNewFolderName(String folderName) { LOG.log(Level.INFO, "Setting folder name to: {0}", folderName); int retries = 5; do { try { By input = By.xpath("//div[@class='ui-overlaypanel-content']//input"); waitForObject(input); driver.findElement(input).sendKeys(folderName); break; } catch (StaleElementReferenceException ex) { LOG.info("Stale element exception - looping again;"); retries--; try { Thread.sleep(200);//the timeout is necessary to ensure ajax text field is properly loaded } catch (InterruptedException ex2) { LOG.log(Level.INFO, null, ex2); } } } while (retries > 0); return this; }
public ManageFilesystemPage clickCreateNewFolder() { LOG.info("Clicking Create folder button"); int retries = 5; do { try { By button = By.xpath("//div[@class='ui-overlaypanel-content']//button"); waitForObject(button); driver.findElement(button).click(); break; } catch (StaleElementReferenceException ex) { LOG.info("Stale element exception - looping again"); retries--; } } while (retries > 0); return this; }
/** * Determines if the page object is toggled visible by checking whether its content container is visible or not. * <p> * Note: Test case for a page object with a hover and click control which has a sticky visibility state after it is * toggled and which is visible when its control is hovered is not yet covered. See this * <a href="http://technicolordreamcode.com/2015/10/03/even-more-reasons-why-you-dont-have-good-automation-w-update-on-generic-uxd-legos-source-code-packages/">post</a> on my blog for more information. * * @param toggleControlName the name of the control which toggles the visibility of the page object * @return {@code true} if the page object is in currently toggled visible; {@code false} * otherwise */ protected boolean isToggledVisible(String toggleControlName) { try { Control control = getControl(toggleControlName); //Design some way to handle combination of hover and click control with component that has a sticky //expanded state where control is not hoverable at all by any means. // if(control.isHoverAndClickControl()) { // ((HoverAndClickControl)control).hover(); // // try { // new WaitForElementVisible().accept(getContentContainer(), getPollingTimeout(), // getPollingInterval()); // } catch(TimeoutException e) { // return false; // } // } return getContentContainer().isDisplayed(); } catch(NoSuchElementException | StaleElementReferenceException e) { return false; } }
/** * Clicks the specified option in the menu. * <p> * If the menu is a drop-down menu and is currently collapsed, it will be expanded before this method attempts to * click the specified option. If clicking the option does not lead to a page load, the menu will be collapsed * after the option is clicked, if it is a drop-down menu. * * @param option the option in the menu to click * @throws IllegalArgumentException if the specified option is not present in the menu */ @Override public void clickOption(OptionT option) { if(getOptions().contains(option)) { if(isDropDownMenu()) { ((Expandable)this).expand(); } option.click(); if(isDropDownMenu()) { try { ((Expandable) this).collapse(); } catch(NoSuchElementException | StaleElementReferenceException e) { //Do nothing. Menu could not be collapsed, possibly because clicking the option lead to another //page } } } else { throw new IllegalArgumentException("There is no option on the menu corresponding to " + option.toString()); } }
public void waitContextMenuJavaDocText(String expectedText) { waitJavaDocPopupSrcAttributeIsNotEmpty(); loadPageDriverWait.until( (ExpectedCondition<Boolean>) driver -> { String javaDocPopupHtmlText = ""; try { javaDocPopupHtmlText = getJavaDocPopupText(); } catch (StaleElementReferenceException e) { LOG.warn("Can not get java doc HTML text from autocomplete context menu in editor"); } return javaDocPopupHtmlText.length() > 0 && verifyJavaDoc(javaDocPopupHtmlText, expectedText); }); }
/** * select item in project explorer with path, with user timeout for waiting of the item For * Example in project with name:'Test' presents folder 'src' and there is present locates file * 'pom.xpl' path will be next:'Test/src/pom.xml') * * @param path full path to project item * @param timeoutForWaitingItem user timeout for waiting expected item in the Project Explorer * tree */ public void selectItem(String path, int timeoutForWaitingItem) { waitItem(path); try { getProjectExplorerItem(path, timeoutForWaitingItem).click(); } // sometimes an element in the project explorer may not be attached to the DOM. We should // refresh all items. catch (StaleElementReferenceException ex) { LOG.debug(ex.getLocalizedMessage(), ex); waitProjectExplorer(); clickOnRefreshTreeButton(); waitItem(path); getProjectExplorerItem(path, EXPECTED_MESS_IN_CONSOLE_SEC).click(); } }
/** * open a item using full path of root folder the project * * @param path */ public void openItemByPath(String path) { Actions action = actionsFactory.createAction(seleniumWebDriver); selectItem(path); waitItemIsSelected(path); try { action.moveToElement(getProjectExplorerItem(path)).perform(); action.doubleClick().perform(); } // sometimes an element in the project explorer may not be attached to the DOM. We should // refresh all items. catch (StaleElementReferenceException ex) { LOG.debug(ex.getLocalizedMessage(), ex); clickOnRefreshTreeButton(); selectItem(path); waitItemIsSelected(path); action.moveToElement(getProjectExplorerItem(path)).perform(); action.doubleClick().perform(); } loader.waitOnClosed(); }
/** * Finds a file by name using Navigate to file feature. Expand the tree using Reveal resource * feature * * @param file file for serch with Navigate to file feature. * @param pathToFile */ public void expandToFileWithRevealResource(String file, String pathToFile) { loader.waitOnClosed(); navigateToFile.waitFormToOpen(); loader.waitOnClosed(); navigateToFile.typeSymbolInFileNameField(file); try { navigateToFile.waitFileNamePopUp(); } catch (StaleElementReferenceException ex) { sleepQuietly(1); } navigateToFile.isFilenameSuggested(file); navigateToFile.selectFileByName(file); navigateToFile.waitFormToClose(); revealResourceByOptionsButton(); waitItem(pathToFile); }
public void deleteSshKeyByHost(String host) { WebElement element = seleniumWebDriver.findElement( By.xpath("//div[text()='" + host + "']" + Locators.SSH_DELETE_BUTTON_FOR_HOST)); try { new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOf(element)) .click(); } catch (StaleElementReferenceException e) { WaitUtils.sleepQuietly(2); new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOf(element)) .click(); } askDialog.clickOkBtn(); askDialog.waitFormToClose(); }
public static ExpectedCondition<WebElement> visibilityOfElementLocated( final WebElement webElement,final String ControlId) { return new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver driver) { try { return elementIfVisible(webElement); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of element located by " +ControlId ; } }; }
/** * An expectation for checking if the given text is present in the specified * element. * * @author Michal Nowierski */ public static ExpectedCondition<Boolean> valueToBePresentInElementsAttribute(final By locator, final String attribute, final String value) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementsAttributeValue = findElement(locator, from).getAttribute(attribute); return elementsAttributeValue.contains(value); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return String.format("value ('%s') to be present in element found by %s", value, locator); } }; }
/** * An expectation for checking if the given text is present in the specified * element. * * @author Michal Nowierski */ public static ExpectedCondition<Boolean> valueToBePresentInElementsAttribute( final WebElement element, final String attribute, final String value) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementsAttributeValue = element.getAttribute(attribute); return elementsAttributeValue.contains(value); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return String.format("value ('%s') to be present in element found by %s", value, element.getTagName()); } }; }
/** * An expectation for checking if the given text is present in the specified * element. * * @author Michal Nowierski */ public static ExpectedCondition<Boolean> valueToNotBePresentInElementsAttribute( final By locator, final String attribute, final String value) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementsAttributeValue = findElement(locator, from).getAttribute(attribute); return !elementsAttributeValue.contains(value); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return String.format("value ('%s') to be present in element found by %s", value, locator); } }; }
/** * An expectation for checking if the given text is present in the specified * element. */ public static ExpectedCondition<Boolean> textToBePresentInElement( final WebElement GivenElement, final String text) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementText = GivenElement.getText(); return elementText.contains(text); } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return String.format("text ('%s') to be present in element %s", text, GivenElement.getTagName()); } }; }
public static ExpectedCondition<Boolean> invisibilityOfElementLocated( final By locator) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { return (findInvisibleElement(locator, driver)); } catch (StaleElementReferenceException e) { // Returns true because stale element reference implies that element // is no longer visible. return true; } } @Override public String toString() { return "element to no longer be visible: " + locator; } }; }
/** * Frameにスイッチするテスト */ @Test public void executeInFrame_inFrameElement() throws Exception { PtlWebElement iframe = (PtlWebElement) driver.findElementByClassName("content"); driver.switchTo().frame(iframe); PtlWebElement left = (PtlWebElement) driver.findElementByClassName("content-left"); driver.switchTo().defaultContent(); try { left.getTagName(); fail(); } catch (StaleElementReferenceException e) { // } left.setFrameParent(iframe); assertThat(left.getTagName(), is("div")); }
/** * An expectation for checking that an element is present on the sub DOM of a page and visible. * Visibility means that the element is not only displayed but also has a height and width that * is greater than 0. * * @param parent the WebElement of a sub DOM * @param locator used to find the element * @return the WebElement once it is located and visible */ public static ExpectedCondition<WebElement> visibilityOfElementLocated_(final WebElement parent, final By locator) { return new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver driver) { try { return elementIfVisible(findElement(locator, parent)); } catch (StaleElementReferenceException e) { return null; } } public String toString() { return "visibility of element located by " + locator; } }; }
/** * An expectation for checking an element is visible and enabled such that you * can click it. */ public static ExpectedCondition<WebElement> elementToBeClickable_(final WebElement parent, final By locator) { return new ExpectedCondition<WebElement>() { public ExpectedCondition<WebElement> visibilityOfElementLocated = visibilityOfElementLocated_(parent, locator); public WebElement apply(WebDriver driver) { WebElement element = visibilityOfElementLocated.apply(driver); try { if (element != null && element.isEnabled()) { return element; } else { return null; } } catch (StaleElementReferenceException e) { return null; } } public String toString() { return "element to be clickable: " + locator; } }; }
public static ExpectedCondition<Boolean> elementSelectionStateToBe_(final WebElement parent, final By locator, final boolean selected) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { WebElement element = findElement(locator, parent); return element.isSelected() == selected; } catch (StaleElementReferenceException e) { return null; } } public String toString() { return String.format("element found by %s to %sbe selected", locator, (selected ? "" : "not ")); } }; }
/** * An expectation for checking if the given text is present in the specified * element. */ public static ExpectedCondition<Boolean> textToBePresentInElement_(final WebElement parent, final By locator, final String text) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { String elementText = findElement(locator, parent).getText(); return elementText.contains(text); } catch (StaleElementReferenceException e) { return null; } } public String toString() { return String.format("text ('%s') to be present in element found by %s", text, locator); } }; }
/** * An expectation for checking if the given attribute value is present in the specified * elements's attribute name. */ public static ExpectedCondition<Boolean> attributeValueToBePresentInElement( final By locator, final String attributeName, final String attributeValue) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { String elementText = findElement(locator, driver).getAttribute(attributeName); if (elementText != null) { return elementText.contains(attributeValue); } else { return false; } } catch (StaleElementReferenceException e) { return null; } } public String toString() { return String.format( "Attribute value ('%s') of the attribute name ('%s') of element located by %s", attributeValue, attributeName, locator); } }; }
/** * Wait until an element is no longer attached to the DOM. The version in {@link ExpectedConditions} is unstable if the element's toString calls any method on the element * * @param element The element to wait for. * @return false is the element is still attached to the DOM, true * otherwise. */ public static ExpectedCondition<Boolean> stalenessOf(final WebElement element) { final String elementDescription;//need to get the element description first to avoid causing a stale element exception in the description - when it becomes stale too fast try{ elementDescription= asString(element); }catch(StaleElementReferenceException e){ return TRUE_CONDITION; } return new ExpectedCondition<Boolean>() { @Override public String toString() { return "Element to become 'stale':" + elementDescription; } @Override public Boolean apply(WebDriver input) { return ExpectedConditions.stalenessOf(element).apply(input); } }; }
public static ExpectedCondition<Boolean> invisibilityOf(final MFinder<WebElement, SearchContext> finder){ return new ExpectedCondition<Boolean>(){ @Override public Boolean apply(WebDriver driver) { Collection<WebElement> foundElements = checkerFor((SearchContext) driver).thatWhichIsFoundBy(expectationOfSome(finder)); if(foundElements.isEmpty()) return true; else { for(WebElement element:foundElements){ try{ if(element.isDisplayed()) return false; }catch(StaleElementReferenceException e){} // if stale this implies element is not displayed so we can skip over it } return true; } } @Override public String toString() { return newDescription().appendDescriptionOf(finder).appendText(" to be invisible or not present").toString(); } }; }
public static ExpectedCondition<Boolean> absenceOf(final MFinder<WebElement,SearchContext> finder){ return new ExpectedCondition<Boolean>(){ @Override public String toString() { return new StringDescription().appendText("absence of ").appendDescriptionOf(finder).toString(); } @Override public Boolean apply(WebDriver driver) { try { return checkerFor((SearchContext) driver).isMet(expectationOf(NoItems.<WebElement>noElements(), finder)); }catch(StaleElementReferenceException e){ return false; } } }; }
public void onException(Throwable throwable, WebDriver driver) { if ((throwable instanceof NoSuchElementException) || (throwable instanceof StaleElementReferenceException) || (throwable instanceof AssertionError)) { log.debug("( HANDLED EXCEPTION) -> Message = " + throwable.getClass()); log.trace(throwable.getMessage()); } else { log.info(LoggerUtil.webFormat() + "(EXCEPTION) -> Message = " + throwable.getLocalizedMessage() + " "); logger.exception(throwable); // stack trace as a string // report.reportException("EXCEPTION", throwable // .getLocalizedMessage().substring(0, 50), "");// TODO Make it // // Small // // message log.trace(throwable.getMessage()); } }