org.openqa.selenium.support.ui.Wait Java Examples
The following examples show how to use
org.openqa.selenium.support.ui.Wait.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WaitExamplesIT.java From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License | 6 votes |
@Test public void fluentWaitIgnoringAListOfExceptions() throws MalformedURLException { WebDriver driver = getDriver(); driver.get("https://angularjs.org"); Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(15)) .pollingEvery(Duration.ofMillis(500)) .ignoreAll(Arrays.asList( NoSuchElementException.class, StaleElementReferenceException.class )) .withMessage("The message you will see in if a TimeoutException is thrown"); wait.until(AdditionalConditions.angularHasFinishedProcessing()); wait.until(weFindElementFoo); }
Example #2
Source File: ImplicitWaitTest.java From selenium with Apache License 2.0 | 6 votes |
@Test @NotYetImplemented(SAFARI) public void testShouldRetainImplicitlyWaitFromTheReturnedWebDriverOfFrameSwitchTo() { driver.manage().timeouts().implicitlyWait(1, SECONDS); driver.get(pages.xhtmlTestPage); driver.findElement(By.name("windowOne")).click(); Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(1)); wait.until(ExpectedConditions.numberOfWindowsToBe(2)); String handle = (String)driver.getWindowHandles().toArray()[1]; WebDriver newWindow = driver.switchTo().window(handle); long start = System.currentTimeMillis(); newWindow.findElements(By.id("this-crazy-thing-does-not-exist")); long end = System.currentTimeMillis(); long time = end - start; assertThat(time).isGreaterThanOrEqualTo(1000); }
Example #3
Source File: WebDriverTestContext.java From selenium with Apache License 2.0 | 6 votes |
@Override public void waitFor(final Finder<WebElement, WebDriver> finder, final long timeoutMillis) { final ExpectedCondition<Boolean> elementsDisplayedPredicate = driver -> finder.findFrom(driver).stream().anyMatch(WebElement::isDisplayed); final long defaultSleepTimeoutMillis = 500; final long sleepTimeout = (timeoutMillis > defaultSleepTimeoutMillis) ? defaultSleepTimeoutMillis : timeoutMillis / 2; Wait<WebDriver> wait = new WebDriverWait( driver, Duration.ofMillis(timeoutMillis), Duration.ofMillis(sleepTimeout), clock, sleeper) { @Override protected RuntimeException timeoutException(String message, Throwable lastException) { throw new AssertionError("Element was not rendered within " + timeoutMillis + "ms"); } }; wait.until(elementsDisplayedPredicate); }
Example #4
Source File: UnexpectedAlertBehaviorTest.java From selenium with Apache License 2.0 | 6 votes |
private void runScenarioWithUnhandledAlert( UnexpectedAlertBehaviour behaviour, String expectedAlertText, boolean silently) { Capabilities caps = behaviour == null ? new ImmutableCapabilities() : new ImmutableCapabilities(UNEXPECTED_ALERT_BEHAVIOUR, behaviour); createNewDriver(caps); driver.get(pages.alertsPage); driver.findElement(By.id("prompt-with-default")).click(); Wait<WebDriver> wait1 = silently ? wait : new WebDriverWait(driver, Duration.ofSeconds(10)) .ignoring(UnhandledAlertException.class); wait1.until(elementTextToEqual(By.id("text"), expectedAlertText)); }
Example #5
Source File: AppiumFluentWaitTest.java From java-client with Apache License 2.0 | 6 votes |
@Test public void testIntervalCalculationForCustomStrategy() { final FakeElement el = new FakeElement(); final AtomicInteger callsCounter = new AtomicInteger(0); // Linear dependency final Function<Long, Long> pollingStrategy = x -> x * 2; final Wait<FakeElement> wait = new AppiumFluentWait<>(el, Clock.systemDefaultZone(), duration -> { int callNumber = callsCounter.incrementAndGet(); assertThat(duration.getSeconds(), is(equalTo(pollingStrategy.apply((long) callNumber)))); Thread.sleep(duration.toMillis()); }).withPollingStrategy(info -> ofSeconds(pollingStrategy.apply(info.getNumber()))) .withTimeout(ofSeconds(4)) .pollingEvery(ofSeconds(1)); try { wait.until(FakeElement::isDisplayed); Assert.fail("TimeoutException is expected"); } catch (TimeoutException e) { // this is expected assertThat(callsCounter.get(), is(equalTo(2))); } }
Example #6
Source File: AppiumFluentWaitTest.java From java-client with Apache License 2.0 | 6 votes |
@Test public void testCustomStrategyOverridesDefaultInterval() { final FakeElement el = new FakeElement(); final AtomicInteger callsCounter = new AtomicInteger(0); final Wait<FakeElement> wait = new AppiumFluentWait<>(el, Clock.systemDefaultZone(), duration -> { callsCounter.incrementAndGet(); assertThat(duration.getSeconds(), is(equalTo(2L))); Thread.sleep(duration.toMillis()); }).withPollingStrategy(info -> ofSeconds(2)) .withTimeout(ofSeconds(3)) .pollingEvery(ofSeconds(1)); try { wait.until(FakeElement::isDisplayed); Assert.fail("TimeoutException is expected"); } catch (TimeoutException e) { // this is expected assertThat(callsCounter.get(), is(equalTo(2))); } }
Example #7
Source File: AbstractHtmlEngine.java From ats-framework with Apache License 2.0 | 6 votes |
private void switchToWindowByTitle( final String windowTitle, long timeoutInSeconds, final boolean checkForNotCurrentWindow) { ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() { public Boolean apply( WebDriver driver ) { return switchToWindowByTitle(windowTitle, checkForNotCurrentWindow); } }; 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); } }
Example #8
Source File: JProgressBarTest.java From marathonv5 with Apache License 2.0 | 6 votes |
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!")); }
Example #9
Source File: WaitExamplesIT.java From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License | 6 votes |
@Test public void fluentWaitIgnoringACollectionOfExceptions() throws MalformedURLException { WebDriver driver = getDriver(); driver.get("https://angularjs.org"); List<Class<? extends Throwable>> exceptionsToIgnore = new ArrayList<Class<? extends Throwable>>() { { add(NoSuchElementException.class); add(StaleElementReferenceException.class); } }; Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(15)) .pollingEvery(Duration.ofMillis(500)) .ignoreAll(exceptionsToIgnore) .withMessage("The message you will see in if a TimeoutException is thrown"); wait.until(AdditionalConditions.angularHasFinishedProcessing()); }
Example #10
Source File: WaitExamplesIT.java From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License | 6 votes |
@Test public void fluentWaitIgnoringMultipleExceptions() throws MalformedURLException { WebDriver driver = getDriver(); driver.get("https://angularjs.org"); Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(15)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class) .ignoring(StaleElementReferenceException.class) .withMessage("The message you will see in if a TimeoutException is thrown"); wait.until(AdditionalConditions.angularHasFinishedProcessing()); }
Example #11
Source File: SessionMapTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldAllowEntriesToBeRemovedByAMessage() { local.add(expected); bus.fire(new SessionClosedEvent(expected.getId())); Wait<SessionMap> wait = new FluentWait<>(local).withTimeout(ofSeconds(2)); wait.until(sessions -> { try { sessions.get(expected.getId()); return false; } catch (NoSuchSessionException e) { return true; } }); }
Example #12
Source File: NodeTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void quittingASessionShouldCauseASessionClosedEventToBeFired() { AtomicReference<Object> obj = new AtomicReference<>(); bus.addListener(SESSION_CLOSED, event -> obj.set(event.getData(Object.class))); Session session = node.newSession(createSessionRequest(caps)) .map(CreateSessionResponse::getSession) .orElseThrow(() -> new AssertionError("Cannot create session")); node.stop(session.getId()); // Because we're using the event bus, we can't expect the event to fire instantly. We're using // an inproc bus, so in reality it's reasonable to expect the event to fire synchronously, but // let's play it safe. Wait<AtomicReference<Object>> wait = new FluentWait<>(obj).withTimeout(ofSeconds(2)); wait.until(ref -> ref.get() != null); }
Example #13
Source File: DriverHelper.java From carina with Apache License 2.0 | 6 votes |
/** * Checks that page title is as expected. * * @param expectedTitle * Expected title * @return validation result. */ public boolean isTitleAsExpected(final String expectedTitle) { boolean result; final String decryptedExpectedTitle = cryptoTool.decryptByPattern(expectedTitle, CRYPTO_PATTERN); final WebDriver drv = getDriver(); Wait<WebDriver> wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, RETRY_TIME); try { wait.until((Function<WebDriver, Object>) dr -> drv.getTitle().contains(decryptedExpectedTitle)); result = true; Messager.TITLE_CORERECT.info(drv.getCurrentUrl(), expectedTitle); } catch (Exception e) { result = false; Messager.TITLE_NOT_CORERECT.error(drv.getCurrentUrl(), expectedTitle, drv.getTitle()); } return result; }
Example #14
Source File: DriverHelper.java From carina with Apache License 2.0 | 6 votes |
public boolean isPageOpened(final AbstractPage page, long timeout) { boolean result; final WebDriver drv = getDriver(); Wait<WebDriver> wait = new WebDriverWait(drv, timeout, RETRY_TIME); try { wait.until((Function<WebDriver, Object>) dr -> LogicUtils.isURLEqual(page.getPageURL(), drv.getCurrentUrl())); result = true; } catch (Exception e) { result = false; } if (!result) { LOGGER.warn(String.format("Actual URL differs from expected one. Expected '%s' but found '%s'", page.getPageURL(), drv.getCurrentUrl())); } return result; }
Example #15
Source File: AbstractPage.java From oxTrust with MIT License | 5 votes |
public void fluentWait(int seconds) { try { Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(seconds, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class); wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(locator); } }); } catch (Exception e) { } }
Example #16
Source File: CommandsToolbar.java From che with Eclipse Public License 2.0 | 5 votes |
/** wait appearance of process timer on commands toolbar and try to get value of the timer */ public String getTimerValue() { Wait<WebDriver> wait = new FluentWait<WebDriver>(seleniumWebDriver) .withTimeout(REDRAW_UI_ELEMENTS_TIMEOUT_SEC, TimeUnit.SECONDS) .pollingEvery(200, TimeUnit.MILLISECONDS) .ignoring(StaleElementReferenceException.class); return wait.until(driver -> driver.findElement(By.id(Locators.TIMER_LOCATOR)).getText()); }
Example #17
Source File: AbstractPage.java From oxTrust with MIT License | 5 votes |
public void fluentWaitMinutes(int seconds) { try { Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(seconds, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.MINUTES).ignoring(NoSuchElementException.class); wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(locator); } }); } catch (Exception e) { } }
Example #18
Source File: AbstractPage.java From oxTrust with MIT License | 5 votes |
public WebElement fluentWaitFor(final By locator) { Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(locator); } }); return foo; }
Example #19
Source File: CustomScriptManagePage.java From oxTrust with MIT License | 5 votes |
public void fluentWaitForTableCompute(int finalSize) { Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class); wait.until(new Function<WebDriver, Boolean>() { public Boolean apply(WebDriver driver) { String className = "allScriptFor".concat(currentTabText.split("\\s+")[0]); WebElement firstElement = driver.findElement(By.className(className)).findElements(By.tagName("tr")) .get(0); List<WebElement> scripts = new ArrayList<>(); scripts.add(firstElement); scripts.addAll(firstElement.findElements(By.xpath("following-sibling::tr"))); return scripts.size() == (finalSize + 1); } }); }
Example #20
Source File: BaseTest.java From oxAuth with MIT License | 5 votes |
protected String acceptAuthorization(WebDriver currentDriver, String redirectUri) { String authorizationResponseStr = currentDriver.getCurrentUrl(); // Check for authorization form if client has no persistent authorization if (!authorizationResponseStr.contains("#")) { Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(Duration.ofSeconds(PageConfig.WAIT_OPERATION_TIMEOUT)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class); WebElement allowButton = wait.until(d -> currentDriver.findElement(By.id(authorizeFormAllowButton))); // We have to use JavaScript because target is link with onclick JavascriptExecutor jse = (JavascriptExecutor) currentDriver; jse.executeScript("scroll(0, 1000)"); String previousURL = currentDriver.getCurrentUrl(); Actions actions = new Actions(currentDriver); actions.click(allowButton).perform(); waitForPageSwitch(currentDriver, previousURL); authorizationResponseStr = currentDriver.getCurrentUrl(); if (redirectUri != null && !authorizationResponseStr.startsWith(redirectUri)) { navigateToAuhorizationUrl(currentDriver, authorizationResponseStr); authorizationResponseStr = waitForPageSwitch(authorizationResponseStr); } if (redirectUri == null && !authorizationResponseStr.contains("code=")) { // corner case for redirect_uri = null navigateToAuhorizationUrl(currentDriver, authorizationResponseStr); authorizationResponseStr = waitForPageSwitch(authorizationResponseStr); } } else { fail("The authorization form was expected to be shown."); } return authorizationResponseStr; }
Example #21
Source File: SeleniumTestUtils.java From oxd with Apache License 2.0 | 5 votes |
private static void loginGluuServer( WebDriver driver, String opHost, String userId, String userSecret, String clientId, String redirectUrls, String state, String nonce, List<String> responseTypes, List<String> scopes) { //navigate to opHost driver.navigate().to(getAuthorizationUrl(opHost, clientId, redirectUrls, state, nonce, responseTypes, scopes)); //driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(Duration.ofSeconds(WAIT_OPERATION_TIMEOUT)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class); WebElement loginButton = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver d) { //System.out.println(d.getCurrentUrl()); //System.out.println(d.getPageSource()); return d.findElement(By.id("loginForm:loginButton")); } }); LOG.info("Login page loaded. The current url is: " + driver.getCurrentUrl()); //username field WebElement usernameElement = driver.findElement(By.id("loginForm:username")); usernameElement.sendKeys(userId); //password field WebElement passwordElement = driver.findElement(By.id("loginForm:password")); passwordElement.sendKeys(userSecret); //click on login button loginButton.click(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); }
Example #22
Source File: AppiumFluentWaitTest.java From java-client with Apache License 2.0 | 5 votes |
@Test(expected = TimeoutException.class) public void testDefaultStrategy() { final FakeElement el = new FakeElement(); final Wait<FakeElement> wait = new AppiumFluentWait<>(el, Clock.systemDefaultZone(), duration -> { assertThat(duration.getSeconds(), is(equalTo(1L))); Thread.sleep(duration.toMillis()); }).withPollingStrategy(AppiumFluentWait.IterationInfo::getInterval) .withTimeout(ofSeconds(3)) .pollingEvery(ofSeconds(1)); wait.until(FakeElement::isDisplayed); Assert.fail("TimeoutException is expected"); }
Example #23
Source File: UITestLifecycle.java From frameworkium-core with Apache License 2.0 | 5 votes |
/** * @param timeout timeout for the new Wait * @return a Wait with the given timeout */ public Wait<WebDriver> newWaitWithTimeout(Duration timeout) { return new FluentWait<>(getWebDriver()) .withTimeout(timeout) .ignoring(NoSuchElementException.class) .ignoring(StaleElementReferenceException.class); }
Example #24
Source File: SeleniumTestUtils.java From oxd with Apache License 2.0 | 5 votes |
private static AuthorizationResponse acceptAuthorization(WebDriver driver) { String authorizationResponseStr = driver.getCurrentUrl(); AuthorizationResponse authorizationResponse = null; // Check for authorization form if client has no persistent authorization if (!authorizationResponseStr.contains("#")) { Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(Duration.ofSeconds(WAIT_OPERATION_TIMEOUT)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class); WebElement allowButton = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver d) { //System.out.println(d.getCurrentUrl()); //System.out.println(d.getPageSource()); return d.findElement(By.id("authorizeForm:allowButton")); } }); // We have to use JavaScript because target is link with onclick JavascriptExecutor jse = (JavascriptExecutor) driver; jse.executeScript("scroll(0, 1000)"); String previousURL = driver.getCurrentUrl(); Actions actions = new Actions(driver); actions.click(allowButton).perform(); authorizationResponseStr = driver.getCurrentUrl(); authorizationResponse = new AuthorizationResponse(authorizationResponseStr); LOG.info("Authorization Response url is: " + driver.getCurrentUrl()); } else { fail("The authorization form was expected to be shown."); } return authorizationResponse; }
Example #25
Source File: AndroidFunctionTest.java From java-client with Apache License 2.0 | 5 votes |
@Test public void complexWaitingTestWithPreCondition() { AppiumFunction<Pattern, List<WebElement>> compositeFunction = searchingFunction.compose(contextFunction); Wait<Pattern> wait = new FluentWait<>(Pattern.compile("WEBVIEW")) .withTimeout(ofSeconds(30)); List<WebElement> elements = wait.until(compositeFunction); assertThat("Element size should be 1", elements.size(), is(1)); assertThat("WebView is expected", driver.getContext(), containsString("WEBVIEW")); }
Example #26
Source File: PageFactoryTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void shouldNotThrowANoSuchElementExceptionWhenUsedWithAFluentWait() { driver = mock(WebDriver.class); when(driver.findElement(ArgumentMatchers.any())).thenThrow(new NoSuchElementException("because")); TickingClock clock = new TickingClock(); Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(1), Duration.ofMillis(1001), clock, clock); PublicPage page = new PublicPage(); PageFactory.initElements(driver, page); WebElement element = page.q; assertThatExceptionOfType(TimeoutException.class) .isThrownBy(() -> wait.until(ExpectedConditions.visibilityOf(element))); }
Example #27
Source File: BasePage.java From frameworkium-core with Apache License 2.0 | 5 votes |
/** * Added to enable testing and, one day, remove coupling to BaseUITest. */ public BasePage(WebDriver driver, Wait<WebDriver> wait) { this.driver = driver; this.wait = wait; JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver; this.visibility = new Visibility(wait, javascriptExecutor); this.javascriptWait = new JavascriptWait(javascriptExecutor, wait); }
Example #28
Source File: Swagger.java From che with Eclipse Public License 2.0 | 5 votes |
/** expand 'workspace' item */ private void expandWorkSpaceItem() { Wait fluentWait = new FluentWait(seleniumWebDriver) .withTimeout(ELEMENT_TIMEOUT_SEC, SECONDS) .pollingEvery(MINIMUM_SEC, SECONDS) .ignoring(StaleElementReferenceException.class, NoSuchElementException.class); fluentWait.until((ExpectedCondition<Boolean>) input -> workSpaceLink.isEnabled()); workSpaceLink.click(); }
Example #29
Source File: PullRequestPanel.java From che with Eclipse Public License 2.0 | 5 votes |
public void openPullRequestOnGitHub() { Wait<WebDriver> wait = new FluentWait(seleniumWebDriver) .withTimeout(ATTACHING_ELEM_TO_DOM_SEC, SECONDS) .pollingEvery(500, MILLISECONDS) .ignoring(WebDriverException.class); wait.until(visibilityOfElementLocated(By.xpath(PullRequestLocators.OPEN_GITHUB_BTN))).click(); }
Example #30
Source File: ExplicitWaitTest.java From webdrivermanager-examples with Apache License 2.0 | 5 votes |
@Test public void test() { driver.get("https://bonigarcia.github.io/selenium-jupiter/"); Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(of(10, SECONDS)).pollingEvery(of(1, SECONDS)) .ignoring(NoSuchElementException.class); wait.until(titleContains("JUnit 5 extension for Selenium")); }