下面列出了怎么用org.openqa.selenium.support.ui.FluentWait的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
@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);
}
@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());
}
@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;
}
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;
}
});
}
@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());
}
}
@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));
}
@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;
}
});
}
@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);
}
@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);
}
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;
}
}
});
}
@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;
}
private void mockDescriptiveWait(TemporalUnit timeunit)
{
FluentWait<WebDriver> fluentWait = new FluentWait<>(webDriver);
DescriptiveWait<WebDriver> descriptiveWait = new DescriptiveWait<>(fluentWait);
descriptiveWait.setTimeout(Duration.of(TIMEOUT_VALUE, timeunit));
Mockito.lenient().when(waitFactory.createWait(webDriver)).thenReturn(descriptiveWait);
Mockito.lenient().when(waitFactory.createWait(webDriver, Duration.of(TIMEOUT_VALUE, timeunit)))
.thenReturn(descriptiveWait);
}
@Test
public void fluentWaitIgnoringSingleException() 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)
.withMessage("The message you will see in if a TimeoutException is thrown");
wait.until(AdditionalConditions.angularHasFinishedProcessing());
}
public void testForBusyIcon(final int showTimeout, final int hideTimeout) {
new FluentWait(driver).withTimeout(showTimeout, TimeUnit.SECONDS).pollingEvery(100, TimeUnit.MILLISECONDS)
.until(ExpectedConditions.numberOfElementsToBe(
By.xpath("//div[contains(@class, 'AppBusyScreen') and contains(@class, 'show')]"), 1));
// Please take note that when "display none" is re-inserted, the whitespace in between the attribute and the value is not there anymore e.g.
// display: none => display:none hence the xpath => contains(@style,'display:none')
new WebDriverWait(driver, hideTimeout)
.until(ExpectedConditions.numberOfElementsToBe(
By.xpath("//div[contains(@class, 'AppBusyScreen') and contains(@class, 'show')]"), 0));
}
@Override
public WebElement getClickableElementFoundBy(
final boolean valueAlias,
@NotNull final String value,
@NotNull final FeatureState featureState,
final long waitTime) {
checkArgument(StringUtils.isNotBlank(value));
checkNotNull(featureState);
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
long time = 0;
while (time < waitTime * Constants.MILLISECONDS_PER_SECOND) {
for (final String locationMethod : LOCATION_METHODS) {
try {
final By by = getBy.getBy(locationMethod, valueAlias, value, featureState);
final FluentWait<WebDriver> wait = new FluentWait<>(webDriver)
.withTimeout(Duration.ofMillis(Constants.TIME_SLICE));
final ExpectedCondition<WebElement> condition =
ExpectedConditions.elementToBeClickable(by);
return wait.until(condition);
} catch (final Exception ignored) {
/*
Do nothing
*/
}
time += Constants.TIME_SLICE;
}
}
throw new WebElementException("All attempts to find element failed");
}
@Override
public WebElement getVisibleElementFoundBy(
final boolean valueAlias,
@NotNull final String value,
@NotNull final FeatureState featureState,
final long waitTime) {
checkArgument(StringUtils.isNotBlank(value));
checkNotNull(featureState);
checkArgument(waitTime >= 0);
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
long time = 0;
do {
for (final String locationMethod : LOCATION_METHODS) {
try {
final By by = getBy.getBy(locationMethod, valueAlias, value, featureState);
final FluentWait<WebDriver> wait = new FluentWait<>(webDriver)
.withTimeout(Duration.ofMillis(Constants.TIME_SLICE));
final ExpectedCondition<WebElement> condition =
ExpectedConditions.visibilityOfElementLocated(by);
return wait.until(condition);
} catch (final Exception ignored) {
/*
Do nothing
*/
}
time += Constants.TIME_SLICE;
}
} while (time < waitTime * Constants.MILLISECONDS_PER_SECOND);
throw new WebElementException("All attempts to find element failed");
}
@Override
public WebElement getPresenceElementFoundBy(
final boolean valueAlias,
@NotNull final String value,
@NotNull final FeatureState featureState,
final long waitTime) {
checkArgument(StringUtils.isNotBlank(value));
checkNotNull(featureState);
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
long time = 0;
while (time < waitTime * Constants.MILLISECONDS_PER_SECOND) {
for (final String locationMethod : LOCATION_METHODS) {
try {
final By by = getBy.getBy(locationMethod, valueAlias, value, featureState);
final FluentWait<WebDriver> wait = new FluentWait<>(webDriver)
.withTimeout(Duration.ofMillis(Constants.TIME_SLICE));
final ExpectedCondition<WebElement> condition =
ExpectedConditions.presenceOfElementLocated(by);
return wait.until(condition);
} catch (final Exception ignored) {
/*
Do nothing
*/
}
time += Constants.TIME_SLICE;
}
}
throw new WebElementException("All attempts to find element failed");
}
public <T> T until(Function<JenkinsServer, T> function, long timeoutInMS) {
return new FluentWait<JenkinsServer>(jenkins)
.pollingEvery(500, TimeUnit.MILLISECONDS)
.withTimeout(timeoutInMS, TimeUnit.MILLISECONDS)
.ignoring(NotFoundException.class)
.until((JenkinsServer server) -> function.apply(server));
}
/**
* Gets elements
* @return the elements found
*/
public List<WebElement> getElements() {
return new FluentWait<>(getDriver())
.pollingEvery(100, TimeUnit.MILLISECONDS)
.withTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class)
.until(driver -> driver.findElements(SmartWebElement.this.by));
}
public void untilEvents(Predicate<List<JSONObject>> isEvents) {
new FluentWait<>(getEvents())
.pollingEvery(1000, TimeUnit.MILLISECONDS)
.withTimeout(120, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class)
.until(new Function<List<JSONObject>, Boolean>() {
public Boolean apply(List<JSONObject> events) {
return isEvents.apply(events);
}
});
}
@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"));
}
public void wait(Function<WebDriver,?> condition, int timeout) {
if(condition!=null) {
new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(timeout))
.ignoring(StaleElementReferenceException.class, NoSuchMethodException.class)
.until(condition);
}else if(timeout>0) {
wait(timeout);
}
}
private void waitForElementDisappearance(String xpath) {
FluentWait<SeleniumWebDriver> wait =
new FluentWait<>(seleniumWebDriver)
.withTimeout(REDRAW_UI_ELEMENTS_TIMEOUT_SEC, TimeUnit.SECONDS)
.pollingEvery(200, TimeUnit.MILLISECONDS)
.ignoring(StaleElementReferenceException.class);
wait.until(
(Function<WebDriver, Boolean>)
driver -> {
List<WebElement> elements = seleniumWebDriver.findElements(By.xpath(xpath));
return elements.isEmpty() || !elements.get(0).isDisplayed();
});
}
private void waitForElementDisappearance(String xpath) {
FluentWait<WebDriver> wait =
new FluentWait<WebDriver>(seleniumWebDriver)
.withTimeout(REDRAW_UI_ELEMENTS_TIMEOUT_SEC, TimeUnit.SECONDS)
.pollingEvery(200, TimeUnit.MILLISECONDS)
.ignoring(StaleElementReferenceException.class);
wait.until(
(Function<WebDriver, Boolean>)
driver -> {
List<WebElement> elements = seleniumWebDriver.findElements(By.xpath(xpath));
return elements.isEmpty() || elements.get(0).isDisplayed();
});
}
/**
* Wait for popup is attached to DOM and animation ends.
*
* @param xpath xpath to match the 'che-popup' element
*/
private void waitForPopupAppearence(String xpath) {
FluentWait<WebDriver> wait =
new FluentWait<WebDriver>(seleniumWebDriver)
.withTimeout(REDRAW_UI_ELEMENTS_TIMEOUT_SEC, TimeUnit.SECONDS)
.pollingEvery(200, TimeUnit.MILLISECONDS)
.ignoring(StaleElementReferenceException.class);
Map<String, Integer> lastSize = new HashMap<>();
lastSize.put("height", 0);
lastSize.put("width", 0);
wait.until(
(Function<WebDriver, Boolean>)
driver -> {
List<WebElement> elements = seleniumWebDriver.findElements(By.xpath(xpath));
if (elements.isEmpty()) {
return false;
}
Dimension size = elements.get(0).getSize();
if (lastSize.get("height") < size.getHeight()
|| lastSize.get("width") < size.getHeight()) {
lastSize.put("height", size.getHeight());
lastSize.put("width", size.getWidth());
return false;
}
return true;
});
}
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();
}
/** 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());
}
/** 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();
}
/**
* @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);
}