类org.openqa.selenium.support.ui.FluentWait源码实例Demo

下面列出了怎么用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());
}
 
源代码4 项目: Quantum   文件: AppiumUtils.java
@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;
}
 
源代码5 项目: che   文件: TestWebElementRenderChecker.java
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;
            }
          });
}
 
源代码6 项目: java-client   文件: ByChained.java
@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());
    }
}
 
源代码7 项目: selenium   文件: AddingNodesTest.java
@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));
}
 
源代码8 项目: selenium   文件: SessionMapTest.java
@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;
    }
  });
}
 
源代码9 项目: selenium   文件: NodeTest.java
@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);
}
 
源代码10 项目: selenium   文件: WebSocketServingTest.java
@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);
}
 
源代码11 项目: carina   文件: ToastDetector.java
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;
            }
        }
    });
}
 
源代码12 项目: vividus   文件: WaitFactory.java
@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;
}
 
源代码13 项目: vividus   文件: WaitActionsTests.java
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());
}
 
源代码15 项目: jwala   文件: JwalaUi.java
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");
}
 
源代码19 项目: blueocean-plugin   文件: ClassicJobApi.java
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));
}
 
源代码20 项目: blueocean-plugin   文件: SmartWebElement.java
/**
 * 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));
}
 
源代码21 项目: blueocean-plugin   文件: SSEClientRule.java
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"));
}
 
源代码23 项目: selenium-shutterbug   文件: Browser.java
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);
    }
}
 
源代码24 项目: che   文件: OrganizationListPage.java
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();
          });
}
 
源代码25 项目: che   文件: AddMember.java
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();
          });
}
 
源代码26 项目: che   文件: AddMember.java
/**
 * 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;
          });
}
 
源代码27 项目: che   文件: PullRequestPanel.java
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();
}
 
源代码28 项目: che   文件: CommandsToolbar.java
/** 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());
}
 
源代码29 项目: che   文件: Swagger.java
/** 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();
}
 
源代码30 项目: frameworkium-core   文件: UITestLifecycle.java
/**
 * @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);
}
 
 类所在包
 类方法
 同包方法