类org.openqa.selenium.StaleElementReferenceException源码实例Demo

下面列出了怎么用org.openqa.selenium.StaleElementReferenceException的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public void mark(WebElement ele, File file) throws IOException
{
	BufferedImage bufImg = ImageIO.read(file);
	
	try
	{
		WebElement webEle = (WebElement) ele;
		Point loc = webEle.getLocation();
		Dimension size = webEle.getSize();
		
		Graphics2D g = bufImg.createGraphics();
		g.setColor(Color.red);
		g.drawRect(loc.getX(), loc.getY(), size.getWidth(), size.getHeight());
	}
	catch(StaleElementReferenceException se)
	{
	}
}
 
源代码2 项目: vividus   文件: AbstractElementSearchAction.java
private List<WebElement> filterElementsByVisibility(List<WebElement> elements, boolean visible,
        boolean retry)
{
    return elements.stream().filter(element -> {
        try
        {
            return visible == isElementVisible(element, false);
        }
        catch (StaleElementReferenceException e)
        {
            if (retrySearchIfStale && !retry)
            {
                throw e;
            }
            LOGGER.warn(e.getMessage(), e);
            return false;
        }
    }).collect(Collectors.toList());
}
 
源代码3 项目: hifive-pitalium   文件: FrameWebElementTest.java
/**
 * Frameにスイッチするテスト
 */
@Test
public void executeInFrame_inFrameElement() throws Exception {
	PtlWebElement iframe = (PtlWebElement) driver.findElementByClassName("content");
	driver.switchTo().frame(iframe);
	PtlWebElement left = (PtlWebElement) driver.findElementByClassName("content-left");
	driver.switchTo().defaultContent();

	try {
		left.getTagName();
		fail();
	} catch (StaleElementReferenceException e) {
		//
	}

	left.setFrameParent(iframe);
	assertThat(left.getTagName(), is("div"));
}
 
源代码4 项目: vividus   文件: ElementSearchActionTests.java
@ParameterizedTest
@MethodSource("provideStaleElementTestData")
void testStaleElementSearchRetry(Answer<Boolean> answer, int expectedSize,
        int isDisplayedMethodInvocations)
{
    elementSearchAction.setRetrySearchIfStale(true);
    WebElement element = mock(WebElement.class);
    List<WebElement> elements = List.of(element);
    Mockito.doThrow(new StaleElementReferenceException(EXCEPTION)).doAnswer(answer)
            .when(element).isDisplayed();
    when(searchContext.findElements(locator)).thenReturn(elements);
    List<WebElement> foundElements = elementSearchAction
            .findElements(searchContext, locator, new SearchParameters().setWaitForElement(false));
    assertEquals(expectedSize, foundElements.size());
    verify(element, Mockito.never()).getSize();
    verifyNoInteractions(waitActions);
    verify(element, times(isDisplayedMethodInvocations)).isDisplayed();
    assertThat(logger.getLoggingEvents().get(0), equalTo(info(TOTAL_NUMBER_OF_ELEMENTS, locator, 1)));
}
 
源代码5 项目: webtau   文件: GenericPageElement.java
static private void repeatForStaleElement(Runnable code) {
    int numberOfAttemptsLeft = getCfg().getStaleElementRetry();

    for (; numberOfAttemptsLeft >= 1; numberOfAttemptsLeft--) {
        try {
            code.run();
            break;
        } catch (StaleElementReferenceException e) {
            if (numberOfAttemptsLeft == 1) {
                throw new RuntimeException("element is stale, " +
                        "consider using waitTo beVisible matcher to make sure component fully appeared");
            }

            sleep(getCfg().getStaleElementRetryWait());
        }
    }
}
 
源代码6 项目: qaf   文件: QAFExtendedWebElement.java
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void onFailure(QAFExtendedWebElement element, CommandTracker commandTracker) {
	commandTracker.setStage(Stage.executingOnFailure);
	commandTracker.setEndTime(System.currentTimeMillis());

	if (commandTracker.getException() instanceof StaleElementReferenceException) {
		logger.warn(commandTracker.getException().getMessage());
		element.setId("-1");
		Map parameters = commandTracker.getParameters();
		parameters.put("id", element.getId());
		commandTracker.setException(null);
		commandTracker.setStage(Stage.executingMethod);
		Response response = element.execute(commandTracker.command, parameters);
		commandTracker.setEndTime(System.currentTimeMillis());
		commandTracker.setResponce(response);
	}
	for (QAFWebElementCommandListener listener : listners) {
		// whether handled previous listener
		if (!commandTracker.hasException()) {
			break;
		}
		logger.debug("Executing listener " + listener.getClass().getName());
		listener.onFailure(element, commandTracker);
	}
}
 
源代码7 项目: che   文件: CodenvyEditor.java
private void waitForText(String expectedText, int timeout, Supplier<String> textProvider) {
  String[] result = new String[1];
  webDriverWaitFactory
      .get(timeout)
      .ignoring(StaleElementReferenceException.class)
      .withMessage(
          () ->
              "Timeout waiting for txt, expected= '"
                  + expectedText
                  + "', actual='"
                  + result[0]
                  + "'")
      .until(
          (ExpectedCondition<Boolean>)
              driver -> {
                result[0] = textProvider.get();
                return result[0].contains(expectedText);
              });
}
 
源代码8 项目: vividus   文件: ExpectedSearchContextConditions.java
private <E> E searchInforming(Supplier<E> search)
{
    try
    {
        return search.get();
    }
    catch (StaleElementReferenceException toWrap)
    {
        throw new StaleContextException(toWrap);
    }
}
 
源代码9 项目: che   文件: FileStructure.java
/**
 * select a certain item in the 'file structure' form
 *
 * @param item is the name of the item
 */
public void selectItemInFileStructure(String item) {
  // we need to wait a little to avoid quick clicking on nodes
  WaitUtils.sleepQuietly(1);

  seleniumWebDriverHelper.waitNoExceptions(
      () -> selectItem(item), StaleElementReferenceException.class);
}
 
源代码10 项目: vividus   文件: AbstractExpectedConditions.java
/**
 * An expectation for checking if the given text is present in the found element.
 * @param searchCriteria used to find elements
 * @param text to be present in the found element
 * @return true once the first element located with searchAttributes contains the given text.
 * Null if StaleElementReferenceException caught.
 */
@Override
public IExpectedSearchContextCondition<Boolean> textToBePresentInElementLocated(final T searchCriteria,
        final String text)
{
    return new IExpectedSearchContextCondition<>()
    {
        @Override
        @SuppressWarnings("checkstyle:returnnullinsteadofboolean")
        @SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
        public Boolean apply(SearchContext searchContext)
        {
            try
            {
                WebElement element = findElement(searchContext, searchCriteria);
                return element.getText().contains(text);
            }
            catch (StaleElementReferenceException e)
            {
                return null;
            }
        }

        @Override
        public String toString()
        {
            return String.format("text ('%s') to be present in element %s", text,
                    toStringParameters(searchCriteria));
        }
    };
}
 
源代码11 项目: vividus   文件: AbstractExpectedConditions.java
/**
 * An expectation for checking that all found elements present within the search context are
 * visible. Visibility means that elements are not
 * only displayed but also have a height and width that is greater than 0.
 * @param searchCriteria used to find elements
 * @return the list of WebElements once they are located
 */
@Override
@SuppressWarnings("checkstyle:nonullforcollectionreturn")
public IExpectedSearchContextCondition<List<WebElement>> visibilityOfAllElementsLocatedBy(final T searchCriteria)
{
    return new IExpectedSearchContextCondition<>()
    {
        @Override
        public List<WebElement> apply(SearchContext searchContext)
        {
            List<WebElement> elements = findElements(searchContext, searchCriteria);
            for (Iterator<WebElement> iterator = elements.iterator(); iterator.hasNext();)
            {
                try
                {
                    if (!iterator.next().isDisplayed())
                    {
                        return null;
                    }
                }
                catch (StaleElementReferenceException e)
                {
                    iterator.remove();
                }
            }
            return !elements.isEmpty() ? elements : null;
        }

        @Override
        public String toString()
        {
            return "visibility of all elements " + toStringParameters(searchCriteria);
        }
    };
}
 
源代码12 项目: 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());
}
 
源代码13 项目: vividus   文件: AbstractExpectedConditions.java
/**
 * An expectation for checking an element is visible and enabled such that you
 * can click it.
 * @param searchCriteria used to find elements
 * @return the WebElement once it is located and clickable (visible and enabled).
 * Null if StaleElementReferenceException caught.
 */
@Override
public IExpectedSearchContextCondition<WebElement> elementToBeClickable(final T searchCriteria)
{
    return new IExpectedSearchContextCondition<>()
    {
        private final IExpectedSearchContextCondition<WebElement> visibilityOfElementLocated = visibilityOfElement(
                searchCriteria);

        @Override
        public WebElement apply(SearchContext searchContext)
        {
            WebElement element = visibilityOfElementLocated.apply(searchContext);
            try
            {
                return element != null && element.isEnabled() ? element : null;
            }
            catch (StaleElementReferenceException e)
            {
                return null;
            }
        }

        @Override
        public String toString()
        {
            return "element to be clickable: " + toStringParameters(searchCriteria);
        }
    };
}
 
源代码14 项目: vividus   文件: AbstractExpectedConditions.java
/**
 * An expectation for checking an element selection state
 * @param searchCriteria used to find elements
 * @param selected state to verify
 * @return true if element state matches verifiable state false otherwise.
 * Null if StaleElementReferenceException caught.
 */
@Override
public IExpectedSearchContextCondition<Boolean> elementSelectionStateToBe(final T searchCriteria,
        final boolean selected)
{
    return new IExpectedSearchContextCondition<>()
    {
        @Override
        @SuppressWarnings("checkstyle:returnnullinsteadofboolean")
        @SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
        public Boolean apply(SearchContext searchContext)
        {
            try
            {
                WebElement element = findElement(searchContext, searchCriteria);
                return element.isSelected() == selected;
            }
            catch (StaleElementReferenceException e)
            {
                return null;
            }
        }

        @Override
        public String toString()
        {
            return String.format("element %s to%s be selected", toStringParameters(searchCriteria),
                    selected ? "" : " not");
        }
    };
}
 
源代码15 项目: vividus   文件: WebElementHighlighterTests.java
@Test
void testEnableHighlightingStaleException()
{
    when(webUiContext.getAssertingWebElements()).thenReturn(List.of(webElement));
    SearchContext searchContext = mock(SearchContext.class);
    when(webUiContext.getSearchContext()).thenReturn(searchContext);
    StaleElementReferenceException exception = new StaleElementReferenceException("StaleElementReferenceException");
    when(javascriptActions.executeScript(ENABLE_HIGHLIGHT_SCRIPT, webElement)).thenThrow(exception);
    Object expected = new Object();
    Object actual = webElementHighlighter.takeScreenshotWithHighlights(() -> expected);
    assertEquals(expected, actual);
    verify(javascriptActions).executeScript(DISABLE_HIGHLIGHT_SCRIPT, webElement);
}
 
@Test
void testVisibilityOfAllElementsStaleElementException()
{
    List<WebElement> elements = new ArrayList<>();
    elements.add(webElement);
    when(searchActions.findElements(searchContext, searchAttributes)).thenReturn(elements);
    when(webElement.isDisplayed()).thenThrow(new StaleElementReferenceException(TEXT));
    IExpectedSearchContextCondition<List<WebElement>> condition = expectedSearchActionsConditions
            .visibilityOfAllElementsLocatedBy(searchAttributes);
    assertNull(condition.apply(searchContext));
}
 
@Test
void testVisibilityOfElementStaleElement()
{
    mockFindElements(webElement);
    when(webElement.isDisplayed()).thenThrow(new StaleElementReferenceException(TEXT));
    assertNull(expectedSearchActionsConditions.visibilityOfElement(searchAttributes).apply(searchContext));
}
 
@Test
void testElementToBeClickableStaleElement()
{
    mockIsDisplayed(true);
    when(webElement.isEnabled()).thenThrow(new StaleElementReferenceException(TEXT));
    assertNull(expectedSearchActionsConditions.elementToBeClickable(searchAttributes).apply(searchContext));
}
 
@Test
void testElementSelectionStateToBeStaleElement()
{
    mockFindElements(webElement);
    when(webElement.isSelected()).thenThrow(new StaleElementReferenceException(TEXT));
    assertNull(expectedSearchActionsConditions.elementSelectionStateToBe(searchAttributes, false)
            .apply(searchContext));
}
 
@Test
void testInvisibilityOfElementStaleElement()
{
    mockFindElements(webElement);
    when(webElement.isDisplayed()).thenThrow(new StaleElementReferenceException(TEXT));
    assertTrue(expectedSearchActionsConditions.invisibilityOfElement(searchAttributes).apply(searchContext)
            .booleanValue());
}
 
源代码21 项目: vividus   文件: WebElementActionsTests.java
@Test
void testTypeTextInStaleElement()
{
    Mockito.doReturn(false).when(webDriverManager).isTypeAnyOf(WebDriverType.SAFARI);
    Mockito.doReturn(webElement).when(baseValidations).assertIfElementExists(eq(ATTRIBUTES), eq(searchAttributes));
    Mockito.doThrow(StaleElementReferenceException.class).doNothing().when(webElement).sendKeys(TEXT);
    webElementActions.typeText(searchAttributes, TEXT);
    verify(webElement).clear();
    verify(webElement, times(2)).sendKeys(TEXT);
}
 
源代码22 项目: vividus   文件: ElementSearchActionTests.java
@Test
void testFindAllElementsWithException()
{
    WebElement element = mock(WebElement.class);
    List<WebElement> elements = List.of(element);
    Mockito.doThrow(new StaleElementReferenceException(EXCEPTION)).when(element).isDisplayed();
    when(searchContext.findElements(locator)).thenReturn(elements);
    List<WebElement> foundElements = elementSearchAction.findElements(searchContext, locator,
            new SearchParameters().setWaitForElement(false));
    assertEquals(0, foundElements.size());
    verify(element, Mockito.never()).getSize();
    verifyNoInteractions(waitActions);
    assertThat(logger.getLoggingEvents().get(0), equalTo(info(TOTAL_NUMBER_OF_ELEMENTS, locator, 1)));
}
 
源代码23 项目: vividus   文件: ElementSearchActionTests.java
private static Stream<Arguments> provideStaleElementTestData()
{
    Answer<Boolean> elementStale = invocation -> {
        throw new StaleElementReferenceException(EXCEPTION);
    };
    Answer<Boolean> elementDisplayed = invocation -> true;
    return Stream.of(Arguments.of(elementStale, 0, 2), Arguments.of(elementDisplayed, 1, 2));
}
 
@Test
void testTextToBePresentInElementLocatedSuccessException()
{
    SearchContext searchContext = mock(SearchContext.class);
    when(searchContext.findElement(XPATH_LOCATOR)).thenThrow(StaleElementReferenceException.class);
    assertNull(
            expectedConditions.textToBePresentInElementLocated(XPATH_LOCATOR, TEXT_TO_FIND).apply(searchContext));
}
 
@Test
void testVisibilityOfAllElementsLocatedBySuccessException()
{
    WebElement webElement1 = mock(WebElement.class);
    WebElement webElement2 = mock(WebElement.class);
    SearchContext searchContext = mock(SearchContext.class);
    mockFoundElements(webElement1, webElement2, searchContext);
    List<WebElement> expectedElements = new ArrayList<>();
    expectedElements.add(webElement1);
    when(webElement1.isDisplayed()).thenReturn(true);
    when(webElement2.isDisplayed()).thenThrow(StaleElementReferenceException.class);
    assertEquals(expectedElements,
            expectedConditions.visibilityOfAllElementsLocatedBy(XPATH_LOCATOR).apply(searchContext));
}
 
@Test
void testVisibilityOfElementLocatedNoElement()
{
    SearchContext searchContext = mock(SearchContext.class);
    when(searchContext.findElement(XPATH_LOCATOR)).thenThrow(StaleElementReferenceException.class);
    assertNull(expectedConditions.visibilityOfElement(XPATH_LOCATOR).apply(searchContext));
}
 
源代码27 项目: che   文件: Consoles.java
/**
 * select process into console by tab name
 *
 * @param tabNameProcess is tab name of process
 */
public void selectProcessByTabName(String tabNameProcess) {
  final String processTabXpath = format(TAB_PROCESS_NAME, tabNameProcess);

  seleniumWebDriverHelper.waitNoExceptions(
      () -> seleniumWebDriverHelper.waitAndClick(By.xpath(processTabXpath)),
      StaleElementReferenceException.class);
}
 
@Test
void testInvisibilityOfElementLocatedStaleElementException()
{
    SearchContext searchContext = mock(SearchContext.class);
    when(searchContext.findElement(XPATH_LOCATOR)).thenThrow(StaleElementReferenceException.class);
    assertTrue(expectedConditions.invisibilityOfElement(XPATH_LOCATOR).apply(searchContext).booleanValue());
}
 
@Test
void shouldWrapExpcetionWithAMessageInCaseOfStaleElementReferenceException()
{
    SearchContext searchContext = mock(SearchContext.class);
    when(searchContext.findElement(XPATH_LOCATOR)).thenThrow(StaleElementReferenceException.class);
    var exception = assertThrows(StaleContextException.class,
        () -> expectedConditions.findElement(searchContext, XPATH_LOCATOR));
    assertEquals("Search context used for search is stale.\n"
               + "Please double check the tests.\n"
               + "You have a few options:\n"
               + "1. Reset context;\n"
               + "2. Synchronize the tests to wait for context's stabilization;", exception.getMessage());
    assertThat(exception.getCause(), instanceOf(StaleElementReferenceException.class));
}
 
源代码30 项目: vividus   文件: NestedStepsTests.java
@Test
void testPerformAllStepsForElementIfFoundExceptionDuringRun()
{
    SearchAttributes searchAttributes = mock(SearchAttributes.class);
    WebElement element = mock(WebElement.class);
    when(baseValidations.assertIfNumberOfElementsFound(ELEMENTS_TO_PERFORM_STEPS, searchAttributes, 1,
            ComparisonRule.EQUAL_TO)).thenReturn(List.of(element));
    when(cssSelectorFactory.getCssSelectors(List.of(element))).thenReturn(List.of(FIRST_XPATH).stream());
    SearchContextSetter searchContextSetter = mockSearchContextSetter();
    doThrow(new StaleElementReferenceException("stale element")).when(webUiContext).putSearchContext(eq(element),
            any(SearchContextSetter.class));
    assertThrows(StaleElementReferenceException.class, () -> nestedSteps
            .performAllStepsForElementIfFound(ComparisonRule.EQUAL_TO, 1, searchAttributes, subSteps));
    verify(searchContextSetter).setSearchContext();
}
 
 类所在包
 同包方法