下面列出了怎么用org.openqa.selenium.TimeoutException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void refresh(WebDriver webDriver)
{
LOGGER.info("Refreshing the current page");
try
{
webDriver.navigate().refresh();
}
catch (TimeoutException ex)
{
handleTimeoutException(ex);
}
// Chrome browser doesn't wait for page load to the end (like Firefox) and stops waiting when the web site is
// still loading. In this case Vividus additional wait.
waitActions.waitForPageLoad();
}
private static String switchToTargetWindow(WebDriver driver, String target) {
String result;
try {
if (null == wait(driver).until(windowToBeAvailableAndSwitchToIt(target))) {
result = "����ִ��ʧ�ܣ��л����ھ��ʧ�ܣ�δ�ҵ����ֵΪ��" + target + "���Ķ���";
LogUtil.APP.warn("�л����ھ��ʧ�ܣ�δ�ҵ����ֵΪ��{}���Ķ���",target);
} else {
result = "�л����ھ���ɹ����ҵ����ֵΪ��" + target + "���Ķ���";
LogUtil.APP.info("�л����ھ���ɹ����ҵ����ֵΪ��{}���Ķ���",target);
}
return result;
} catch (TimeoutException e) {
result = "����ִ��ʧ�ܣ��л����ھ��ʧ�ܣ��ȴ���ʱ��δ�ҵ����ֵΪ��" + target + "���Ķ���";
LogUtil.APP.error("�л����ھ��ʧ�ܣ��ȴ���ʱ��δ�ҵ����ֵΪ��{}���Ķ���",target,e);
return result;
}
}
/**
* wait Until Element Not Present
*
* @param locator By
* @param timeout long
* @param pollingTime long
*/
@Deprecated
public static void waitUntilElementNotPresent(final By locator, final long timeout, final long pollingTime) {
LOGGER.info(String.format("Wait until element %s disappear", locator.toString()));
WebDriver driver = getDriver();
try {
if (new WebDriverWait(driver, timeout, pollingTime).until(ExpectedConditions.invisibilityOfElementLocated(locator))) {
LOGGER.info(String.format("Element located by: %s not present.", locator.toString()));
} else {
LOGGER.info(String.format("Element located by: %s is still present.", locator.toString()));
}
} catch (TimeoutException e) {
LOGGER.debug(e.getMessage());
LOGGER.info(String.format("Element located by: %s is still present.", locator.toString()));
}
}
@SuppressWarnings("unchecked")
private static boolean urlCheck(ExpectedCondition condition, boolean secondTry) {
WebDriver driver = getCurrentDriver();
try {
(new WebDriverWait(driver, 5, 100)).until(condition);
}
catch (TimeoutException e) {
if (driver instanceof InternetExplorerDriver && !secondTry) {
// IE WebDriver has sometimes invalid current URL
log.info("IE workaround: checking URL failed at first attempt - refreshing the page and trying one more time...");
driver.navigate().refresh();
urlCheck(condition, true);
}
else {
return false;
}
}
return true;
}
/**
* @param buttonText
* @return message
* @author wasiq.bhamla
* @since 09-May-2017 9:14:16 PM
*/
public String handlePermissionAlert(final String buttonText) {
return getValue("Handling Android Permission Alert pop-up...", d -> {
try {
final PermissionActivity perm = new PermissionActivity(this.device);
final String description = perm.onElement("Message")
.text();
LOG.trace("Alert Text: {}", description);
perm.onElement(buttonText)
.tap();
return description;
} catch (final TimeoutException e) {
LOG.warn("Expected Alert not displayed...");
LOG.warn(e.getMessage());
}
return null;
});
}
@Test
public void internalError_showNotification_clickEsc_refresh() {
clickButton(UPDATE);
clickButton("cause-exception");
Assert.assertTrue("The page should not be immediately refreshed after "
+ "a server-side exception", isMessageUpdated());
Assert.assertTrue(
"'Internal error' notification should be present after "
+ "a server-side exception",
isInternalErrorNotificationPresent());
new Actions(getDriver()).sendKeys(Keys.ESCAPE).build().perform();
try {
waitUntil(driver -> !isMessageUpdated());
} catch (TimeoutException e) {
Assert.fail(
"After internal error, pressing esc-key should refresh the page, "
+ "resetting the state of the UI.");
}
Assert.assertFalse(
"'Internal error' notification should be gone after refreshing",
isInternalErrorNotificationPresent());
}
private <T extends PageObject> void waitOnPageObjectListsVisibility(T pageInstance, Field field) {
PageObjectList<PageObject> list = getPageObjectListFromOf(field, pageInstance);
int expected = field.getAnnotation(Visible.class).value();
int actual = 0;
for (PageObject pageObject : list) {
try {
Waits.waitUntil(pageObject, is(visible()));
actual++;
} catch (TimeoutException e) {
// ignore timeout for present but not visible objects
logger.debug("page object {} of list wasn't visible within the timeout - ignoring");
}
}
if (actual != expected) {
String message = "Expected %s elements of page object list (%s) to be visible, but there were %s.";
throw new IllegalStateException(String.format(message, expected, field, actual));
}
}
protected void logoutFromRealm(String contextRoot, String realm, String initiatingIdp, String tokenHint) {
driver.navigate().to(contextRoot
+ "/auth/realms/" + realm
+ "/protocol/" + "openid-connect"
+ "/logout?redirect_uri=" + encodeUrl(getAccountUrl(contextRoot, realm))
+ (!StringUtils.isBlank(initiatingIdp) ? "&initiating_idp=" + initiatingIdp : "")
+ (!StringUtils.isBlank(tokenHint) ? "&id_token_hint=" + tokenHint : "")
);
try {
Retry.execute(() -> {
try {
waitForPage(driver, "log in to " + realm, true);
} catch (TimeoutException ex) {
driver.navigate().refresh();
log.debug("[Retriable] Timed out waiting for login page");
throw ex;
}
}, 10, 100);
} catch (TimeoutException e) {
log.debug(driver.getTitle());
log.debug(driver.getPageSource());
Assert.fail("Timeout while waiting for login page");
}
}
@Test
public void shouldIncludeRemoteInfoForWrappedDriverTimeout() throws IOException {
Capabilities caps = new MutableCapabilities();
Response response = new Response(new SessionId("foo"));
response.setValue(caps.asMap());
CommandExecutor executor = mock(CommandExecutor.class);
when(executor.execute(any(Command.class))).thenReturn(response);
RemoteWebDriver driver = new RemoteWebDriver(executor, caps);
WebDriver testDriver = mock(WebDriver.class, withSettings().extraInterfaces(WrapsDriver.class));
when(((WrapsDriver) testDriver).getWrappedDriver()).thenReturn(driver);
TickingClock clock = new TickingClock();
WebDriverWait wait =
new WebDriverWait(testDriver, Duration.ofSeconds(1), Duration.ofMillis(200), clock, clock);
assertThatExceptionOfType(TimeoutException.class)
.isThrownBy(() -> wait.until(d -> false))
.withMessageContaining("Capabilities {javascriptEnabled: true, platform: ANY, platformName: ANY}")
.withMessageContaining("Session ID: foo");
}
@Before
public void setUp() {
findService = (BIFindService)getApplication().findService();
savedSearchService = getApplication().savedSearchService();
elementFactory = (BIIdolFindElementFactory)getElementFactory();
findPage = elementFactory.getFindPage();
findService.searchAnyView("careful now");
try {
findPage = elementFactory.getFindPage();
findPage.waitUntilSearchTabsLoaded();
savedSearchService.deleteAll();
elementFactory.getConceptsPanel().removeAllConcepts();
} catch(final TimeoutException ignored) {
//no-op
}
elementFactory.getTopicMap().waitForMapLoaded();
}
@Test
@ResolvedBug("FIND-228")
public void testCompareUnsavedSearches() {
findService.searchAnyView("\"not many results\"");
savedSearchService.openNewTab();
findService.searchAnyView("\"to speed up comparison\"");
final ComparisonModal modal = findPage.openCompareModal();
modal.select("New Search");
modal.compareButton().click();
Exception thrown = null;
try {
// server appears to cancel comparison request after 90s
modal.waitForComparisonToLoad(100);
} catch(final TimeoutException e) {
thrown = e;
}
assertThat(thrown, nullValue());
findPage.goBackToSearch();
}
private void doTest(final String subContext, Transport transport, boolean pushMustWork) throws InterruptedException {
String url = getRootURL() + "/custom-context-router/" + subContext;
if (transport != null) {
url += "?transport=" + transport.getIdentifier();
}
getDriver().get(url);
waitForDevServer();
findElement(By.id(DependencyLayout.RUN_PUSH_ID)).click();
WebElement signal = findElement(By.id(DependencyLayout.PUSH_SIGNAL_ID));
String sampleText = pushMustWork ? DependencyLayout.PUSH_WORKS_TEXT : DependencyLayout.NO_PUSH_YET_TEXT;
try {
waitUntil(driver -> signal.getText().equals(sampleText), 2);
} catch (TimeoutException e) {
Assert.fail("Push state check failed when waiting for '"
+ sampleText + "' in element #"
+ DependencyLayout.PUSH_SIGNAL_ID);
}
}
@Test
public void callsDeprecatedHandlerForRuntimeExceptions() {
final TimeoutException exception = new TimeoutException();
when(mockClock.instant()).thenReturn(EPOCH, EPOCH.plusMillis(2500));
when(mockCondition.apply(mockDriver)).thenThrow(exception);
final TestException sentinelException = new TestException();
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(mockDriver, mockClock, mockSleeper) {
@Override
protected RuntimeException timeoutException(String message, Throwable lastException) {
throw sentinelException;
}
};
wait.withTimeout(Duration.ofMillis(0))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(TimeoutException.class);
assertThatExceptionOfType(TestException.class)
.isThrownBy(() -> wait.until(mockCondition))
.satisfies(expected -> assertThat(sentinelException).isSameAs(expected));
}
@Test
public void timeoutWhenConditionMakesNoProgress() {
when(mockClock.instant()).thenReturn(EPOCH, EPOCH.plusMillis(2500));
when(mockCondition.apply(mockDriver)).then(invocation -> {
while (true) {
// it gets into an endless loop and makes no progress.
}
});
FluentWait<WebDriver> wait = new FluentWait<>(mockDriver, mockClock, mockSleeper)
.withTimeout(Duration.ofSeconds(0))
.pollingEvery(Duration.ofSeconds(2));
assertThatExceptionOfType(org.openqa.selenium.TimeoutException.class)
.isThrownBy(() -> wait.until(mockCondition))
.satisfies(actual -> assertThat(actual.getMessage()).startsWith("Supplied function might have stalled"));
}
/**
* Waits for DOMContent to load
*/
public static void waitForDomContentToLoad() {
WebDriver driver = getCurrentDriver();
if (driver instanceof HtmlUnitDriver) {
return; // not needed
}
WebDriverWait wait = new WebDriverWait(driver, PAGELOAD_TIMEOUT_MILLIS / 1000);
try {
wait
.pollingEvery(Duration.ofMillis(500))
.until(javaScriptThrowsNoExceptions(
"if (document.readyState !== 'complete') { throw \"Not ready\";}"));
} catch (TimeoutException e) {
log.warn("waitForPageToLoad time exceeded!");
}
}
@Test
public void waitingForCssAttributeToBeEqualForWebElementThrowsTimeoutExceptionWhenAttributeIsNotEqual() {
String attributeName = "attributeName";
when(mockElement.getAttribute(attributeName)).thenReturn("");
when(mockElement.getCssValue(attributeName)).thenReturn("");
assertThatExceptionOfType(TimeoutException.class)
.isThrownBy(() -> wait.until(attributeToBe(mockElement, attributeName, "test")));
}
@Override
public void navigateTo(String url)
{
LOGGER.info("Loading: {}", url);
try
{
getWebDriver().navigate().to(url);
}
catch (TimeoutException ex)
{
handleTimeoutException(ex);
}
}
@SuppressWarnings("checkstyle:IllegalCatchExtended")
private void handleTimeoutException(TimeoutException exception)
{
softAssert.recordFailedAssertion(exception);
try
{
javascriptActions.executeScript("window.stop()");
}
catch (Exception e)
{
LOGGER.error("Unable to stop resource loading", e);
}
}
@Test
void testWaitWith4ParametersFailWithTimeoutException()
{
when(wait.toString()).thenReturn(MOCKED_WAIT_DESCRIPTION);
when(waitFactory.createWait(searchContext, TIMEOUT_SECONDS)).thenReturn(wait);
mockException(TimeoutException.class);
waitActions.wait(searchContext, TIMEOUT_SECONDS, isTrue);
verifyFailureRecording();
}
public boolean isSshKeyIsPresent(String host) {
try {
seleniumWebDriverHelper.waitPresence(By.xpath(Locators.SSH_KEYS_TABLE), ELEMENT_TIMEOUT_SEC);
return sshKeysTable.getText().contains(host);
} catch (TimeoutException e) {
return false;
}
}
@Test
void testWaitWith5ParametersFailWithTimeoutExceptionAndDoNotRecordAssertionFailure()
{
when(waitFactory.createWait(searchContext, TIMEOUT_SECONDS, TIMEOUT_MILLIS)).thenReturn(wait);
mockException(TimeoutException.class);
waitActions.wait(searchContext, TIMEOUT_SECONDS, TIMEOUT_MILLIS, isTrue, false);
verifyNoInteractions(softAssert);
}
@Test
public void checksTimeoutAfterConditionSoZeroTimeoutWaitsCanSucceed() {
when(mockClock.instant()).thenReturn(EPOCH, EPOCH.plusMillis(250));
when(mockCondition.apply(mockDriver)).thenReturn(null);
Wait<WebDriver> wait = new FluentWait<>(mockDriver, mockClock, mockSleeper)
.withTimeout(Duration.ofMillis(0));
assertThatExceptionOfType(TimeoutException.class)
.isThrownBy(() -> wait.until(mockCondition))
.withNoCause();
}
@Test
public void waitingForAllExpectedConditionsToHavePositiveResultWhenFirstFailed() {
String attributeName = "test";
when(mockElement.getText()).thenReturn("");
when(mockElement.getCssValue(attributeName)).thenReturn(attributeName);
when(mockElement.getAttribute(attributeName)).thenReturn(attributeName);
assertThatExceptionOfType(TimeoutException.class)
.isThrownBy(() -> wait.until(and(textToBePresentInElement(mockElement, "test"),
attributeToBe(mockElement, attributeName, attributeName))));
}
public void assertTrue(ExpectedCondition expectedCondition) {
try {
waitFor(expectedCondition);
} catch (TimeoutException e) {
throw new AssertionError(e);
}
}
/**
* sets the driver's cookies up based on the requestHeaders set
*/
private void setDriverCookies(){
// You can't set cookies until you have the domain set in the DOM, this is a fix for that
try {
driver.get(url);
}
catch (TimeoutException e){
System.err.println("[" + url + "][-] - timeout when connecting.");
}
// Set the driver's cookies based on the headers, if there are any
if (requestHeaders != null){
for (String header: requestHeaders){
if (header.startsWith("Cookie: ")){
// This is a cookie header, split it up
String cookieString = header.substring(8,header.length());
for (String kvPair : cookieString.split(";")){
String key = kvPair.split("=")[0].trim();
String value = kvPair.split("=")[1].trim();
Cookie cookieObj = new Cookie(key, value);
try {
driver.manage().addCookie(cookieObj);
}
catch (org.openqa.selenium.UnableToSetCookieException d){
System.err.println("[JS-SRI][-] Could not set cookie for key " + key + " and value " + value);
}
}
}
}
}
}
@Test(expected = TimeoutException.class)
public void testGenericWaitUntil_BadCase() {
try {
when(supplier.get()).thenReturn(false);
Waits.waitUntil(50, TimeUnit.MILLISECONDS, 25, supplier);
} finally {
verify(supplier, atMost(2)).get();
}
}
@SneakyThrows
public void loginSuccessfully(UserData userData) {
login(userData);
try {
synchWait().until((page) -> !isOnPage());
} catch (TimeoutException e) {
throw new Exception("login was unsuccessful; found error message: " + error.getText());
}
}
/**
* Waits until the expectations are full filled or timeout runs out
*
* @param condition The conditions the element should meet
* @param timeout The timeout to wait
* @return True if element meets the condition
*/
public boolean waitForExpectedCondition(ExpectedCondition<?> condition, int timeout) {
WebDriver driver = getWebDriver();
boolean conditionMet = true;
try {
new WebDriverWait(driver, timeout).until(condition);
} catch (TimeoutException e) {
conditionMet = false;
}
return conditionMet;
}
/**
* Returns a 'wait' proxy that determines if this page component is visible
*
* @return page component if visible; otherwise 'null'
*/
public static Coordinator<PageComponent> componentIsVisible() {
return new Coordinator<PageComponent>() {
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("squid:S1774")
public PageComponent apply(final SearchContext context) {
PageComponent component = verifyContext(context);
return (component.isDisplayed()) ? component : null;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "page component to be visible";
}
/**
* {@inheritDoc}
*/
@Override
public TimeoutException differentiateTimeout(TimeoutException e) {
return new ComponentStillInvisibleTimeoutException(e.getMessage(), e.getCause());
}
};
}
/**
* Returns a 'wait' proxy that determines if this page component is hidden
*
* @return page component if hidden; otherwise 'null'
*/
public static Coordinator<PageComponent> componentIsHidden() {
return new Coordinator<PageComponent>() {
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("squid:S1774")
public PageComponent apply(final SearchContext context) {
PageComponent component = verifyContext(context);
return (component.isInvisible()) ? component : null;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "page component to be absent or hidden";
}
/**
* {@inheritDoc}
*/
@Override
public TimeoutException differentiateTimeout(TimeoutException e) {
return new ComponentStillDisplayedTimeoutException(e.getMessage(), e.getCause());
}
};
}