Java Code Examples for org.openqa.selenium.WebDriverException

The following examples show how to use org.openqa.selenium.WebDriverException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: selenium   Source File: HttpCommandExecutor.java    License: Apache License 2.0 6 votes vote down vote up
public HttpCommandExecutor(
    Map<String, CommandInfo> additionalCommands,
    URL addressOfRemoteServer,
    HttpClient.Factory httpClientFactory) {
  try {
    remoteServer = addressOfRemoteServer == null
        ? new URL(System.getProperty("webdriver.remote.server", "http://localhost:4444/"))
        : addressOfRemoteServer;
  } catch (MalformedURLException e) {
    throw new WebDriverException(e);
  }

  this.additionalCommands = additionalCommands;
  this.httpClientFactory = httpClientFactory;
  this.client = httpClientFactory.createClient(remoteServer);
}
 
Example 2
Source Project: selenium   Source File: W3CHttpResponseCodecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void decodingAnErrorWithoutAStacktraceIsDecodedProperlyForNonCompliantImplementations() {
  Map<String, Object> error = new HashMap<>();
  error.put("error", "unsupported operation");  // 500
  error.put("message", "I like peas");
  error.put("stacktrace", "");

  HttpResponse response = createValidResponse(HTTP_INTERNAL_ERROR, error);

  Response decoded = new W3CHttpResponseCodec().decode(response);

  assertThat(decoded.getState()).isEqualTo("unsupported operation");
  assertThat(decoded.getStatus().intValue()).isEqualTo(METHOD_NOT_ALLOWED);

  assertThat(decoded.getValue()).isInstanceOf(UnsupportedCommandException.class);
  assertThat(((WebDriverException) decoded.getValue()).getMessage()).contains("I like peas");
}
 
Example 3
Source Project: selenium   Source File: RemoteWebElement.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected List<WebElement> findElements(String using, String value) {
  Response response = execute(DriverCommand.FIND_CHILD_ELEMENTS(id, using, value));
  Object responseValue = response.getValue();
  if (responseValue == null) { // see https://github.com/SeleniumHQ/selenium/issues/4555
    return Collections.emptyList();
  }
  List<WebElement> allElements;
  try {
    allElements = (List<WebElement>) responseValue;
  } catch (ClassCastException ex) {
    throw new WebDriverException("Returned value cannot be converted to List<WebElement>: " + responseValue, ex);
  }
  allElements.forEach(element -> parent.setFoundBy(this, element, using, value));
  return allElements;
}
 
Example 4
Source Project: selenium   Source File: BySelector.java    License: Apache License 2.0 6 votes vote down vote up
public By pickFrom(String method, String selector) {
  if ("class name".equals(method)) {
    return By.className(selector);
  } else if ("css selector".equals(method)) {
    return By.cssSelector(selector);
  } else if ("id".equals(method)) {
    return By.id(selector);
  } else if ("link text".equals(method)) {
    return By.linkText(selector);
  } else if ("partial link text".equals(method)) {
    return By.partialLinkText(selector);
  } else if ("name".equals(method)) {
    return By.name(selector);
  } else if ("tag name".equals(method)) {
    return By.tagName(selector);
  } else if ("xpath".equals(method)) {
    return By.xpath(selector);
  } else {
    throw new WebDriverException("Cannot find matching element locator to: " + method);
  }
}
 
Example 5
Source Project: java-client   Source File: MobileBy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws WebDriverException when current session doesn't support the given selector or when
 *      value of the selector is not consistent.
 * @throws IllegalArgumentException when it is impossible to find something on the given
 * {@link SearchContext} instance
 */
@Override public WebElement findElement(SearchContext context) throws WebDriverException,
        IllegalArgumentException {
    Class<?> contextClass = context.getClass();

    if (FindsByAndroidViewTag.class.isAssignableFrom(contextClass)) {
        return FindsByAndroidViewTag.class.cast(context)
                .findElementByAndroidViewTag(getLocatorString());
    }

    if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {
        return super.findElement(context);
    }

    throw formIllegalArgumentException(contextClass, FindsByAndroidViewTag.class,
            FindsByFluentSelector.class);
}
 
Example 6
Source Project: java-client   Source File: AppiumCommandExecutor.java    License: Apache License 2.0 6 votes vote down vote up
protected void setPrivateFieldValue(String fieldName, Object newValue) {
    Class<?> superclass = getClass().getSuperclass();
    Throwable recentException = null;
    while (superclass != Object.class) {
        try {
            final Field f = superclass.getDeclaredField(fieldName);
            f.setAccessible(true);
            f.set(this, newValue);
            return;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            recentException = e;
        }
        superclass = superclass.getSuperclass();
    }
    throw new WebDriverException(recentException);
}
 
Example 7
Source Project: keycloak   Source File: PatternFlyClosableAlert.java    License: Apache License 2.0 6 votes vote down vote up
public void close() {
    try {
        closeButton.click();
        WaitUtils.pause(500); // Sometimes, when a test is too fast,
                                    // one of the consecutive alerts is not displayed;
                                    // to prevent this we need to slow down a bit
    }
    catch (WebDriverException e) {
        if (driver instanceof InternetExplorerDriver) {
            log.warn("Failed to close the alert; test is probably too slow and alert has already closed itself");
        }
        else {
            throw e;
        }
    }
}
 
Example 8
Source Project: vividus   Source File: WebElementsStepsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testCheckPageContainsTextThrowsWebDriverException()
{
    By locator = LocatorUtil.getXPathLocatorByInnerText(TEXT);
    List<WebElement> webElementList = List.of(mockedWebElement);
    when(webUiContext.getSearchContext()).thenReturn(webDriver);
    when(webDriver.findElements(locator)).thenAnswer(new Answer<List<WebElement>>()
    {
        private int count;

        @Override
        public List<WebElement> answer(InvocationOnMock invocation)
        {
            count++;
            if (count == 1)
            {
                throw new WebDriverException();
            }

            return webElementList;
        }
    });
    webElementsSteps.ifTextExists(TEXT);
    verify(softAssert).assertTrue(THERE_IS_AN_ELEMENT_WITH_TEXT_TEXT_IN_THE_CONTEXT, true);
}
 
Example 9
Source Project: selenium   Source File: EdgeHtmlDriverService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected EdgeHtmlDriverService createDriverService(File exe, int port,
                                                    Duration timeout,
                                                    List<String> args,
                                                    Map<String, String> environment) {
  try {
    EdgeHtmlDriverService
        service = new EdgeHtmlDriverService(exe, port, timeout, args, environment);

    if (getLogFile() != null) {
      service.sendOutputTo(new FileOutputStream(getLogFile()));
    } else {
      String logFile = System.getProperty(EDGEHTML_DRIVER_LOG_PROPERTY);
      if (logFile != null) {
        service.sendOutputTo(new FileOutputStream(logFile));
      }
    }

    return service;
  } catch (IOException e) {
    throw new WebDriverException(e);
  }
}
 
Example 10
Source Project: bromium   Source File: ActionExecutorTest.java    License: MIT License 6 votes vote down vote up
@Test
public void properlyHandlesInterruptedExceptionBetweenRetries() throws IOException, URISyntaxException, InterruptedException {
    ActionExecutor webDriverActionExecutionBase = getWebDriverActionExecutionBase(10);
    Iterator<WebDriverAction> webDriverActionIterator = mock(Iterator.class);
    TestScenarioActions testScenarioSteps = mock(TestScenarioActions.class);
    when(testScenarioSteps.iterator()).thenReturn(webDriverActionIterator);
    TestScenario testScenario = mock(TestScenario.class);
    when(testScenario.steps()).thenReturn(testScenarioSteps);
    WebDriverAction firstAction = mock(WebDriverAction.class);
    doThrow(new WebDriverException("Something happened!")).when(firstAction).execute(any(), any(), any());
    when(webDriverActionIterator.hasNext()).thenReturn(true, false);
    when(firstAction.expectsHttpRequest()).thenReturn(true);
    PowerMockito.mockStatic(Thread.class);
    PowerMockito.doThrow(new InterruptedException()).when(Thread.class);
    Thread.sleep(anyLong());
    when(webDriverActionIterator.next()).thenReturn(firstAction);
    ExecutionReport report = webDriverActionExecutionBase.execute(testScenario);
    assertEquals(AutomationResult.INTERRUPTED, report.getAutomationResult());
}
 
Example 11
Source Project: htmlunit   Source File: HtmlAreaTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("§§URL§§")
@BuggyWebDriver(FF = "WebDriverException",
                FF68 = "WebDriverException",
                FF60 = "WebDriverException",
                IE = "WebDriverException")
public void referer() throws Exception {
    expandExpectedAlertsVariables(URL_FIRST);

    final WebDriver driver = createWebClient("");
    driver.get(URL_FIRST.toExternalForm());
    try {
        driver.findElement(By.id("third")).click();

        final Map<String, String> lastAdditionalHeaders = getMockWebConnection().getLastAdditionalHeaders();
        assertEquals(getExpectedAlerts()[0], lastAdditionalHeaders.get(HttpHeader.REFERER));
    }
    catch (final WebDriverException e) {
        assertEquals(getExpectedAlerts()[0], "WebDriverException");
    }
}
 
Example 12
Source Project: che   Source File: SeleniumTestHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private void storeLogsFromCurrentWindow(ITestResult result, SeleniumWebDriver webDriver) {
  String testReference = getTestReference(result);

  try {
    String filename = getTestResultFilename(testReference, "log");
    Path webDriverLogsDirectory = Paths.get(webDriverLogsDir, filename);
    Files.createDirectories(webDriverLogsDirectory.getParent());
    Files.write(
        webDriverLogsDirectory,
        webDriverLogsReaderFactory
            .create(webDriver)
            .getAllLogs()
            .getBytes(Charset.forName("UTF-8")),
        StandardOpenOption.CREATE);
  } catch (WebDriverException | IOException | JsonParseException e) {
    LOG.error(format("Can't store web driver logs related to test %s.", testReference), e);
  }
}
 
Example 13
Source Project: bromium   Source File: ActionExecutorTest.java    License: MIT License 6 votes vote down vote up
@Test
public void ifTooManyAttemtpsActionTimesOut() throws IOException, URISyntaxException {
    int maxRetries = 3;
    ActionExecutor webDriverActionExecutionBase = getWebDriverActionExecutionBase(10, maxRetries);
    Iterator<WebDriverAction> webDriverActionIterator = mock(Iterator.class);
    TestScenarioActions testScenarioSteps = mock(TestScenarioActions.class);
    when(testScenarioSteps.iterator()).thenReturn(webDriverActionIterator);
    TestScenario testScenario = mock(TestScenario.class);
    when(testScenario.steps()).thenReturn(testScenarioSteps);
    when(webDriverActionIterator.hasNext()).thenReturn(true, false);
    WebDriverAction firstAction = mock(WebDriverAction.class);
    doThrow(new WebDriverException("Exception occured!")).when(firstAction).execute(any(), any(), any());
    when(webDriverActionIterator.next()).thenReturn(firstAction);
    ExecutionReport report = webDriverActionExecutionBase.execute(testScenario);
    assertEquals(AutomationResult.TIMEOUT, report.getAutomationResult());
    verify(firstAction, times(maxRetries)).execute(any(), any(), any());
}
 
Example 14
Source Project: selenium   Source File: RemoteWebDriver.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected List<WebElement> findElements(String by, String using) {
  if (using == null) {
    throw new IllegalArgumentException("Cannot find elements when the selector is null.");
  }

  Response response = execute(DriverCommand.FIND_ELEMENTS(by, using));
  Object value = response.getValue();
  if (value == null) { // see https://github.com/SeleniumHQ/selenium/issues/4555
    return Collections.emptyList();
  }
  List<WebElement> allElements;
  try {
    allElements = (List<WebElement>) value;
  } catch (ClassCastException ex) {
    throw new WebDriverException("Returned value cannot be converted to List<WebElement>: " + value, ex);
  }
  for (WebElement element : allElements) {
    setFoundBy(this, element, by, using);
  }
  return allElements;
}
 
Example 15
Source Project: che   Source File: CodenvyEditor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Auxiliary method for reading text from Orion editor.
 *
 * @param lines List of WebElements that contain text (mostly <div> tags after
 *     ORION_ACTIVE_EDITOR_CONTAINER_XPATH locator)
 * @return the normalized text
 */
private String getTextFromOrionLines(List<WebElement> lines) {
  StringBuilder stringBuilder = new StringBuilder();

  try {
    stringBuilder = waitLinesElementsPresenceAndGetText(lines);
  }
  // If an editor do not attached to the DOM (we will have state element exception). We wait
  // attaching 2 second and try to read text again.
  catch (WebDriverException ex) {
    WaitUtils.sleepQuietly(2);

    stringBuilder.setLength(0);
    stringBuilder = waitLinesElementsPresenceAndGetText(lines);
  }
  return stringBuilder.toString();
}
 
Example 16
Source Project: selenium   Source File: DriverCommandExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends the {@code command} to the driver server for execution. The server will be started
 * if requesting a new session. Likewise, if terminating a session, the server will be shutdown
 * once a response is received.
 *
 * @param command The command to execute.
 * @return The command response.
 * @throws IOException If an I/O error occurs while sending the command.
 */
@Override
public Response execute(Command command) throws IOException {
  if (DriverCommand.NEW_SESSION.equals(command.getName())) {
    service.start();
  }

  try {
    return super.execute(command);
  } catch (Throwable t) {
    Throwable rootCause = Throwables.getRootCause(t);
    if (rootCause instanceof ConnectException &&
        "Connection refused".equals(rootCause.getMessage()) &&
        !service.isRunning()) {
      throw new WebDriverException("The driver server has unexpectedly died!", t);
    }
    Throwables.throwIfUnchecked(t);
    throw new WebDriverException(t);
  } finally {
    if (DriverCommand.QUIT.equals(command.getName())) {
      service.stop();
    }
  }
}
 
Example 17
Source Project: marathonv5   Source File: JavaDriverTest.java    License: Apache License 2.0 6 votes vote down vote up
public void getLocationInView() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    WebElement element1 = driver.findElement(By.name("click-me"));
    try {
        ((RemoteWebElement) element1).getCoordinates().inViewPort();
        throw new MissingException(WebDriverException.class);
    } catch (WebDriverException e) {
    }
}
 
Example 18
Source Project: che   Source File: Consoles.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public void openServersTabFromContextMenu(String machineName) {
  final String machineXpath = format(MACHINE_NAME, machineName);

  seleniumWebDriverHelper.waitNoExceptions(
      () -> {
        seleniumWebDriverHelper.waitAndClick(By.xpath(machineXpath));
      },
      WebDriverException.class);

  seleniumWebDriverHelper.moveCursorToAndContextClick(By.xpath(machineXpath));

  seleniumWebDriverHelper.waitNoExceptions(
      () -> {
        seleniumWebDriverHelper.waitAndClick(serversMenuItem);
      },
      StaleElementReferenceException.class);
}
 
Example 19
Source Project: adf-selenium   Source File: FileOutputType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public File convertFromPngBytes(byte[] png) {
    try {
        FileUtils.writeByteArrayToFile(file, png);
    } catch (IOException e) {
        throw new WebDriverException(e);
    }
    return file;
}
 
Example 20
Source Project: selenium   Source File: RemoteWebElement.java    License: Apache License 2.0 5 votes vote down vote up
private String upload(File localFile) {
  if (!localFile.isFile()) {
    throw new WebDriverException("You may only upload files: " + localFile);
  }

  try {
    String zip = Zip.zip(localFile);
    Response response = execute(DriverCommand.UPLOAD_FILE(zip));
    return (String) response.getValue();
  } catch (IOException e) {
    throw new WebDriverException("Cannot upload " + localFile, e);
  }
}
 
Example 21
Source Project: stevia   Source File: ByExtended.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Check if the Sizzle library is loaded.
 * 
 * @return the true if Sizzle is loaded in the web page 
 */
public Boolean sizzleLoaded() {
	Boolean loaded = true;
	try {
		loaded = (Boolean) ((JavascriptExecutor) getDriver())
				.executeScript("return (window.Sizzle != null);");
		
	} catch (WebDriverException e) {
		LOG.error("while trying to verify Sizzle loading, WebDriver threw exception {} {}",e.getMessage(),e.getCause() != null ? "with cause "+e.getCause() : "");
		loaded = false;
	}
	return loaded;
}
 
Example 22
Source Project: selenium   Source File: ErrorCodes.java    License: Apache License 2.0 5 votes vote down vote up
public KnownError(
  int jsonCode,
  String w3cCode,
  int w3cHttpStatus,
  Class<? extends WebDriverException> exception,
  boolean isCanonicalJsonCodeForException,
  boolean isCanonicalForW3C) {
  this.jsonCode = jsonCode;
  this.w3cCode = w3cCode;
  this.w3cHttpStatus = w3cHttpStatus;
  this.exception = exception;
  this.isCanonicalJsonCodeForException = isCanonicalJsonCodeForException;
  this.isCanonicalForW3C = isCanonicalForW3C;
}
 
Example 23
@Override
public Optional<String> getData()
{
    try
    {
        return Optional.ofNullable(webDriverProvider.get().getCurrentUrl());
    }
    catch (WebDriverException e)
    {
        return Optional.empty();
    }
}
 
Example 24
Source Project: vividus   Source File: ScrollbarHandlerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testPerformActionWithHiddenScrollbarsExceptionStyleRestore()
{
    when(webDriverProvider.get()).thenReturn(webDriver);
    Supplier<?> action = mock(Supplier.class);
    Object object = mock(Object.class);
    mockScrollbarHiding(object);
    when(action.get()).thenThrow(new WebDriverException());
    assertThrows(WebDriverException.class, () -> scrollbarHandler.performActionWithHiddenScrollbars(action));
    verify((JavascriptExecutor) webDriver).executeScript(eq(RESTORE_STYLE_SCRIPT),
            nullable(WebElement.class), eq(object));
}
 
Example 25
Source Project: selenium   Source File: OsProcess.java    License: Apache License 2.0 5 votes vote down vote up
private void waitForProcessStarted() {
  while (starting) {
    try {
      Thread.sleep(50);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new WebDriverException(e);
    }
  }
}
 
Example 26
Source Project: vividus   Source File: MouseActionsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void clickElementWithoutAlert()
{
    WebElement body = mockBodySearch();
    doThrow(WebDriverException.class).when(body).isDisplayed();
    when(alertActions.waitForAlert(webDriver)).thenReturn(Boolean.FALSE);
    testClick(false, true);
    verify(webUiContext).reset();
}
 
Example 27
Source Project: adf-selenium   Source File: FirefoxDriverResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected RemoteWebDriver createDriver(String language) {
    RemoteWebDriver driver = new FirefoxDriver(createProfile(language));
    if (!Long.valueOf(10).equals(driver.executeScript("return arguments[0]", 10))) {
        throw new WebDriverException("This browser version is not supported due to Selenium bug 8387. See https://code.google.com/p/selenium/issues/detail?id=8387");
    }
    return driver;
}
 
Example 28
Source Project: selenium   Source File: EventFiringWebDriver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
 public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
   if (driver instanceof TakesScreenshot) {
      dispatcher.beforeGetScreenshotAs(target);
      X screenshot = ((TakesScreenshot) driver).getScreenshotAs(target);
      dispatcher.afterGetScreenshotAs(target, screenshot);
      return screenshot;
   }

  throw new UnsupportedOperationException(
      "Underlying driver instance does not support taking screenshots");
}
 
Example 29
Source Project: java-client   Source File: ErrorCodesMobile.java    License: Apache License 2.0 5 votes vote down vote up
/**
* Returns the exception type that corresponds to the given {@code statusCode}. All unrecognized
* status codes will be mapped to {@link WebDriverException WebDriverException.class}.
*
* @param statusCode The status code to convert.
* @return The exception type that corresponds to the provided status
*/
public Class<? extends WebDriverException> getExceptionType(int statusCode) {
    switch (statusCode) {
        case NO_SUCH_CONTEXT:
            return NoSuchContextException.class;
        default:
            return super.getExceptionType(statusCode);
    }
}
 
Example 30
Source Project: selenium   Source File: RemoteWebDriver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public WebDriver newWindow(WindowType typeHint) {
  String original = getWindowHandle();
  try {
    Response response = execute(DriverCommand.SWITCH_TO_NEW_WINDOW(typeHint));
    String newWindowHandle = ((Map<String, Object>) response.getValue()).get("handle").toString();
    switchTo().window(newWindowHandle);
    return RemoteWebDriver.this;
  } catch (WebDriverException ex) {
    switchTo().window(original);
    throw ex;
  }
}