Java Code Examples for org.openqa.selenium.support.ui.Wait#until()

The following examples show how to use org.openqa.selenium.support.ui.Wait#until() . 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: ImplicitWaitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: WaitExamplesIT.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
@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 3
Source File: WaitExamplesIT.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
@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 4
Source File: WaitExamplesIT.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
@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 5
Source File: DriverHelper.java    From carina with Apache License 2.0 6 votes vote down vote up
/**
 * 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 6
Source File: UnexpectedAlertBehaviorTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
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 7
Source File: JProgressBarTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
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 8
Source File: AbstractHtmlEngine.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
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 9
Source File: DriverHelper.java    From carina with Apache License 2.0 6 votes vote down vote up
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 10
Source File: AndroidFunctionTest.java    From java-client with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: SeleniumTestUtils.java    From oxd with Apache License 2.0 5 votes vote down vote up
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 12
Source File: BaseTest.java    From oxAuth with MIT License 5 votes vote down vote up
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 13
Source File: AbstractPage.java    From oxTrust with MIT License 5 votes vote down vote up
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 14
Source File: AbstractPage.java    From oxTrust with MIT License 5 votes vote down vote up
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 15
Source File: DriverHelper.java    From carina with Apache License 2.0 5 votes vote down vote up
/**
 * Cancels alert modal.
 */
public void cancelAlert() {
    WebDriver drv = getDriver();
    Wait<WebDriver> wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, RETRY_TIME);
    try {
        wait.until((Function<WebDriver, Object>) dr -> isAlertPresent());
        drv.switchTo().alert().dismiss();
        Messager.ALERT_CANCELED.info("");
    } catch (Exception e) {
        Messager.ALERT_NOT_CANCELED.error("");
    }
}
 
Example 16
Source File: AppiumFluentWaitTest.java    From java-client with Apache License 2.0 5 votes vote down vote up
@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 17
Source File: DockerSessionFactory.java    From selenium with Apache License 2.0 5 votes vote down vote up
private void waitForServerToStart(HttpClient client, Duration duration) {
  Wait<Object> wait = new FluentWait<>(new Object())
      .withTimeout(duration)
      .ignoring(UncheckedIOException.class);

  wait.until(obj -> {
    HttpResponse response = client.execute(new HttpRequest(GET, "/status"));
    LOG.fine(string(response));
    return 200 == response.getStatus();
  });
}
 
Example 18
Source File: DistributorTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldReleaseSlotOnceSessionEnds() {
  SessionMap sessions = new LocalSessionMap(tracer, bus);

  CombinedHandler handler = new CombinedHandler();
  Distributor distributor = new LocalDistributor(
      tracer,
      bus,
      new PassthroughHttpClient.Factory(handler),
      sessions,
      null);
  handler.addHandler(distributor);

  Node node = createNode(caps, 1, 0);
  handler.addHandler(node);
  distributor.add(node);

  // Use up the one slot available
  Session session;
  try (NewSessionPayload payload = NewSessionPayload.create(caps)) {
     session = distributor.newSession(createRequest(payload)).getSession();
  }

  // Make sure the session map has the session
  sessions.get(session.getId());

  node.stop(session.getId());

  // Now wait for the session map to say the session is gone.
  Wait<Object> wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(2));
  wait.until(obj -> {
    try {
      sessions.get(session.getId());
      return false;
    } catch (NoSuchSessionException e) {
      return true;
    }
  });

  wait.until(obj -> distributor.getStatus().hasCapacity());

  // And we should now be able to create another session.
  try (NewSessionPayload payload = NewSessionPayload.create(caps)) {
    distributor.newSession(createRequest(payload));
  }
}
 
Example 19
Source File: AbsFinder.java    From colibri-ui with Apache License 2.0 4 votes vote down vote up
@Override
public WebElement waitVisible(By by) {
    Wait<WebDriver> wait = new WebDriverWait(getDriver(), getDriversSettings().getFindingTimeOutInSeconds());
    return wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}
 
Example 20
Source File: AbsFinder.java    From colibri-ui with Apache License 2.0 4 votes vote down vote up
@Override
public WebElement waitClickable(By by) {
    Wait<WebDriver> wait = new WebDriverWait(getDriver(), getDriversSettings().getFindingTimeOutInSeconds());
    return wait.until(ExpectedConditions.elementToBeClickable(by));
}