org.openqa.selenium.StaleElementReferenceException Java Examples

The following examples show how to use org.openqa.selenium.StaleElementReferenceException. 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: TargetElementMark.java    From phoenix.webui.framework with Apache License 2.0 7 votes vote down vote up
@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)
	{
	}
}
 
Example #2
Source File: CodenvyEditor.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
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);
              });
}
 
Example #3
Source File: ElementSearchActionTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@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)));
}
 
Example #4
Source File: QAFExtendedWebElement.java    From qaf with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #5
Source File: GenericPageElement.java    From webtau with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
}
 
Example #6
Source File: FrameWebElementTest.java    From hifive-pitalium with Apache License 2.0 6 votes vote down vote up
/**
 * 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"));
}
 
Example #7
Source File: AbstractElementSearchAction.java    From vividus with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #8
Source File: FindReferencesConsoleTab.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void waitReferenceWithText(String expectedText) {
  seleniumWebDriverHelper.waitNoExceptions(
      () ->
          seleniumWebDriverHelper.waitSuccessCondition(
              driver ->
                  getReferences()
                      .stream()
                      .anyMatch(reference -> isReferenceContainsText(reference, expectedText))),
      StaleElementReferenceException.class);
}
 
Example #9
Source File: CodenvyEditor.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Wait specific git marker at giving positions. Since operation is not atomic the {@link
 * StaleElementReferenceException} might occur. That's why it is necessary to give one more try
 * until throwing an exception.
 *
 * @param marker the marker to wait
 * @param startLine the first line of git marker
 * @param endLine the last line of git marker
 */
public void waitGitMarkerInPosition(String marker, int startLine, int endLine) {
  seleniumWebDriverHelper.waitNoExceptions(
      () ->
          seleniumWebDriverHelper.waitSuccessCondition(
              webDriver -> {
                List<String> classAttrs;

                for (int i = 0; ; i++) {
                  try {
                    classAttrs =
                        getListGitMarkers()
                            .stream()
                            .map(webElement -> webElement.getAttribute("class"))
                            .collect(toList());
                    break;
                  } catch (StaleElementReferenceException e) {
                    if (i == 2) {
                      throw e;
                    }
                  }
                }

                for (int i = 0; i < classAttrs.size(); i++) {
                  if (startLine - 1 <= i && i <= endLine - 1) {
                    if (!marker.equals(classAttrs.get(i))) {
                      return false;
                    }
                  }
                }

                return true;
              },
              REDRAW_UI_ELEMENTS_TIMEOUT_SEC),
      StaleElementReferenceException.class);
}
 
Example #10
Source File: OrganizationListPage.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
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();
          });
}
 
Example #11
Source File: FileStructure.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * perform 'double click' on the certain item in the 'file structure' form
 *
 * @param item is the name of the item
 */
public void selectItemInFileStructureByDoubleClick(String item) {
  final String itemXpath = getItemXpath(item);

  // we need to wait a little to avoid node closing after quick clicking
  WaitUtils.sleepQuietly(1);

  seleniumWebDriverHelper.waitNoExceptions(
      () -> seleniumWebDriverHelper.moveCursorToAndDoubleClick(By.xpath(itemXpath)),
      StaleElementReferenceException.class);
}
 
Example #12
Source File: AddMember.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
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();
          });
}
 
Example #13
Source File: AddMember.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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;
          });
}
 
Example #14
Source File: GitStatusBar.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public void waitMessageInGitTab(final String message) {
  waitGitStatusBarInfoPanel();

  seleniumWebDriverHelper.waitNoExceptions(
      () ->
          seleniumWebDriverHelper.waitSuccessCondition(
              webDriver -> getTextStatus().contains(message), LOAD_PAGE_TIMEOUT_SEC),
      StaleElementReferenceException.class);
}
 
Example #15
Source File: ProjectExplorer.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Waits during {@code timeout} for visibility and selects item with specified {@code path} in
 * project explorer.
 *
 * @param path item's path in format: 'Test/src/pom.xml'
 * @param timeout waiting timeout in seconds
 */
public void waitAndSelectItem(String path, int timeout) {
  waitItem(path);
  seleniumWebDriverHelper.waitNoExceptions(
      () -> waitAndGetItem(path, timeout).click(),
      LOAD_PAGE_TIMEOUT_SEC,
      StaleElementReferenceException.class);
}
 
Example #16
Source File: SeleniumWebDriverHelper.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks visibility state of provided {@code webElement}.
 *
 * @param webElement element which should be checked
 * @return state of element visibility
 */
public boolean isVisible(WebElement webElement) {
  try {
    return webElement.isDisplayed();
  } catch (NoSuchElementException | StaleElementReferenceException ex) {
    return false;
  }
}
 
Example #17
Source File: AssistantFindPanel.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public void waitNode(String expectedText, int timeout) {
  seleniumWebDriverHelper.waitNoExceptions(
      () ->
          seleniumWebDriverHelper.waitSuccessCondition(
              driver -> {
                for (int i = 0; i < getActionNodesCount(timeout); i++) {
                  if (isActionNodeContainsText(i, expectedText)) {
                    return true;
                  }
                }
                return false;
              }),
      timeout,
      StaleElementReferenceException.class);
}
 
Example #18
Source File: PageComponent.java    From Selenium-Foundation with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if this component is absent or hidden
 * 
 * @return 'true' if component is absent or hidden; otherwise 'false'
 */
public boolean isInvisible() {
    RobustWebElement element = getViewport();
    if (element.hasReference()) {
        try {
            return ! element.getWrappedElement().isDisplayed();
        } catch (StaleElementReferenceException e) {
            getLogger().warn("Container element no longer exists");
        }
    }
    return true;
}
 
Example #19
Source File: BobcatWait.java    From bobcat with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the provided condition is met.
 *
 * @param condition condition to be checked
 * @return boolean indicating if condition is met
 */
public boolean isConditionMet(final ExpectedCondition<?> condition) {
  try {
    until(condition);
  } catch (TimeoutException | StaleElementReferenceException e) {
    LOG.debug("{} condition has not been met before timeout ", condition, e);
    return false;
  }
  return true;
}
 
Example #20
Source File: WebElementConditions.java    From bobcat with Apache License 2.0 5 votes vote down vote up
/**
 * Condition that checks if provided WebElement is 'ready' to be operated on, ie. is visible and not stale.
 *
 * @param element list of WebElements within which the specified WebElement is searched
 * @return ExpectedCondition representing the above check
 */
public static ExpectedCondition<WebElement> elementIsReady(final WebElement element) {
  return webDriver -> {
    try {
      return element.isDisplayed() ? element : null;
    } catch (NoSuchElementException | StaleElementReferenceException e) {
      LOG.debug("Element {} not present: {}", element, e);
      return null;
    }
  };
}
 
Example #21
Source File: WaitHelper.java    From SeleniumCucumber with GNU General Public License v3.0 5 votes vote down vote up
private WebDriverWait getWait(int timeOutInSeconds,int pollingEveryInMiliSec) {
	oLog.debug("");
	WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
	wait.pollingEvery(pollingEveryInMiliSec, TimeUnit.MILLISECONDS);
	wait.ignoring(NoSuchElementException.class);
	wait.ignoring(ElementNotVisibleException.class);
	wait.ignoring(StaleElementReferenceException.class);
	wait.ignoring(NoSuchFrameException.class);
	return wait;
}
 
Example #22
Source File: Menu.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Run command from toolbar with user delay for active state of menu
 *
 * @param idCommand
 * @param userDelay delay for waiting active state menu defined by user
 */
public void runCommand(String idCommand, int userDelay) {
  seleniumWebDriverHelper.waitNoExceptions(
      () -> seleniumWebDriverHelper.waitAndClick(By.id(idCommand), userDelay),
      userDelay,
      StaleElementReferenceException.class);
}
 
Example #23
Source File: SelenideAddons.java    From neodymium-library with MIT License 5 votes vote down vote up
/**
 * Executes the given code at least once but potentially multiple times as long as a
 * {@link StaleElementReferenceException} occurs.
 * <p>
 * The following settings can be configured within the Neodymium configuration to tune the retry behavior:
 * </p>
 * <ul>
 * <li>neodymium.selenideAddons.staleElement.retry.count (default 3 retries)</li>
 * <li>neodymium.selenideAddons.staleElement.retry.timeout (default 500ms pause between retries)</li>
 * </ul>
 * <p>
 * <b>Example:</b>
 * </p>
 * 
 * <pre>
 * SelenideAddons.$safe(() -&gt; {
 *     $("selectorOne").find("selectorTwo").shouldBe(visible);
 * });
 * </pre>
 * 
 * @param code
 *            the code to run
 */
public static void $safe(final Runnable code)
{
    final int maxRetryCount = Neodymium.configuration().staleElementRetryCount();
    int retryCounter = 0;

    while (retryCounter <= maxRetryCount)
    {
        try
        {
            code.run();
            break;
        }
        catch (final Throwable t)
        {
            if (isThrowableCausedBy(t, StaleElementReferenceException.class))
            {
                retryCounter++;
                if (retryCounter > maxRetryCount)
                {
                    // fail
                    throw t;
                }
                else
                {
                    AllureAddons.addToReport("StaleElementReferenceException catched times: \"" + retryCounter + "\".", retryCounter);
                    Selenide.sleep(Neodymium.configuration().staleElementRetryTimeout());
                }
            }
            else
            {
                // not the kind of error we are looking for
                throw t;
            }
        }
    }
}
 
Example #24
Source File: SelenideAddons.java    From neodymium-library with MIT License 5 votes vote down vote up
/**
 * Executes the given code at least once but potentially multiple times as long as a
 * {@link StaleElementReferenceException} occurs.
 * <p>
 * Attention: Since the SelenideElement class implements the InvocationHandler interface you have to make sure that
 * the element is retrieved in order to provoke a StaleElementReferenceException. You can do this by calling a
 * should function that uses a condition.
 * </p>
 * <p>
 * The following settings can be configured within the Neodymium configuration to tune the retry behavior:
 * </p>
 * <ul>
 * <li>neodymium.selenideAddons.staleElement.retry.count (default 3 retries)</li>
 * <li>neodymium.selenideAddons.staleElement.retry.timeout (default 500ms pause between retries)</li>
 * </ul>
 * <p>
 * <b>Example:</b>
 * </p>
 * 
 * <pre>
 * SelenideAddons.$safe(() -&gt; {
 *     return $("selector").should(exist);
 * });
 * </pre>
 *
 * @param code
 *            the code to run
 * @return the element of the execution or any exception that might bubble up
 */
public static SelenideElement $safe(final Supplier<SelenideElement> code)
{
    final int maxRetryCount = Neodymium.configuration().staleElementRetryCount();
    int retryCounter = 0;

    while (retryCounter <= maxRetryCount)
    {
        try
        {
            return code.get();
        }
        catch (final Throwable t)
        {
            if (isThrowableCausedBy(t, StaleElementReferenceException.class))
            {
                retryCounter++;
                if (retryCounter > maxRetryCount)
                {
                    // fail
                    throw t;
                }
                else
                {
                    AllureAddons.addToReport("StaleElementReferenceException catched times: \"" + retryCounter + "\".", retryCounter);
                    Selenide.sleep(Neodymium.configuration().staleElementRetryTimeout());
                }
            }
            else
            {
                // not the kind of error we are looking for
                throw t;
            }
        }
    }

    // never get here
    return null;
}
 
Example #25
Source File: JavaScriptUtils.java    From neodymium-library with MIT License 5 votes vote down vote up
/**
 * Wait until all conditions are true. One wait statement, so the timeouts don't sum up
 *
 * @param conditions
 *            a list of conditions to verify
 */
public static void until(final List<BooleanSupplier> conditions)
{
    final long timeout = Neodymium.configuration().javaScriptTimeout();
    final long start = System.currentTimeMillis();

    // loop if still is time
    for (final BooleanSupplier condition : conditions)
    {
        boolean endEarly = false;

        while (!endEarly && System.currentTimeMillis() - start < timeout)
        {
            try
            {
                final boolean result = condition.getAsBoolean();
                if (result)
                {
                    endEarly = true;
                    continue;
                }
            }
            catch (final StaleElementReferenceException | NoSuchElementException e)
            {
                // we might have to limit the exception range
            }

            sleep(Neodymium.configuration().javaScriptPollingInterval());

            // time is up?
            if (System.currentTimeMillis() - start >= timeout)
            {
                return;
            }
        }
    }
}
 
Example #26
Source File: ComponentContainer.java    From Selenium-Foundation with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a 'wait' proxy that switches focus to the specified context
 * 
 * @param context search context on which to focus
 * @return target search context
 */
static Coordinator<SearchContext> contextIsSwitched(final ComponentContainer context) {
    return new Coordinator<SearchContext>() {
        
        /**
         * {@inheritDoc}
         */
        @Override
        public SearchContext apply(final SearchContext ignore) {
            if (context.parent != null) {
                context.parent.switchTo();
            }
            
            try {
                return context.switchToContext();
            } catch (StaleElementReferenceException e) { //NOSONAR
                return context.refreshContext(context.acquiredAt());
            }
        }
        
        /**
         * {@inheritDoc}
         */
        @Override
        public String toString() {
            return "context to be switched";
        }
    };
}
 
Example #27
Source File: RobustElementFactory.java    From Selenium-Foundation with Apache License 2.0 5 votes vote down vote up
/**
 * Get the list of elements that match the specified locator in the indicated context.
 * 
 * @param context element search context
 * @param locator element locator
 * @return list of robust elements in context that match the locator
 */
public static List<WebElement> getElements(final WrapsContext context, final By locator) {
    List<WebElement> elements;
    try {
        elements = context.getWrappedContext().findElements(locator);
        for (int index = 0; index < elements.size(); index++) {
            elements.set(index, makeRobustElement(elements.get(index), context, locator, index));
        }
    } catch (StaleElementReferenceException e) { //NOSONAR
        elements = context.refreshContext(context.acquiredAt()).findElements(locator);
    }
    return elements;
}
 
Example #28
Source File: ExpectedSearchContextConditions.java    From vividus with Apache License 2.0 5 votes vote down vote up
private <E> E searchInforming(Supplier<E> search)
{
    try
    {
        return search.get();
    }
    catch (StaleElementReferenceException toWrap)
    {
        throw new StaleContextException(toWrap);
    }
}
 
Example #29
Source File: RobustElementWrapper.java    From Selenium-Foundation with Apache License 2.0 5 votes vote down vote up
/**
 * This is the method that intercepts component container methods in "enhanced" model objects.
 * 
 * @param obj "enhanced" object upon which the method was invoked
 * @param method {@link Method} object for the invoked method
 * @param args method invocation arguments
 * @return {@code anything} (the result of invoking the intercepted method)
 * @throws Exception {@code anything} (exception thrown by the intercepted method)
 */
@RuntimeType
@BindingPriority(Integer.MAX_VALUE)
public Object intercept(@This final Object obj, @Origin final Method method,
                @AllArguments final Object[] args) throws Exception { //NOSONAR
    try {
        return invoke(method, args);
    } catch (StaleElementReferenceException sere) {
        refreshReference(sere);
        return invoke(method, args);
    }
}
 
Example #30
Source File: RobustJavascriptExecutor.java    From Selenium-Foundation with Apache License 2.0 5 votes vote down vote up
/**
 * Refresh references wrapped by {@link RobustWebElement} objects in the specified arguments array.
 * 
 * @param e {@link StaleElementReferenceException} that prompted this refresh
 * @param args arguments array to scan for {@link RobustWebElement} objects
 * @return 'true' if at least one {@link RobustWebElement} object was refreshed; otherwise 'false'
 */
private static boolean refreshReferences(final StaleElementReferenceException e, final Object... args) {
    boolean didRefresh = false;
    
    for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof RobustWebElement) {
            ((RobustWebElement) args[i]).refreshReference(e);
            didRefresh = true;
        }
    }
    
    return didRefresh;
}