Java 类org.openqa.selenium.WebDriverException 实例源码

项目:bromium    文件:ActionExecutor.java   
private void executeIgnoringExceptions(WebDriver webDriver, WebDriverAction webDriverAction) {
    int i = 0;

    while (i < dependencies.getMaxRetries()) {
        try {
            webDriverAction.execute(webDriver, dependencies.getReplayingState(), dependencies.getEventSynchronizer());
            return;
        } catch (WebDriverException ex) {
            logger.error("Could not make it from first try because of {}", ex.toString());
            i++;
            try {
                Thread.sleep(dependencies.getMeasurementsPrecisionMilli());
            } catch (InterruptedException e) {
                throw dependencies.webDriverActionExecutionException("Interrupted while waiting to retry", e);
            }
        }
    }

    throw new TimeoutException("Could not execute the action! " + webDriverAction.getName());
}
项目:Selenium-Foundation    文件:SearchContextWait.java   
/**
 * {@inheritDoc}
 */
@Override
protected RuntimeException timeoutException(String message, Throwable lastException) {
    TimeoutException ex = new TimeoutException(message, lastException);
    ex.addInfo(WebDriverException.DRIVER_INFO, context.getClass().getName());
    WebDriver driver = WebDriverUtils.getDriver(context);
    if (driver instanceof RemoteWebDriver) {
        RemoteWebDriver remote = (RemoteWebDriver) driver;
        if (remote.getSessionId() != null) {
            ex.addInfo(WebDriverException.SESSION_ID, remote.getSessionId().toString());
        }
        if (remote.getCapabilities() != null) {
            ex.addInfo("Capabilities", remote.getCapabilities().toString());
        }
    }
    throw ex;
}
项目:marathonv5    文件:JavaProfile.java   
public String getAgentJar() {
    String prefix = launchType.getPrefix();
    if (System.getenv(MARATHON_AGENT + ".file") != null) {
        return System.getenv(MARATHON_AGENT + ".file");
    }
    if (System.getProperty(MARATHON_AGENT + ".file") != null) {
        return System.getProperty(MARATHON_AGENT + ".file");
    }
    String path = findFile(new String[] { ".", "marathon-" + prefix + "-agent", "../marathon-" + prefix + "-agent",
            "../../marathonv4/marathon-" + prefix + "/marathon-" + prefix + "-agent", System.getProperty(PROP_HOME, "."),
            dirOfMarathonJavaDriverJar }, "marathon-" + prefix + "-agent.*.jar");
    if (path != null) {
        Logger.getLogger(JavaProfile.class.getName()).info("Using " + path + " for agent");
        return path;
    }
    throw new WebDriverException("Unable to find marathon-agent.jar. Set " + MARATHON_AGENT + ".file"
            + " environment variable to point to the jar file: " + new File(".").getAbsolutePath());
}
项目:site-infrastructure-tests    文件:VisitorIDServiceMinVersionTestCase.java   
@Override
protected void runTest() throws Throwable {
    try {
        // check whether DTM has been loaded on the page
        Object response = _page
                .executeJavaScript("(typeof Visitor !== 'undefined') ? Visitor.version : 'unavailable'")
                .getJavaScriptResult();

        // make sure the element exists
        if (String.class.isAssignableFrom(response.getClass()) && !((String) response).equals("unavailable")) {
            boolean result = Tools.testVersionNotOlderThanBaseVersion((String) response, _minVersion);
            assertTrue(Tools.MCVID + " min version should be " + _minVersion, result);
        } else {
            fail(Tools.MCVID + " version not available");
        }
    } catch (WebDriverException we) {
        fail(Tools.MCVID + " not found");
    }
}
项目:Sqawsh    文件:SharedDriver.java   
@After
public void embedScreenshot(Scenario scenario) {
  try {
    if (!scenario.isFailed()) {
      // Take a screenshot only in the failure case
      return;
    }

    String webDriverType = System.getProperty("WebDriverType");
    if (!webDriverType.equals("HtmlUnit")) {
      // HtmlUnit does not support screenshots
      byte[] screenshot = getScreenshotAs(OutputType.BYTES);
      scenario.embed(screenshot, "image/png");
    }
  } catch (WebDriverException somePlatformsDontSupportScreenshots) {
    scenario.write(somePlatformsDontSupportScreenshots.getMessage());
  }
}
项目:Selenium-Foundation    文件:PageSourceUtils.java   
/**
 * Produce page source from the specified driver.
 * 
 * @param optDriver optional web driver object
 * @param reason impetus for capture request; may be 'null'
 * @param logger SLF4J logger object
 * @return page source; if capture fails, an empty string is returned
 */
public static String getArtifact(Optional<WebDriver> optDriver, Throwable reason, Logger logger) {
    if (canGetArtifact(optDriver, logger)) {
        try {
            WebDriver driver = optDriver.get();
            StringBuilder sourceBuilder = new StringBuilder(driver.getPageSource());
            insertBaseElement(sourceBuilder, driver);
            insertBreakpointInfo(sourceBuilder, reason);
            insertOriginalUrl(sourceBuilder, driver);
            return sourceBuilder.toString();
        } catch (WebDriverException e) {
            logger.warn("The driver is capable of producing page source, but failed.", e);
        }
    }
    return "";
}
项目:bromium    文件:ActionExecutorTest.java   
@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());
}
项目:bobcat    文件:AemImageSetterHelper.java   
private void executeJavascript(String imagePlaceholderId) {
  frameSwitcher.switchTo("/");
  JavascriptExecutor js = (JavascriptExecutor) webDriver;
  LOG.debug("executing javascript with argument: '{}'", imagePlaceholderId);

  bobcatWait.withTimeout(Timeouts.MEDIUM).until(driver -> {
    boolean executedSuccessfully = false;
    do {
      try {
        String javaScript = getJavascriptToExecute();
        js.executeScript(javaScript, imagePlaceholderId);
        executedSuccessfully = true;
      } catch (WebDriverException wde) {
        LOG.warn("error while executing JavaScript: '{}'", wde.getMessage(), wde);
      } catch (IOException ioe) {
        String msg = "error while loading JavaScript from file: " + IMAGE_SETTER_JS_FILENAME;
        LOG.error(msg, ioe);
        throw new BobcatRuntimeException(msg);
      }
    } while (!executedSuccessfully);
    return executedSuccessfully;
  }, DELAY_BEFORE_RETRY_IN_SECONDS);
  frameSwitcher.switchBack();
}
项目:site-infrastructure-tests    文件:DataLayerElementDelayedValueTestCase.java   
@Override
protected void runTest() throws Throwable {
    try {
        // sleep
        Thread.sleep(_delay);

        // get the value of the dl element from the page
        Object response = _page.executeJavaScript(_elementName).getJavaScriptResult();

        // make sure the element exists
        if (String.class.isAssignableFrom(response.getClass())) {
            assertEquals("Data Layer element " + _elementName + " value should be " + _elementExpectedValue
                    + "after " + _delay + "ms", _elementExpectedValue, (String) response);
        } else {
            fail("Data Layer element " + _elementName + " does not exist");
        }
    } catch (WebDriverException we) {
        fail("Data Layer element " + _elementName + " does not exist");
    }
}
项目:site-infrastructure-tests    文件:DataLayerElementDelayedExistsTestCase.java   
@Override
protected void runTest() throws Throwable {
    // wait
    Thread.sleep(_milliseconds);

    try {
        // get the value of the dl element from the page
        Object response = _page.executeJavaScript("(typeof " + _elementName + " !== 'undefined')")
                .getJavaScriptResult();

        // make sure the element exists
        if (Boolean.class.isAssignableFrom(response.getClass())) {
            assertTrue("Data Layer element " + _elementName + " must exist after " + _milliseconds + "ms",
                    (Boolean) response);
        } else {
            fail("Data Layer element " + _elementName + " does not exist");
        }
    } catch (WebDriverException we) {
        fail("Data Layer element " + _elementName + " does not exist");
    }

}
项目:site-infrastructure-tests    文件:DataLayerNumericElementDelayedValueTestCase.java   
@Override
protected void runTest() throws Throwable {
    try {
        // sleep
        Thread.sleep(_delay);

        // get the value of the dl element from the page
        Object response = _page.executeJavaScript(_elementName).getJavaScriptResult();

        // make sure the element exists
        if (Long.class.isAssignableFrom(response.getClass())) {
            assertEquals("Data Layer element " + _elementName + " numeric value should be " + _elementExpectedValue
                    + "after " + _delay + "ms", _elementExpectedValue, (Long) response);
        } else {
            fail("Data Layer element " + _elementName + " does not exist");
        }
    } catch (WebDriverException we) {
        fail("Data Layer element " + _elementName + " does not exist");
    }
}
项目:snippets    文件:CustomConditions.java   
public static ExpectedCondition<Boolean> ajaxCompleted() {
    return new ExpectedCondition<Boolean>() {
        boolean result;
        @Override
        public Boolean apply(WebDriver driver) {
            try {
                result = (Boolean) ((JavascriptExecutor) driver).executeScript("return typeof($) !== 'undefined' && $.active == 0");
                //System.out.println("Ajax return $.active == 0  is: '" + result + "'");
            } catch (WebDriverException e) {
                return false;
            }
            return result;
        }
        public String toString() {
            return "Ajax return $.active == 0  is: '" + result + "'";
        }
    };
}
项目:qaf    文件:QAFExtendedWebElement.java   
public boolean isPresent() {
    if (StringUtils.isNotBlank(id) && id != "-1" && cacheable) {
        return true;
    }
    try {
        List<WebElement> eles = null;
        if ((parentElement != null)) {
            if (!parentElement.isPresent()) {
                return false;
            }
            eles = parentElement.findElements(getBy());

        } else {
            eles = getWrappedDriver().findElements(getBy());
        }
        if ((eles != null) && (eles.size() > 0)) {
            if (StringUtils.isBlank(id)) {
                id = ((QAFExtendedWebElement) eles.get(0)).id;
            }
            return true;
        }
        return false;
    } catch (WebDriverException e) {
        return false;
    }
}
项目:qaf    文件:ElementList.java   
public void waitForIndex(final int index) {
    new QAFWebDriverWait()
            .withMessage(String.format("Wait timeout for list of %s with size %d",
                    description, index + 1))
            .until(new ExpectedCondition<QAFExtendedWebDriver, Boolean>() {
                @SuppressWarnings("unchecked")
                @Override
                public Boolean apply(QAFExtendedWebDriver driver) {
                    try {
                        clear();
                        addAll((Collection<T>) context.findElements(by));
                        return size() > index;
                    } catch (WebDriverException e) {
                        return false;
                    }
                }
            });
}
项目:qaf    文件:QAFTestBase.java   
private void init() {
    if (ApplicationProperties.DRIVER_NAME.getStringVal("").equalsIgnoreCase("")) {
        System.err.println("Driver not configured!... \nUsing " + STBArgs.browser_str.getDefaultVal()
                + " as default value. Please configure driver to be used using '"
                + ApplicationProperties.DRIVER_NAME.key + "' property");
    }
    stb = initStbArgs();
    logger.info("Initializing Driver..." + STBArgs.allToString(stb));
    // uiDriver = new UiDriverFactory().get(commandLog, stb);
    DriverInitExpectedCondition driverInitExpectedCondition = new DriverInitExpectedCondition(
            (ArrayList<LoggingBean>) getLog(), stb);
    UiDriver uiDriver = new UiDriverInitializer()
            .withTimeout(ApplicationProperties.DRIVER_INIT_TIMEOUT.getIntVal(0), TimeUnit.SECONDS)
            .pollingEvery(10, TimeUnit.SECONDS).withMessage(driverInitExpectedCondition)
            .ignoring(WebDriverException.class).until(driverInitExpectedCondition);

    setUiDriver(uiDriver);
    logger.info("driver init done");
}
项目:selenium-cucumber-framework    文件:BrowserFactory.java   
public static WebDriver selectLocalBrowser() {
    switch (browser) {
    case Chrome:
        return new ChromeDriver();
    case Firefox:
        return new FirefoxDriver();
    case IE:
        return new InternetExplorerDriver();
    case Opera:
        return new OperaDriver();
    case Safari:
        return new SafariDriver();
    default:
        throw new WebDriverException("No browser specified");
    }
}
项目:bdd-test-automation-for-mobile    文件:SetupTeardownSteps.java   
@After
public void tearDown(Scenario scenario) {
    if (scenario.isFailed()) {
        try {
            logger.info("Test failed, taking screenshot");
            byte[] screenshot = ((TakesScreenshot) new Augmenter().augment(getAppiumDriver()))
                    .getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenshot, "image/png");
        }
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        }
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }
    application.tearDown();
}
项目:aet    文件:AetSocketLock.java   
/**
 * @inheritDoc
 */
@Override
public void lock(long timeoutInMillis) {
  synchronized (syncObject) {
    // Calculate the 'exit time' for our wait loop.
    long maxWait = System.currentTimeMillis() + timeoutInMillis + ADDITIONAL_TIMEOUT_IN_MILLIS;

    // Attempt to acquire the lock until something goes wrong or we run out of time.
    do {
      try {
        if (isLockOnInetSocketAddressFree(address)) {
          return;
        }
        // Randomness or retry! Something from my past (Paul H) :
        // http://www.wattystuff.net/amateur/packet/whatispacket.htm (search for random in page)
        Thread.sleep((long) (DELAY_BETWEEN_SOCKET_CHECKS * Math.random()));
      } catch (InterruptedException | IOException e) {
        throw new WebDriverException(e);
      }
    } while (System.currentTimeMillis() < maxWait);

    throw new WebDriverException(String.format("Unable to bind to locking port %d within %d ms",
        address.getPort(), timeoutInMillis + ADDITIONAL_TIMEOUT_IN_MILLIS));
  }
}
项目:seleniumtestsframework    文件:AbstractWebDriverFactory.java   
public void cleanUp() {
    try {
        if (driver != null) {
            try {
                TestLogging.log("quiting webdriver" + Thread.currentThread().getId());
                driver.quit();
            } catch (WebDriverException ex) {
                TestLogging.log("Exception encountered when quiting driver: "
                        + WebUIDriver.getWebUIDriver().getConfig().getBrowser().name() + ":" + ex.getMessage());
            }

            driver = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:seleniumtestsframework    文件:IEDriverFactory.java   
@Override
public void cleanUp() {
    try {
        if (driver != null) {
            try {
                driver.quit();
            } catch (WebDriverException ex) {
                ex.printStackTrace();
            }

            driver = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:seleniumtestsframework    文件:FirefoxDriverFactory.java   
/**
 * Create webDriver, capture socket customexception and retry with timeout.
 *
 * @return  WebDriver
 */
protected WebDriver createWebDriverWithTimeout() {
    long time = 0;
    while (time < getTimeout()) {
        try {
            driver = createNativeDriver();
            return driver;
        } catch (WebDriverException ex) {
            if (ex.getMessage().contains("SocketException")
                    || ex.getMessage().contains("Failed to connect to binary FirefoxBinary")
                    || ex.getMessage().contains("Unable to bind to locking port 7054 within 45000 ms")) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) { }

                time++;
            } else {
                throw new RuntimeException(ex);
            }
        }
    }

    throw new RuntimeException("Got customexception when creating webDriver with socket timeout 1 minute");
}
项目:seleniumtestsframework    文件:MarionetteDriverFactory.java   
/**
 * Create webDriver, capture socket customexception and retry with timeout.
 *
 * @return  WebDriver
 */
protected WebDriver createWebDriverWithTimeout() {
    long time = 0;
    while (time < getTimeout()) {
        try {
            driver = createNativeDriver();
            return driver;
        } catch (WebDriverException ex) {
            if (ex.getMessage().contains("SocketException")
                    || ex.getMessage().contains("Failed to connect to binary FirefoxBinary")
                    || ex.getMessage().contains("Unable to bind to locking port 7054 within 45000 ms")) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) { }

                time++;
            } else {
                throw new RuntimeException(ex);
            }
        }
    }

    throw new RuntimeException("Got customexception when creating webDriver with socket timeout 1 minute");
}
项目:seleniumtestsframework    文件:WebUIDriver.java   
public static void cleanUp() {
    IWebDriverFactory iWebDriverFactory = getWebUIDriver().webDriverBuilder;
    if (iWebDriverFactory != null) {
        iWebDriverFactory.cleanUp();
    } else {
        WebDriver driver = driverSession.get();
        if (driver != null) {
            try {
                driver.quit();
            } catch (WebDriverException ex) {
                ex.printStackTrace();
            }

            driver = null;
        }
    }

    driverSession.remove();
    uxDriverSession.remove();
}
项目:jbehave-vaadin-example    文件:AddressbookSteps.java   
private Predicate<WebDriver> vaadinIsReady() {
    return new Predicate<WebDriver>() {
        @Override
        public boolean apply(WebDriver driver) {
            try {
                JavascriptExecutor executor = (JavascriptExecutor) webDriver;
                return (Boolean) executor.executeScript(//
                        " if(!window.vaadin) { return false;}" + //
                                "for (var client in window.vaadin.clients) { " + //
                                " if (window.vaadin.clients[client].isActive()) { " + //
                                "   return false;" + //
                                "  }" + //
                                "}" + //
                                "return true;");
            } catch (WebDriverException e) {
                if ((e.getMessage() != null) && e.getMessage().contains("window.vaadin is undefined")) {
                    return false;
                } else {
                    throw e;
                }
            }
        }
    };
}
项目:rise    文件:RiseWait.java   
private <V> V untilSucessful(final Supplier<V> operation, Predicate<V> isSuccessful,
        Function<Throwable, RuntimeException> exceptionProducer) {
    Instant end = Instant.now().plus(interval);
    Throwable lastThrowable;
    while (true) {
        try {
            V result = operation.get();
            if (isSuccessful.test(result))
                return result;
            else
                lastThrowable = null;
        } catch (Throwable t) {
            lastThrowable = t;
        }
        if (Instant.now().isAfter(end)) {
            throw exceptionProducer.apply(lastThrowable);
        }

        try {
            Thread.sleep(interval.toMillis());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new WebDriverException(e);
        }
    }
}
项目:Gepard    文件:WebDriverUtil.java   
/**
 * By using the default URL, creates a WebDriver object and Selenium object as well.
 *
 * @param baseUrl is the default URL for the browser, must not be null!
 * @return withthe new WebDriver object
 */
public WebDriver buildWebDriverInstance(final String baseUrl) {
    if (browserString == null) {
        throw new SimpleGepardException("No browser to be used was specified.");
    }

    DesiredCapabilities capabilities = detectCapabilities();

    try {
        webDriver = new RemoteWebDriver(buildWebDriverUrl(), capabilities);
        selenium = new WebDriverBackedSelenium(webDriver, baseUrl);
        selenium.setTimeout(DEFAULT_TIMEOUT); //set the default timeout
    } catch (WebDriverException | SeleniumException e) {
        throw new SimpleGepardException(e.getLocalizedMessage());
    }
    // hide all open windows on Mac, it is necessary to hide 'always on top' windows, otherwise useless screenshots will be created from desktop
    if (getBrowserType() == BrowserEnum.Safari) {
        selenium.keyPressNative(String.valueOf(KeyEvent.VK_F11));
    }

    return webDriver;
}
项目:Gepard    文件:WebDriverUtil.java   
/**
 * Destroys the WebDriver object of this util class, as necessary.
 */
public void destroyWebDriverInstance() {
    if (webDriver != null) {
        webDriver.close();
        try {
            Thread.sleep(WEB_DRIVER_SHUTDOWN_DELAY);
            webDriver.quit(); //close all opened browser window
        } catch (Exception e) {
            if (!(e instanceof WebDriverException)) {
                throw new SimpleGepardException("Issue occurred meanwhile waiting for WebDriver Quit.", e);
            }
        }
        webDriver = null;
    }
    selenium = null;
}
项目:marathonv5    文件:JavaProfile.java   
public String findCommand(String command) {
    if (vmCommand != null) {
        return vmCommand;
    }
    if (javaHome != null) {
        File homeFolder = new File(javaHome);
        if (!homeFolder.exists() || !homeFolder.isDirectory()) {
            throw new WebDriverException(String.format("%s: No such directory", homeFolder));
        }
        File binFolder = new File(javaHome, "bin");
        if (!binFolder.exists() || !binFolder.isDirectory()) {
            throw new WebDriverException(String.format("%s: No bin directory found in home directory", binFolder));
        }
        File java = new File(binFolder, Platform.getCurrent().is(Platform.WINDOWS) ? command + ".exe" : command);
        if (!java.exists() || !java.isFile()) {
            throw new WebDriverException(String.format("%s: No such file", java));
        }
        return java.getAbsolutePath();
    }
    return command;
}
项目:marathonv5    文件:JavaProfile.java   
public String getRecorderJar() {
    if (System.getenv(MARATHON_RECORDER + ".file") != null) {
        return System.getenv(MARATHON_RECORDER + ".file");
    }
    if (System.getProperty(MARATHON_RECORDER + ".file") != null) {
        return System.getProperty(MARATHON_RECORDER + ".file");
    }
    String prefix = launchType.getPrefix();
    String path = findFile(new String[] { ".", "marathon-" + prefix + "-recorder", "../marathon-" + prefix + "-recorder",
            System.getProperty(PROP_HOME, "."), dirOfMarathonJavaDriverJar }, "marathon-" + prefix + "-recorder.*.jar");
    if (path != null) {
        Logger.getLogger(JavaProfile.class.getName()).info("Using " + path + " for recorder");
        return path;
    }
    throw new WebDriverException("Unable to find marathon-recorder.jar. Set " + MARATHON_RECORDER
            + " environment variable to point to the jar file");
}
项目:marathonv5    文件:JavaDriverTest.java   
public void executeAsyncScriptWithoutCallback() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        WebElement element1 = driver.findElement(By.name("text-field"));
        ((JavascriptExecutor) driver).executeAsyncScript("$1.setText(\"hello world\");", element1);
        throw new MissingException(WebDriverException.class);
    } catch (WebDriverException e) {
    } finally {
        JavaElementFactory.reset();
    }
}
项目:cucumber-framework-java    文件:SessionContextManager.java   
/**
 * Clear context.
 */
public void clear() {
    if (controller != null) {
        try {
            controller.quit();
        } catch (WebDriverException wde) {
            logger.warn("Exception caught calling controller.quit(): \""+wde.getMessage()+"\" additional info: "+wde.getAdditionalInformation());
        }
    }
    controller = null;
    verify = null;
    isWebDriver = false;
    if (paramsRegistry != null) {
        paramsRegistry.clear();
    }

    Thread.currentThread().setName("Context - Inactive");
    logger.info("Context closed, controller shutdown");
}
项目:devtools-driver    文件:IOSServerManager.java   
public ServerSideSession getSession(String sessionId) {
  // first, check if the session stopped already
  if (stoppedSessionIds.contains(sessionId)) {
    throw newSessionStoppedException(sessionId);
  }

  // check if the session is in the process of stopping
  for (ServerSideSession session : sessions) {
    if (session.getSessionId().equals(sessionId)) {
      if (session.getSessionState() == SessionState.STOPPED) {
        throw newSessionStoppedException(sessionId);
      } else {
        return session;
      }
    }
  }

  throw new WebDriverException("Cannot find session " + sessionId + " on the server.");
}
项目:devtools-driver    文件:WebInspectorHelper.java   
private RemoteWebElement retrieveDocumentAndCheckReady(long deadline) {
  RemoteWebElement element = null;
  String readyState = "";
  while (!readyState.equals("complete")) {
    if (deadline > 0 && System.currentTimeMillis() > deadline) {
      throw new TimeoutException("Timeout waiting to get the document.");
    }

    try {
      if (element == null) {
        element = retrieveDocument();
      }
      readyState = element.getRemoteObject().call(".readyState");
    } catch (WebDriverException e) {
      log.info("Caught exception waiting for document to be ready. Retrying...: " + e);
      element = null;
    }
  }
  return element;
}
项目:devtools-driver    文件:WebInspectorHelper.java   
private JsonObject getResponseBody(JsonObject response) {
  JsonObject body = null;
  try {
    body =
        response.containsKey("result")
            ? response.getJsonObject("result")
            : response.getJsonObject("object");
  } catch (Exception e) {
    throw new WebDriverException(e);
  }

  if (body == null) {
    throw new RuntimeException("Error parsting " + response);
  }
  return body;
}
项目:devtools-driver    文件:ServerStatusHandler.java   
@Override
public Response handle() throws Exception {
  JSONObject res = generateStatus();

  Set<ServerSideSession> sessions = getServer().getSessions();
  Response resp = new Response();

  resp.setStatus(0);
  resp.setValue(res);
  if (sessions.size() == 0) {
    resp.setSessionId(null);
  } else if (sessions.size() == 1) {
    resp.setSessionId(sessions.iterator().next().getSessionId());
  } else {
    throw new WebDriverException("NI multi sessions per server.");
  }
  return resp;
}
项目:devtools-driver    文件:ToCSSSelectorConverter.java   
public static String convertToCSSSelector(String type, String value) {
  if ("css selector".equals(type)) {
    return value;
  }
  if ("id".equals(type)) {
    // return "#" + value; // doesn't work for id starting with an int.
    return "[id='" + value + "']";
  }
  if ("tag name".equals(type)) {
    return value;
  }
  if ("class name".equals(type)) {
    // detect composite class name
    if (isCompoundName(value)) {
      throw new InvalidSelectorException("Compound class names aren't allowed");
    }
    return "." + value;
  }
  if ("class name".equals(type)) {
    return "." + value;
  }
  if ("name".equals(type)) {
    return "[name='" + value + "']";
  }
  throw new WebDriverException("NI , selector type " + type);
}
项目:bromium    文件:ActionExecutorTest.java   
@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());
}
项目:willtest    文件:Utils.java   
public static void assumeHavingFirefoxConfigured() {
    try {
        new FirefoxBinary();
    }
    catch ( WebDriverException e ) {
        if ( e.getMessage().contains("Cannot find firefox binary in PATH") ) {
            assumeThat(
                    "Please define the path to your firefox executable using " +
                            DefaultFirefoxBinaryProvider.FIREFOX_BINARY_LOCATION_SYSTEM_PROPERTY_KEY +
                            " system property, or add your firefox executable to the PATH variable! " +
                            "This is just an assumption to keep our build green.",
                    System.getProperty(DefaultFirefoxBinaryProvider.FIREFOX_BINARY_LOCATION_SYSTEM_PROPERTY_KEY),
                    is(notNullValue()));
        } else {
            throw e;
        }
    }
}
项目:Habanero    文件:ScreenShotHook.java   
/**
 * <p>
 * Takes screen-shot if the scenario fails
 * </p>
 *
 * @param scenario will be the individual scenario's within the Feature files
 * @throws InterruptedException Exception thrown if there is an interuption within the JVM
 */
@After()
public void afterTest(Scenario scenario) throws InterruptedException {
    LOG.info("Taking screenshot IF Test Failed");
    System.out.println("Taking screenshot IF Test Failed (sysOut)");
    if (scenario.isFailed()) {
        try {
            System.out.println("Scenario FAILED... screen shot taken");
            scenario.write(getDriver().getCurrentUrl());
            byte[] screenShot = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenShot, "image/png");
        } catch (WebDriverException e) {
            LOG.error(e.getMessage());
        }
    }
}
项目:bobcat    文件:Parsys.java   
/**
 * it may happen that the window pops up just a moment before {@code dropArea.click(} happens,
 * which results in WebdriverException: 'Other element would receive the click' - thus it is
 * catched and validated
 */
private void tryToOpenInsertWindow() {
  conditions.verify(ignored -> {
    try {
      boolean isInsertButtonPresent = !driver
              .findElements(By.cssSelector(INSERT_BUTTON_SELECTOR))
              .isEmpty();
      if(!isInsertButtonPresent) {
        // AEM 6.1
        actions.doubleClick(dropArea).perform();
      } else {
        // AEM 6.2
        insertButton.click();
      }
    } catch (WebDriverException e) {
      return e.getMessage().contains("Other element would receive the click");
    }
    return insertComponentWindow.isDisplayedExpectingComponents();
  }, Timeouts.MEDIUM);
}