org.openqa.selenium.support.ui.FluentWait Java Examples

The following examples show how to use org.openqa.selenium.support.ui.FluentWait. 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: ToastDetector.java    From carina with Apache License 2.0 6 votes vote down vote up
private void waitForToast() {
    LOGGER.info("Wait for toast...");
    isPresent = false;
    FluentWait<WebDriver> fluentWait = new FluentWait<>(webDriver);
    fluentWait.withTimeout(waitTimeout, TimeUnit.SECONDS).pollingEvery(300, TimeUnit.MILLISECONDS).until(new Function<WebDriver, Boolean>() {
        @Override
        public Boolean apply(WebDriver input) {
            List<?> webElemenList = webDriver.findElements(By.xpath(String.format(TOAST_PATTERN, toastToWait)));
            if (webElemenList.size() == 1) {
                LOGGER.info("Toast with text present: " + toastToWait);
                isPresent = true;
                return true;
            } else {
                return false;
            }
        }
    });
}
 
Example #2
Source File: AppiumUtils.java    From Quantum with MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "deprecation" })
private static MobileElement fluentWait(AppiumDriver driver, By xpath) {
	MobileElement waitElement = null;

	FluentWait<RemoteWebDriver> fwait = new FluentWait<RemoteWebDriver>(driver).withTimeout(15, TimeUnit.SECONDS)
			.pollingEvery(500, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class)
			.ignoring(TimeoutException.class);

	try {
		waitElement = (MobileElement) fwait.until(new Function<RemoteWebDriver, WebElement>() {
			public WebElement apply(RemoteWebDriver driver) {
				return driver.findElement(xpath);
			}
		});
	} catch (Exception e) {
	}
	return waitElement;
}
 
Example #3
Source File: ByChained.java    From java-client with Apache License 2.0 6 votes vote down vote up
@Override
public WebElement findElement(SearchContext context) {
    AppiumFunction<SearchContext, WebElement> searchingFunction = null;

    for (By by: bys) {
        searchingFunction = Optional.ofNullable(searchingFunction != null
                ? searchingFunction.andThen(getSearchingFunction(by)) : null).orElse(getSearchingFunction(by));
    }

    FluentWait<SearchContext> waiting = new FluentWait<>(context);

    try {
        checkNotNull(searchingFunction);
        return waiting.until(searchingFunction);
    } catch (TimeoutException e) {
        throw new NoSuchElementException("Cannot locate an element using " + toString());
    }
}
 
Example #4
Source File: AddingNodesTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Before
public void setUpDistributor() throws MalformedURLException {
  tracer = DefaultTestTracer.createTracer();
  bus = new GuavaEventBus();

  handler = new CombinedHandler();
  externalUrl = new URL("http://example.com");
  HttpClient.Factory clientFactory = new RoutableHttpClientFactory(
    externalUrl,
    handler,
    HttpClient.Factory.createDefault());

  LocalSessionMap sessions = new LocalSessionMap(tracer, bus);
  Distributor local = new LocalDistributor(tracer, bus, clientFactory, sessions, null);
  handler.addHandler(local);
  distributor = new RemoteDistributor(tracer, clientFactory, externalUrl);

  wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(2));
}
 
Example #5
Source File: SessionMapTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: NodeTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: TestWebElementRenderChecker.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void waitElementIsStatic(FluentWait<WebDriver> webDriverWait, WebElement webElement) {
  AtomicInteger sizeHashCode = new AtomicInteger();

  webDriverWait.until(
      (ExpectedCondition<Boolean>)
          driver -> {
            Dimension newDimension = waitAndGetWebElement(webElement).getSize();

            if (dimensionsAreEquivalent(sizeHashCode, newDimension)) {
              return true;
            } else {
              sizeHashCode.set(getSizeHashCode(newDimension));
              return false;
            }
          });
}
 
Example #8
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 #9
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 #10
Source File: WebSocketServingTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void webSocketHandlersShouldBeAbleToFireMoreThanOneMessage() {
  server = new NettyServer(
    defaultOptions(),
    req -> new HttpResponse(),
    (uri, sink) -> Optional.of(msg -> {
      sink.accept(new TextMessage("beyaz peynir"));
      sink.accept(new TextMessage("cheddar"));
    })).start();

  HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl());
  List<String> messages = new LinkedList<>();
  WebSocket socket = client.openSocket(new HttpRequest(GET, "/cheese"), new WebSocket.Listener() {
    @Override
    public void onText(CharSequence data) {
      messages.add(data.toString());
    }
  });

  socket.send(new TextMessage("Hello"));

  new FluentWait<>(messages).until(msgs -> msgs.size() == 2);
}
 
Example #11
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 #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: FluentWaitForWebElement.java    From webDriverExperiments with MIT License 5 votes vote down vote up
@Test
public void waitForWebElementFluentlyPredicate(){

    new FluentWait<WebElement>(countdown).
            withTimeout(10, TimeUnit.SECONDS).
            pollingEvery(100,TimeUnit.MILLISECONDS).
            until(new Predicate<WebElement>() {
                @Override
                public boolean apply(WebElement element) {
                    return element.getText().endsWith("04");
                }
            }
            );
}
 
Example #14
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 #15
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 #16
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 #17
Source File: DistributedCdpTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private void waitUntilUp(int port) {
  try {
    HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();
    HttpClient client = clientFactory.createClient(new URL("http://localhost:" + port));

    new FluentWait<>(client)
      .ignoring(UncheckedIOException.class)
      .withTimeout(ofSeconds(15))
      .until(http -> http.execute(new HttpRequest(GET, "/status")).isSuccessful());
  } catch (MalformedURLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #18
Source File: FluentWaitForWebElement.java    From webDriverExperiments with MIT License 5 votes vote down vote up
@Test
public void waitForWebElementFluently(){

    new FluentWait<WebElement>(countdown).
            withTimeout(10, TimeUnit.SECONDS).
            pollingEvery(100,TimeUnit.MILLISECONDS).
            until(new Function<WebElement, Boolean>() {
                @Override
                public Boolean apply(WebElement element) {
                    return element.getText().endsWith("04");
                }
            }
            );
}
 
Example #19
Source File: FluentWaitForWebElement.java    From webDriverExperiments with MIT License 5 votes vote down vote up
@Test
public void waitForWebElementFluentlyPredicate(){

    new FluentWait<WebElement>(countdown).
            withTimeout(10, TimeUnit.SECONDS).
            pollingEvery(100,TimeUnit.MILLISECONDS).
            until(new Predicate<WebElement>() {
                @Override
                public boolean apply(WebElement element) {
                    return element.getText().endsWith("04");
                }
            }
            );
}
 
Example #20
Source File: AppiumElementLocator.java    From java-client with Apache License 2.0 5 votes vote down vote up
private <T> T waitFor(Supplier<T> supplier) {
    WaitingFunction<T> function = new WaitingFunction<>();
    try {
        FluentWait<Supplier<T>> wait = new FluentWait<>(supplier)
                .ignoring(NoSuchElementException.class);
        wait.withTimeout(duration);
        return wait.until(function);
    } catch (TimeoutException e) {
        if (function.foundStaleElementReferenceException != null) {
            throw StaleElementReferenceException
                    .class.cast(function.foundStaleElementReferenceException);
        }
        throw e;
    }
}
 
Example #21
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 #22
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 #23
Source File: WaitFactory.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Wait<T> createWait(T input, Duration timeout, Duration pollingPeriod)
{
    FluentWait<T> fluentWait = new FluentWait<>(input).pollingEvery(pollingPeriod);
    DescriptiveWait<T> wait = new DescriptiveWait<>(fluentWait);
    wait.setTimeout(timeout);
    return wait;
}
 
Example #24
Source File: AbstractPage.java    From oxTrust with MIT License 5 votes vote down vote up
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 #25
Source File: CustomScriptManagePage.java    From oxTrust with MIT License 5 votes vote down vote up
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 #26
Source File: BasePageObjects.java    From kspl-selenium-helper with GNU General Public License v3.0 5 votes vote down vote up
protected static void waitForFrame(Log log, WebDriver driver, By by,
		int duration) {
	try {
		new FluentWait<WebDriver>(driver)
				.withTimeout(duration,TimeUnit.SECONDS)
				.pollingEvery(10,TimeUnit.SECONDS)
				.ignoring(StaleElementReferenceException.class,NoSuchElementException.class)
				.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(by));
	} catch (StaleElementReferenceException e) {
		e.printStackTrace();
	}
}
 
Example #27
Source File: BasePageObjects.java    From kspl-selenium-helper with GNU General Public License v3.0 5 votes vote down vote up
protected static void waitForElementVisible(Log log, WebDriver driver,
		WebElement element, int duration) {
	try {
		new FluentWait<WebDriver>(driver)
				.withTimeout(duration, TimeUnit.SECONDS)
				.pollingEvery(10,TimeUnit.SECONDS)
				.ignoring(StaleElementReferenceException.class, NoSuchElementException.class)
				.until(ExpectedConditions.visibilityOf(element));
	} catch (StaleElementReferenceException e) {
		if(log != null)
			log.write(e);
	}

}
 
Example #28
Source File: BasePageObjects.java    From kspl-selenium-helper with GNU General Public License v3.0 5 votes vote down vote up
protected static void waitForElementVisible(Log log, WebDriver driver,
		By by, int duration) {
	try {
		new FluentWait<WebDriver>(driver)
				.withTimeout(duration, TimeUnit.SECONDS)
				.pollingEvery(10,TimeUnit.SECONDS)
				.ignoring(StaleElementReferenceException.class, NoSuchElementException.class)
				.until(ExpectedConditions.visibilityOfElementLocated(by));
	} catch (StaleElementReferenceException e) {
		if(log != null)
			log.write(e);
	}
}
 
Example #29
Source File: BasePageObjects.java    From kspl-selenium-helper with GNU General Public License v3.0 5 votes vote down vote up
protected static void waitForClickable(Log log, WebDriver driver,
		WebElement element, int duration) {
	try {
		new FluentWait<WebDriver>(driver)
				.withTimeout(duration, TimeUnit.SECONDS)
				.pollingEvery(10,TimeUnit.SECONDS)
				.ignoring(StaleElementReferenceException.class, NoSuchElementException.class)
				.until(ExpectedConditions.elementToBeClickable(element));
	} catch (StaleElementReferenceException e) {
		if(log != null)
			log.write(e);
	}

}
 
Example #30
Source File: BasePageObjects.java    From kspl-selenium-helper with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Function to explicitly wait for an element to be clickable
 *
 * @param log -To log steps.
 * 
 * @param driver
 *            -WebDriver currently in use by script
 * @param by
 *            -By identifying the element to be interacted with
 * @param duration
 *            -Int identifying the wait time in seconds
 */
protected static void waitForClickable(Log log, WebDriver driver, By by,
		int duration) {
	try {
		new FluentWait<WebDriver>(driver)
				.withTimeout(duration, TimeUnit.SECONDS)
				.pollingEvery(10,TimeUnit.SECONDS)
				.ignoring(StaleElementReferenceException.class, NoSuchElementException.class)
				.until(ExpectedConditions.elementToBeClickable(by));
	} catch (StaleElementReferenceException e) {
		if(log != null)
			log.write(e);
	}
}