下面列出了怎么用org.openqa.selenium.WebDriverException的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
@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");
}
@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;
}
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);
}
}
/**
* {@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);
}
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);
}
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;
}
}
}
@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);
}
@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);
}
}
@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());
}
/**
* @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");
}
}
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);
}
}
@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());
}
@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;
}
/**
* 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();
}
/**
* 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();
}
}
}
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) {
}
}
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);
}
@Override
public File convertFromPngBytes(byte[] png) {
try {
FileUtils.writeByteArrayToFile(file, png);
} catch (IOException e) {
throw new WebDriverException(e);
}
return file;
}
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);
}
}
/**
* 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;
}
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;
}
@Override
public Optional<String> getData()
{
try
{
return Optional.ofNullable(webDriverProvider.get().getCurrentUrl());
}
catch (WebDriverException e)
{
return Optional.empty();
}
}
@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));
}
private void waitForProcessStarted() {
while (starting) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new WebDriverException(e);
}
}
}
@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();
}
@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;
}
@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");
}
/**
* 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);
}
}
@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;
}
}