public static ExpectedCondition<Boolean> absenceElementBy(final By locator) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(final WebDriver driver) { try { driver.findElement(locator); return false; } catch (WebDriverException ignored) { return true; } } @Override public String toString() { return String.format("absence of element located by %s", locator); } }; }
/** * We don't know the actual window title without switching to one. * This method was always used to make sure that the window appeared. After it we switched to appeared window. * Switching between windows is rather time consuming operation * <p> * To avoid the double switching to the window we are switching to window in this method * <p> * The same approach is applies to all ExpectedConditions for windows * * @param title - title of window * @return - handle of expected window */ public static ExpectedCondition<String> appearingOfWindowAndSwitchToIt(final String title) { return new ExpectedCondition<String>() { @Override public String apply(final WebDriver driver) { final String initialHandle = driver.getWindowHandle(); for (final String handle : driver.getWindowHandles()) { if (needToSwitch(initialHandle, handle)) { driver.switchTo().window(handle); if (driver.getTitle().equals(title)) { return handle; } } } driver.switchTo().window(initialHandle); return null; } @Override public String toString() { return String.format("appearing of window by title %s and switch to it", title); } }; }
/** * Checks if specified node property has specified value * * @param session Jcr session. * @param nodePath Absolute path to node. * @param propertyName Property name. * @param propertyValue Property value. * @return True if node property has specified value. */ public static ExpectedCondition<Boolean> hasNodePropertyValue(final Session session, final String nodePath, final String propertyName, final String propertyValue) { LOG.debug("Checking if node '{}' has property '{}' with value '{}'", nodePath, propertyName, propertyValue); return input -> { Boolean result = null; try { session.refresh(true); result = session.getNode(nodePath).getProperty(propertyName).getValue().getString() .equals(propertyValue); } catch (RepositoryException e) { LOG.error(JCR_ERROR, e); } return result; }; }
/** * 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; }
public static ExpectedCondition<Boolean> ajaxCompleted() { return new ExpectedCondition<Boolean>() { boolean result; @Override public Boolean apply(WebDriver driver) { try { result = (Boolean) ((JavascriptExecutor) driver).executeScript("return typeof($) !== 'undefined' && $.active == 0"); //System.out.println("Ajax return $.active == 0 is: '" + result + "'"); } catch (WebDriverException e) { return false; } return result; } public String toString() { return "Ajax return $.active == 0 is: '" + result + "'"; } }; }
/** * 根据标题中包含某个子串来等待 * @param title 标题子串 * @param timeOutInMillis 超时时间毫秒数 * @param delayedMillis 延迟毫秒数 */ public void waitWithTitleAndDelayed(final String title, int timeOutInMillis, int delayedMillis) { (new WebDriverWait(this, timeOutInMillis/1000)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { String t = d.getTitle(); if (StringUtils.isEmpty(title)) { //等到有title就停止 return StringUtils.isNotBlank(t); } return t != null && t.contains(title); } }); if (delayedMillis > 0) { sleep(delayedMillis); } }
/** * 根据内容中包含某个子串来等待 * @param content 内容子串 * @param timeOutInMillis 超时时间毫秒数 * @param delayedMillis 延迟毫秒数 */ public void waitWithContentAndDelayed(final String content, int timeOutInMillis, int delayedMillis) { (new WebDriverWait(this, timeOutInMillis/1000)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { String html = d.getPageSource(); if (StringUtils.isEmpty(content)) { //等到有内容就停止 return StringUtils.isNotBlank(html); } return html != null && html.contains(content); } }); if (delayedMillis > 0) { sleep(delayedMillis); } }
public static ExpectedCondition<String> appearingOfWindowByPartialTitle(final String fullTitle) { return new ExpectedCondition<String>() { @Override public String apply(final WebDriver driver) { final String initialHandle = driver.getWindowHandle(); for (final String handle : driver.getWindowHandles()) { if (needToSwitch(initialHandle, handle)) { driver.switchTo().window(handle); if (fullTitle.contains(driver.getTitle().split("\\(")[0].trim())) { return handle; } } } driver.switchTo().window(initialHandle); return null; } @Override public String toString() { return String.format("appearing of window by partial title %s and switch to it", fullTitle); } }; }
public static ExpectedCondition<String> appearingOfWindowWithNewTitle(final Set<String> oldTitle) { return new ExpectedCondition<String>() { @Override public String apply(final WebDriver driver) { Set<String> windowHandles = driver.getWindowHandles(); if (windowHandles.containsAll(oldTitle)) { windowHandles.removeAll(oldTitle); if (!windowHandles.isEmpty()) { return windowHandles.iterator().next(); } } return null; } @Override public String toString() { return String.format("appearing of window with new title. Old windows titles %s", oldTitle); } }; }
public static ExpectedCondition<String> appearingOfWindowByPartialUrl(final String url) { return new ExpectedCondition<String>() { @Override public String apply(final WebDriver driver) { final String initialHandle = driver.getWindowHandle(); for (final String handle : driver.getWindowHandles()) { if (needToSwitch(initialHandle, handle)) { driver.switchTo().window(handle); if (driver.getCurrentUrl().contains(url)) { return handle; } } } driver.switchTo().window(initialHandle); return null; } @Override public String toString() { return String.format("appearing of window by partial url %s and switch to it", url); } }; }
/** * Returns a 'wait' proxy that determines if the specified element reference has gone stale. * * @param element the element to wait for * @return 'false' if the element reference is still valid; otherwise 'true' */ public static Coordinator<Boolean> stalenessOf(final WebElement element) { return new Coordinator<Boolean>() { private final ExpectedCondition<Boolean> condition = conditionInitializer(); // initializer for [condition] field private final ExpectedCondition<Boolean> conditionInitializer() { if (element instanceof WrapsElement) { return ExpectedConditions.stalenessOf(((WrapsElement) element).getWrappedElement()); } else { return ExpectedConditions.stalenessOf(element); } } @Override public Boolean apply(SearchContext ignored) { return condition.apply(null); } @Override public String toString() { return condition.toString(); } }; }
public void progress() throws Throwable { driver = new JavaDriver(); final WebElement progressbar = driver.findElement(By.cssSelector("progress-bar")); AssertJUnit.assertNotNull("could not find progress-bar", progressbar); AssertJUnit.assertEquals("0", progressbar.getAttribute("value")); driver.findElement(By.cssSelector("button")).click(); Wait<WebDriver> wait = new WebDriverWait(driver, 30); // Wait for a process to complete wait.until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { return progressbar.getAttribute("value").equals("100"); } }); AssertJUnit.assertEquals("100", progressbar.getAttribute("value")); AssertJUnit.assertTrue(driver.findElement(By.cssSelector("text-area")).getText().contains("Done!")); }
/** * Expects that the target element contains the given value as text. * The inner text and 'value' attribute of the element is checked. * * @param locator * is the selenium locator * @param value * is the expected value * @return true or false */ public static ExpectedCondition<Boolean> textToBeEqualsToExpectedValue(final By locator, final String value) { return new ExpectedCondition<Boolean>() { /** * {@inheritDoc} */ @Override public Boolean apply(@Nullable WebDriver driver) { try { WebElement element = driver.findElement(locator); if (element != null && value != null) { if (element.getAttribute(VALUE) == null || !value.equals(element.getAttribute(VALUE).trim())) { if (!value.equals(element.getText())) { return false; } } return true; } } catch (Exception e) { } return false; } }; }
public static ExpectedCondition<WebElement> atLeastOneOfTheseElementsIsPresent(final By... locators) { return new ExpectedCondition<WebElement>() { @Override public WebElement apply(@Nullable WebDriver driver) { WebElement element = null; if (driver != null && locators.length > 0) { for (final By b : locators) { try { element = driver.findElement(b); } catch (final Exception e) { continue; } } } return element; } }; }
/** * An expectation for checking that nb elements present on the web page that match the locator * are visible. Visibility means that the elements are not only displayed but also have a height * and width that is greater than 0. * * @param locator * used to find the element * @param nb * is exactly number of responses * @return the list of WebElements once they are located */ public static ExpectedCondition<List<WebElement>> visibilityOfNbElementsLocatedBy(final By locator, final int nb) { return new ExpectedCondition<List<WebElement>>() { @Override public List<WebElement> apply(WebDriver driver) { int nbElementIsDisplayed = 0; final List<WebElement> elements = driver.findElements(locator); for (final WebElement element : elements) { if (element.isDisplayed()) { nbElementIsDisplayed++; } } return nbElementIsDisplayed == nb ? elements : null; } }; }
/** * @param currentHandles * is list of opened windows. * @return a string with new Window Opens (GUID) */ public static ExpectedCondition<String> newWindowOpens(final Set<String> currentHandles) { return new ExpectedCondition<String>() { /** * {@inheritDoc} */ @Override public String apply(@Nullable WebDriver driver) { if (driver != null && !currentHandles.equals(driver.getWindowHandles())) { for (String s : driver.getWindowHandles()) { if (!currentHandles.contains(s)) { return s; } } } return null; } }; }
private void switchToWindowByTitle( final String windowTitle, long timeoutInSeconds ) { ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() { public Boolean apply( WebDriver driver ) { return switchToWindowByTitle(windowTitle); } }; Wait<WebDriver> wait = new WebDriverWait(webDriver, timeoutInSeconds); try { wait.until(expectation); } catch (Exception e) { throw new SeleniumOperationException("Timeout waiting for Window with title '" + windowTitle + "' to appear.", e); } }
protected Boolean waitForPageToLoad() { WebDriverWait wait = new WebDriverWait(driver, 10); //give up after 10 seconds //keep executing the given JS till it returns "true", when page is fully loaded and ready return wait.until((ExpectedCondition<Boolean>) input -> ( (JavascriptExecutor) input).executeScript("return document.readyState").equals("complete")); }
protected Boolean waitForPageToLoad() { JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; WebDriverWait wait = new WebDriverWait(driver, 10); //give up after 10 seconds //keep executing the given JS till it returns "true", when page is fully loaded and ready return wait.until((ExpectedCondition<Boolean>) input -> { String res = jsExecutor.executeScript("return /loaded|complete/.test(document.readyState);").toString(); return Boolean.parseBoolean(res); }); }
@Override public void visit(WebDriver driver, String url) { final int implicitWait = Integer.parseInt(properties.getProperty("caching.page_load_wait")); driver.manage().timeouts().implicitlyWait(implicitWait, TimeUnit.SECONDS); driver.get(url); LOGGER.fine("Wait for JS complete"); (new WebDriverWait(driver, implicitWait)).until((ExpectedCondition<Boolean>) d -> { final String status = (String) ((JavascriptExecutor) d).executeScript("return document.readyState"); return status.equals("complete"); }); LOGGER.fine("JS complete"); LOGGER.fine("Wait for footer"); (new WebDriverWait(driver, implicitWait)) .until( ExpectedConditions.visibilityOf( driver.findElement(By.name("downarrow")))); LOGGER.info("Footer is there"); try { Thread.sleep(implicitWait * 1000l); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
private ExpectedCondition<WebElement> visibilityOfElementLocated(final By by) { return new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver driver) { try { WebElement element = driver.findElement(by); if (element!=null && element.isDisplayed()) { return element; }else{ return null; } }catch (Exception ex) { return null; } } }; }
/** * Clicks contentFinder tab and checks if it is active. * * @param tab tab to be showed * @return condition for tab to be active */ public static ExpectedCondition<Boolean> showContentFinderTab(final WebElement tab) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { tab.click(); return tab.getAttribute(HtmlTags.Attributes.CLASS).contains( TAB_ACTIVE); } @Override public String toString() { return "Tab is not ready"; } }; }
/** * Clicks contentFinder view and checks is it the active one now. * * @param view view to be showed * @return condition for the view to be active */ public static ExpectedCondition<Boolean> showContentFinderView(final WebElement view) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { view.click(); return view.findElement(By.xpath(VIEW_WRAPPER_XPATH)) .getAttribute(HtmlTags.Attributes.CLASS) .contains(VIEW_ACTIVE); } @Override public String toString() { return String.format(VIEW_IS_NOT_READY); } }; }
/** * Expands content finder and checks if expand button hides. * * @return condition for content finder to be expanded */ public static ExpectedCondition<Boolean> expand() { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { WebElement expandButton = driver.findElement(By.cssSelector(EXPAND_BUTTON_CSS)); expandButton.click(); return !expandButton.isDisplayed(); } @Override public String toString() { return String.format(VIEW_IS_NOT_READY); } }; }
/** * Shows sidekick tab and checks if its active one now. * * @param tab tab to show * @return condition for active tab */ public static ExpectedCondition<Boolean> showSidekickTab(final WebElement tab) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { tab.click(); return tab.findElement(By.xpath(TAB_WRAPPER_XPATH)).getAttribute(HtmlTags.Attributes.CLASS) .contains( TAB_ACTIVE); } @Override public String toString() { return "Tab is not ready"; } }; }
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; } }; }
public <T> T getWithRetry(String url, ExpectedCondition<T> expectedCondition, Long duration, TimeUnit timeUnit, int retryCount, ExpectedCondition retryImmediatelyCondition) { TimeoutException lastException = null; RetryImmediateCondition<T> condition = new RetryImmediateCondition<T>(expectedCondition, retryImmediatelyCondition); for (int ctr = 0; ctr < retryCount; ctr++) { try { boolean gotIt = get(url, condition, duration, timeUnit); if (gotIt && !condition.retry) return condition.ret; } catch (TimeoutException ignored) { lastException = ignored; } } throw lastException; }
public static ExpectedCondition<Boolean> jsReturnedTrue(final String script, final Object... arguments) { return new ExpectedCondition<Boolean>() { Object result; public Boolean apply(WebDriver webDriver) { try { this.result = ((JavascriptExecutor)webDriver).executeScript(script, arguments); return (Boolean) this.result; } catch (Exception e) { return false; } } public String toString() { return String.format( "expected script: %s\n" + "to return: true\n" + "but returned: %s\n", script, this.result ); } }; }
public void getWebeleByID() { IdInforSend inforSend = new IdInforSend(); webDriver .get("http://web.daycogarage.com/catalogue/zh-cn/search-product-by-code?t=2&c=90499401&a=1"); WebDriverWait wait = new WebDriverWait(webDriver, 10); wait.until(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver d) { return d.findElement(By.id("ContainerInformationProducts")); } }); WebElement webElement = webDriver.findElement(By .id("ContainerInformationProducts")); inforSend.setWebElement(webElement); inforSend.sendProductInfor(); }
@Override public void perform(final SelectAction action, final ScenarioExecutionContext context) { WebDriver driver = context.getDriver(); WebElement element = (new WebDriverWait(driver, getActionTimeout(action, context))).until(new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver d) { return filter(context, action); } }); Actions actions = new Actions(driver); actions.moveToElement(element).perform(); if (element.getTagName().equalsIgnoreCase(OPTION)) { element.click(); } else { Select select = new Select(element); select.selectByValue(action.getValue()); } }
@Test public void testTitle() throws IOException { // Find elements by attribute lang="READ_MORE_BTN" List<WebElement> elements = driver .findElements(By.cssSelector("[lang=\"READ_MORE_BTN\"]")); //Click the selected button elements.get(0).click(); assertTrue("The page title should be chagned as expected", (new WebDriverWait(driver, 5)) .until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().equals("我眼中软件工程人员该有的常识"); } }) ); }
@Test public void testTitle() throws IOException { // Find elements by attribute lang="READ_MORE_BTN" List<WebElement> elements = driver .findElements(By.cssSelector("[lang=\"READ_MORE_BTN\"]")); //Click the selected button elements.get(0).click(); assertTrue("The page title should be chagned as expected", (new WebDriverWait(driver, 3)) .until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().equals("我眼中软件工程人员该有的常识"); } }) ); }
@When("^I search for tests containing \"([^\"]*)\"$") public void iSearchForTestsContaining(final String searchedTerm) throws Throwable { Aside aside = reportHomePage.getAside(); final WebElement searchInput = aside.getSearchInput(); // retries typing as there is known bug in selenium: // https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/4446 bobcatWait.withTimeout(Timeouts.MEDIUM).until( new ExpectedCondition<Boolean>() { @Nullable @Override public Boolean apply(@Nullable WebDriver input) { searchInput.clear(); searchInput.sendKeys(searchedTerm); return searchInput.getAttribute("value").equals(searchedTerm); } }); }
@Override public void perform(final EnsureAction action, final ScenarioExecutionContext context) { WebDriver driver = context.getDriver(); final Boolean absent = Boolean.parseBoolean(action.getAbsent()); (new WebDriverWait(driver, getActionTimeout(action, context))).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { WebElement webElement = filter(context, action); if(webElement == null){ return absent; } else { if(absent){ return Boolean.FALSE; } return webElement.isDisplayed(); } } }); }
/** * 根据标题中包含某个子串来等待 * @param title 标题子串 * @param timeOutInMillis 超时时间毫秒数 */ public void waitWithTitle(final String title, int timeOutInMillis) { (new WebDriverWait(this, timeOutInMillis/1000)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { String t = d.getTitle(); if (StringUtils.isEmpty(title)) { //等到有title就停止 return StringUtils.isNotBlank(t); } return t != null && t.contains(title); } }); }
/** * 根据内容中包含某个子串来等待 * @param content 内容子串 * @param timeOutInMillis 超时时间毫秒数 */ public void waitWithContent(final String content, int timeOutInMillis) { (new WebDriverWait(this, timeOutInMillis/1000)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { String html = d.getPageSource(); if (StringUtils.isEmpty(content)) { //等到有内容就停止 return StringUtils.isNotBlank(html); } return html != null && html.contains(content); } }); }
public static ExpectedCondition<WebElement> presenceOfElementLocatedBy(final SearchContext searchContext, final By locator) { return new ExpectedCondition<WebElement>() { @Override public WebElement apply(final WebDriver driver) { return searchContext.findElements(locator).isEmpty() ? null : searchContext.findElements(locator).get(0); } @Override public String toString() { return String.format("presence of element located by %s -> %s", searchContext, locator); } }; }
public static ExpectedCondition<WebElement> presenceOfElementLocatedBy(final By locator) { return new ExpectedCondition<WebElement>() { @Override public WebElement apply(final WebDriver driver) { return driver.findElements(locator).isEmpty() ? null : driver.findElements(locator).get(0); } @Override public String toString() { return String.format("presence of element located by %s", locator); } }; }
public static ExpectedCondition<List<WebElement>> presenceOfAllElementsLocatedBy(final TeasyElement searchContext, final By locator) { return new ExpectedCondition<List<WebElement>>() { @Override public List<WebElement> apply(final WebDriver driver) { return searchContext.findElements(locator).isEmpty() ? null : searchContext.findElements(locator); } @Override public String toString() { return String.format("presence of all elements located by %s -> %s", searchContext, locator); } }; }