org.openqa.selenium.WebDriverException Java Examples

The following examples show how to use org.openqa.selenium.WebDriverException. 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: ActionExecutorTest.java    From bromium with 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 #2
Source File: AppiumCommandExecutor.java    From java-client with 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 #3
Source File: MobileBy.java    From java-client with 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 #4
Source File: BySelector.java    From selenium with 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 File: PatternFlyClosableAlert.java    From keycloak with 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 #6
Source File: RemoteWebElement.java    From selenium with 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 #7
Source File: DriverCommandExecutor.java    From selenium with 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 #8
Source File: ActionExecutorTest.java    From bromium with 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 #9
Source File: W3CHttpResponseCodecTest.java    From selenium with 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 #10
Source File: RemoteWebDriver.java    From selenium with 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 #11
Source File: WebElementsStepsTests.java    From vividus with 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 #12
Source File: CodenvyEditor.java    From che with 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 #13
Source File: HtmlAreaTest.java    From htmlunit with 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 #14
Source File: EdgeHtmlDriverService.java    From selenium with 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 #15
Source File: HttpCommandExecutor.java    From selenium with 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 #16
Source File: Consoles.java    From che with 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 #17
Source File: JavaDriverTest.java    From marathonv5 with 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 File: SeleniumTestHandler.java    From che with 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 #19
Source File: WebPage.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private void stopPeerConnectionStats(String jsFunction, String peerConnectionId) {

    try {
      log.debug("kurentoTest." + jsFunction + "('" + peerConnectionId + "');");
      browser.executeScript("kurentoTest." + jsFunction + "('" + peerConnectionId + "');");

    } catch (WebDriverException we) {
      we.printStackTrace();

      // If client is not ready to gather rtc statistics, we just log it
      // as warning (it is not an error itself)
      log.warn("Client does not support RTC statistics (function kurentoTest.{}() not defined)");
    }
  }
 
Example #20
Source File: ErrorHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void testCauseStackTraceShouldBeEmptyIfTheServerDidNotProvideThatInformation() {
  assertThatExceptionOfType(WebDriverException.class)
      .isThrownBy(() -> handler.throwIfResponseFailed(
          createResponse(ErrorCodes.UNHANDLED_ERROR,
                         ImmutableMap.of("message", "boom", "class", NullPointerException.class.getName())), 1234))
      .withMessage(new WebDriverException("boom (WARNING: The server did not provide any stacktrace information)\nCommand duration or timeout: 1.23 seconds").getMessage())
      .withCauseInstanceOf(NullPointerException.class)
      .satisfies(expected -> {
        assertThat(expected.getCause()).hasMessage("boom");
        assertThat(expected.getCause().getStackTrace()).isEmpty();
      });
}
 
Example #21
Source File: AppiumDriver.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Override
public ScreenOrientation getOrientation() {
    Response response = execute(DriverCommand.GET_SCREEN_ORIENTATION);
    String orientation = response.getValue().toString().toLowerCase();
    if (orientation.equals(ScreenOrientation.LANDSCAPE.value())) {
        return ScreenOrientation.LANDSCAPE;
    } else if (orientation.equals(ScreenOrientation.PORTRAIT.value())) {
        return ScreenOrientation.PORTRAIT;
    } else {
        throw new WebDriverException("Unexpected orientation returned: " + orientation);
    }
}
 
Example #22
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * An expectation for String value from javascript
 *
 * @param javaScript as executable js line
 * @return true once js return string
 */
public static ExpectedCondition<Object> jsReturnsValue(final String javaScript) {
  return new ExpectedCondition<Object>() {
    @Override
    public Object apply(WebDriver driver) {
      try {
        Object value = ((JavascriptExecutor) driver).executeScript(javaScript);

        if (value instanceof List) {
          return ((List<?>) value).isEmpty() ? null : value;
        }
        if (value instanceof String) {
          return ((String) value).isEmpty() ? null : value;
        }

        return value;
      } catch (WebDriverException e) {
        return null;
      }
    }

    @Override
    public String toString() {
      return String.format("js %s to be executable", javaScript);
    }
  };
}
 
Example #23
Source File: OperaDriverService.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
protected OperaDriverService createDriverService(File exe, int port,
                                                  Duration timeout,
                                                  List<String> args,
                                                  Map<String, String> environment) {
  try {
    return new OperaDriverService(exe, port, timeout, args, environment);
  } catch (IOException e) {
    throw new WebDriverException(e);
  }
}
 
Example #24
Source File: FirefoxDriverFactory.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public FirefoxDriver getObject() throws BeansException {
	if (properties.getFirefox().isEnabled()) {
		try {
			return new FirefoxDriver();
		} catch (WebDriverException e) {
			e.printStackTrace();
			// swallow the exception
		}
	}
	return null;
}
 
Example #25
Source File: PtlWebDriver.java    From hifive-pitalium with Apache License 2.0 5 votes vote down vote up
@Override
public <X> X getScreenshotAs(OutputType<X> outputType) throws WebDriverException {
	X screenshot = super.getScreenshotAs(outputType);
	if (environmentConfig != null && environmentConfig.isDebug()) {
		exportDebugScreenshot(screenshot);
	}
	return screenshot;
}
 
Example #26
Source File: DefaultNetworkInterfaceProvider.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public NetworkInterface getLoInterface() {
  final String localIF = getLocalInterfaceName();
  try {
    final java.net.NetworkInterface byName = java.net.NetworkInterface.getByName(localIF);
    return (byName != null) ? new NetworkInterface(byName) : null;
  } catch (SocketException e) {
    throw new WebDriverException(e);
  }
}
 
Example #27
Source File: QAFExtendedWebDriver.java    From qaf with MIT License 5 votes vote down vote up
@Override
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
	Object takeScreenshot = getCapabilities().getCapability(CapabilityType.TAKES_SCREENSHOT);
	if (null == takeScreenshot || (Boolean) takeScreenshot) {
		String base64Str = execute(DriverCommand.SCREENSHOT).getValue().toString();
		return target.convertFromBase64Png(base64Str);
	}
	return null;
}
 
Example #28
Source File: AppiumDriver.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> getContextHandles() {
    Response response = execute(DriverCommand.GET_CONTEXT_HANDLES);
    Object value = response.getValue();
    try {
        List<String> returnedValues = (List<String>) value;
        return new LinkedHashSet<>(returnedValues);
    } catch (ClassCastException ex) {
        throw new WebDriverException(
                "Returned value cannot be converted to List<String>: " + value, ex);
    }
}
 
Example #29
Source File: PageProvider.java    From adf-selenium with Apache License 2.0 5 votes vote down vote up
protected P createPage(Class<P> cls) {
    try {
        return cls.getConstructor(WebDriver.class).newInstance(driver);
    } catch (Exception e) {
        throw new WebDriverException(e.getCause() != null ? e.getCause() : e);
    }
}
 
Example #30
Source File: OperaOptions.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> asMap() {
  Map<String, Object> toReturn = new TreeMap<>(super.asMap());

  Map<String, Object> options = new TreeMap<>();

  for (String key : experimentalOptions.keySet()) {
    options.put(key, experimentalOptions.get(key));
  }

  if (binary != null) {
    options.put("binary", binary);
  }

  options.put("args", unmodifiableList(new ArrayList<>(args)));

  List<String> encodedExtensions = new ArrayList<>();
  for (File file : extensionFiles) {
    try {
      String encoded = Base64.getEncoder().encodeToString(Files.readAllBytes(file.toPath()));

      encodedExtensions.add(encoded);
    } catch (IOException e) {
      throw new WebDriverException(e);
    }
  }
  encodedExtensions.addAll(extensions);
  options.put("extensions", unmodifiableList(encodedExtensions));

  toReturn.put(CAPABILITY, options);

  return unmodifiableMap(toReturn);
}