org.openqa.selenium.TimeoutException Java Examples

The following examples show how to use org.openqa.selenium.TimeoutException. 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: DefaultPageObjectFactory.java    From webtester-core with Apache License 2.0 6 votes vote down vote up
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));
        }

    }
 
Example #2
Source File: URLUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: AbstractBaseBrokerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #4
Source File: WebDriverWaitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #5
Source File: AndroidDeviceActions.java    From coteafs-appium with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
    });
}
 
Example #6
Source File: AndroidUtils.java    From carina with Apache License 2.0 6 votes vote down vote up
/**
 * 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()));
    }
}
 
Example #7
Source File: ResultsComparisonITCase.java    From find with MIT License 6 votes vote down vote up
@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();
}
 
Example #8
Source File: ListResultsComparisonITCase.java    From find with MIT License 6 votes vote down vote up
@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();
}
 
Example #9
Source File: PushIT.java    From flow with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #10
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example #11
Source File: FluentWaitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #12
Source File: FluentWaitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #13
Source File: InternalErrorIT.java    From flow with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #14
Source File: WaitUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * 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!");
    }
}
 
Example #15
Source File: NavigateActions.java    From vividus with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #16
Source File: ExpectedConditionsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void waitingForAllExpectedConditionsToHavePositiveResultWhenAllFailed() {
  String attributeName = "test";
  when(mockElement.getText()).thenReturn("");
  when(mockElement.getCssValue(attributeName)).thenReturn("");
  when(mockElement.getAttribute(attributeName)).thenReturn("");

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(and(textToBePresentInElement(mockElement, "test"),
                                   attributeToBe(mockElement, attributeName, "test"))));
}
 
Example #17
Source File: ExpectedConditionsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void waitingElementSelectionStateToBeThrowsTimeoutExceptionWhenStateDontMatch() {
  when(mockClock.instant()).thenReturn(Instant.now(), Instant.now().plusMillis(2000));
  when(mockElement.isSelected()).thenReturn(true);

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(elementSelectionStateToBe(mockElement, false)));
}
 
Example #18
Source File: WebDriverService.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private AnswerItem<WebElement> getSeleniumElement(Session session, Identifier identifier, boolean visible, boolean clickable) {
    AnswerItem<WebElement> answer = new AnswerItem<>();
    MessageEvent msg;
    By locator = this.getBy(identifier);
    LOG.debug("Waiting for Element : " + identifier.getIdentifier() + "=" + identifier.getLocator());
    try {
        WebDriverWait wait = new WebDriverWait(session.getDriver(), TimeUnit.MILLISECONDS.toSeconds(session.getCerberus_selenium_wait_element()));
        WebElement element;
        if (visible) {
            if (session.isCerberus_selenium_autoscroll()) {
                element = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
                scrollElement(session, element);
            }
            if (clickable) {
                element = wait.until(ExpectedConditions.elementToBeClickable(locator));
            } else {
                element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
            }
        } else {
            element = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
        }
        answer.setItem(element);
        msg = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_WAIT_ELEMENT);
        msg.setDescription(msg.getDescription().replace("%ELEMENT%", identifier.getIdentifier() + "=" + identifier.getLocator()));
    } catch (TimeoutException exception) {
        LOG.warn("Exception waiting for element :" + exception);
        //throw new NoSuchElementException(identifier.getIdentifier() + "=" + identifier.getLocator());
        msg = new MessageEvent(MessageEventEnum.ACTION_FAILED_WAIT_NO_SUCH_ELEMENT);
        msg.setDescription(msg.getDescription().replace("%ELEMENT%", identifier.getIdentifier() + "=" + identifier.getLocator()));
    }
    answer.setResultMessage(msg);
    return answer;
}
 
Example #19
Source File: SeleniumWebDriverHelper.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Performs and verifies action.
 *
 * @param perform perform action
 * @param verify verification action
 * @param rollback rollback action
 */
public void performAndVerify(
    UnaryOperator<Void> perform, UnaryOperator<Void> verify, UnaryOperator<Void> rollback) {
  for (; ; ) {
    perform.apply(null);

    try {
      verify.apply(null);
      break;
    } catch (TimeoutException e) {
      rollback.apply(null);
    }
  }
}
 
Example #20
Source File: ProfilePage.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public boolean isGetStartedButtonPresent() {
  try {
    new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
        .until(ExpectedConditions.visibilityOf(getStartedButton));
    return true;
  } catch (TimeoutException e) {
    return false;
  }
}
 
Example #21
Source File: WorkspacesListTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void checkSearchField() throws Exception {
  int nameLength = workspaceName.length();
  int existingWorkspacesCount = testWorkspaceServiceClient.getWorkspacesCount();
  String sequenceForSearch = workspaceName.substring(nameLength - 5, nameLength);

  workspaces.waitVisibleWorkspacesCount(existingWorkspacesCount);
  workspaces.typeToSearchInput(sequenceForSearch);

  try {
    workspaces.waitVisibleWorkspacesCount(EXPECTED_SEARCHED_WORKSPACES_COUNT);
  } catch (TimeoutException ex) {
    // remove try-catch block after issue has been resolved
    fail("Known permanent failure https://github.com/eclipse/che/issues/13950");
  }

  List<Workspaces.WorkspaceListItem> items = workspaces.getVisibleWorkspaces();
  assertEquals(items.get(0).getWorkspaceName(), workspaceName);

  // check displaying list size
  workspaces.typeToSearchInput("");
  workspaces.waitVisibleWorkspacesCount(testWorkspaceServiceClient.getWorkspacesCount());

  workspaces.waitWorkspaceIsPresent(workspaceName);
  Assert.assertEquals(workspaces.getWorkspaceProjectsValue(workspaceName), "1");
  workspaces.waitWorkspaceIsPresent(workspaceName1);
  Assert.assertEquals(workspaces.getWorkspaceProjectsValue(workspaceName), "1");
}
 
Example #22
Source File: LoginAndCreateOnpremAccountPage.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean isOpened() {
  try {
    waitLoginPage();
    return true;
  } catch (TimeoutException ex) {
    return false;
  }
}
 
Example #23
Source File: TheiaIde.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public void waitTheiaIde() {
  try {
    seleniumWebDriverHelper.waitVisibility(theiaIde, PREPARING_WS_TIMEOUT_SEC);
  } catch (TimeoutException ex) {
    switchToIdeFrame();
    seleniumWebDriverHelper.waitVisibility(theiaIde, PREPARING_WS_TIMEOUT_SEC);
  }
}
 
Example #24
Source File: UIUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean doesElementClassContain(WebElement element, String value) {
    try {
        waitUntilElementClassContains(element, value);
    }
    catch (TimeoutException e) {
        return false;
    }
    return true;
}
 
Example #25
Source File: ExpectedConditionsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void waitingForTextToBeEqualForElementLocatedThrowsTimeoutExceptionWhenTextIsNotEqual() {
  String testSelector = "testSelector";
  when(mockDriver.findElement(By.cssSelector(testSelector))).thenReturn(mockElement);
  when(mockElement.getText()).thenReturn("");

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(textToBe(By.cssSelector(testSelector), "test")));
}
 
Example #26
Source File: ExpectedConditionsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void waitingForVisibilityOfAllElementsThrowsTimeoutExceptionWhenElementNotDisplayed() {
  List<WebElement> webElements = singletonList(mockElement);
  when(mockElement.isDisplayed()).thenReturn(false);

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(visibilityOfAllElements(webElements)));
}
 
Example #27
Source File: WaitStepDefinitions.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Waits the given amount of time for an element with the supplied attribute and attribute value to be displayed
 * (i.e. to be visible) on the page.
 *
 * @param waitDuration    The maximum amount of time to wait for
 * @param attribute       The attribute to use to select the element with
 * @param alias           If this word is found in the step, it means the selectorValue is found from the
 *                        data set.
 * @param selectorValue   The value used in conjunction with the selector to match the element. If alias
 *                        was set, this value is found from the data set. Otherwise it is a literal value.
 * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be present
 */
@When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with (?:a|an|the) attribute of \"([^\"]*)\" "
	+ "equal to( alias)? \"([^\"]*)\" to be present(,? ignoring timeouts?)?")
public void presentAttrWait(
	final String waitDuration,
	final String attribute,
	final String alias,
	final String selectorValue,
	final String ignoringTimeout) {

	final String attributeValue = autoAliasUtils.getValue(
		selectorValue, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());

	try {
		final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
		final WebDriverWait wait = new WebDriverWait(
			webDriver,
			Integer.parseInt(waitDuration),
			Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
		wait.until(ExpectedConditions.presenceOfElementLocated(
			By.cssSelector("[" + attribute + "='" + attributeValue + "']")));
	} catch (final TimeoutException ex) {
		/*
			Rethrow if we have not ignored errors
		 */
		if (StringUtils.isBlank(ignoringTimeout)) {
			throw ex;
		}
	}
}
 
Example #28
Source File: WaitStepDefinitions.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Waits the given amount of time for an element with the supplied attribute and attribute value to be displayed
 * (i.e. to be visible) on the page.
 *
 * @param waitDuration    The maximum amount of time to wait for
 * @param attribute       The attribute to use to select the element with
 * @param alias           If this word is found in the step, it means the selectorValue is found from the
 *                        data set.
 * @param selectorValue   The value used in conjunction with the selector to match the element. If alias
 *                        was set, this value is found from the data set. Otherwise it is a literal value.
 * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be present
 */
@When("^I wait \"(\\d+)\" seconds for (?:a|an|the) element with (?:a|an|the) attribute of \"([^\"]*)\" "
	+ "equal to( alias)? \"([^\"]*)\" to not be displayed(,? ignoring timeouts?)?")
public void notDisplayAttrWait(
	final String waitDuration,
	final String attribute,
	final String alias,
	final String selectorValue,
	final String ignoringTimeout) {

	final String attributeValue = autoAliasUtils.getValue(
		selectorValue, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());

	try {
		final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
		final WebDriverWait wait = new WebDriverWait(
			webDriver,
			Integer.parseInt(waitDuration),
			Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
		final boolean result = wait.until(
			ExpectedConditions.not(ExpectedConditions.visibilityOfAllElementsLocatedBy(
				By.cssSelector("[" + attribute + "='" + attributeValue + "']"))));
		if (!result) {
			throw new TimeoutException(
				"Gave up after waiting " + Integer.parseInt(waitDuration)
					+ " seconds for the element to not be displayed");
		}
	} catch (final TimeoutException ex) {
		/*
			Rethrow if we have not ignored errors
		 */
		if (StringUtils.isBlank(ignoringTimeout)) {
			throw ex;
		}
	}
}
 
Example #29
Source File: ExpectedConditionsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@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")));
}
 
Example #30
Source File: WaitStepDefinitions.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Waits the given amount of time for a link with the supplied text to be placed in the DOM. Note that the
 * element does not have to be visible just present in the HTML.
 *
 * @param waitDuration    The maximum amount of time to wait for
 * @param alias           If this word is found in the step, it means the linkContent is found from the
 *                        data set.
 * @param linkContent     The text content of the link we are wait for
 * @param ignoringTimeout The presence of this text indicates that timeouts are ignored
 */
@When("^I wait \"(\\d+)\" seconds for a link with the text content of"
	+ "( alias)? \"([^\"]*)\" to not be present(,? ignoring timeouts?)?")
public void notPresentLinkStep(
	final String waitDuration,
	final String alias,
	final String linkContent,
	final String ignoringTimeout) {

	try {
		final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
		final String content = autoAliasUtils.getValue(
			linkContent, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());
		final WebDriverWait wait = new WebDriverWait(
			webDriver,
			Integer.parseInt(waitDuration),
			Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
		final boolean result = wait.until(
			ExpectedConditions.not(
				ExpectedConditions.presenceOfAllElementsLocatedBy(By.linkText(content))));

		if (!result) {
			throw new TimeoutException(
				"Gave up after waiting " + Integer.parseInt(waitDuration)
					+ " seconds for the element to not be present");
		}
	} catch (final TimeoutException ex) {
			/*
				Rethrow if we have not ignored errors
			 */
		if (StringUtils.isBlank(ignoringTimeout)) {
			throw ex;
		}
	}
}