类org.openqa.selenium.chrome.ChromeDriverService源码实例Demo

下面列出了怎么用org.openqa.selenium.chrome.ChromeDriverService的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void shouldCreateChromeAndStartService() throws Exception {
    ChromeDriver mockChromeDriver = mock(ChromeDriver.class);
    whenNew(ChromeDriver.class).withParameterTypes(ChromeDriverService.class, Capabilities.class).withArguments(isA(ChromeDriverService.class), isA(Capabilities.class)).thenReturn(mockChromeDriver);
    ChromeDriverService.Builder mockServiceBuilder = mock(ChromeDriverService.Builder.class);
    whenNew(ChromeDriverService.Builder.class).withNoArguments().thenReturn(mockServiceBuilder);
    when(mockServiceBuilder.usingDriverExecutable(isA(File.class))).thenReturn(mockServiceBuilder);
    ChromeDriverService mockService = mock(ChromeDriverService.class);
    when(mockServiceBuilder.build()).thenReturn(mockService);

    final ChromeDriver browser = config.createBrowser();

    assertThat(browser, is(mockChromeDriver));
    verifyNew(ChromeDriver.class, times(1)).withArguments(isA(ChromeDriverService.class), isA(Capabilities.class));
    verify(mockServiceBuilder, times(1)).build();
    assertThat(config.getServices().size(), is(1));
    assertThat(config.getServices().values(), hasItem(mockService));
}
 
源代码2 项目: qaf   文件: ChromeDriverHelper.java
private synchronized void createAndStartService() {
	if ((service != null) && service.isRunning()) {
		return;
	}
	File driverFile = new File(ApplicationProperties.CHROME_DRIVER_PATH.getStringVal("./chromedriver.exe"));
	if (!driverFile.exists()) {
		logger.error("Please set webdriver.chrome.driver property properly.");
		throw new AutomationError("Driver file not exist.");
	}
	try {
		System.setProperty("webdriver.chrome.driver", driverFile.getCanonicalPath());
		service = ChromeDriverService.createDefaultService();
		service.start();
	} catch (IOException e) {
		logger.error("Unable to start Chrome driver", e);
		throw new AutomationError("Unable to start Chrome Driver Service ", e);
	}
}
 
源代码3 项目: rice   文件: WebDriverUtils.java
/**
 * <p>
 * <a href="http://code.google.com/p/chromedriver/downloads/list">ChromeDriver downloads</a>, {@see #REMOTE_PUBLIC_CHROME},
 * {@see #WEBDRIVER_CHROME_DRIVER}, and {@see #HUB_DRIVER_PROPERTY}
 * </p>
 *
 * @return chromeDriverService
 */
public static ChromeDriverService chromeDriverCreateCheck() {
    String driverParam = System.getProperty(HUB_DRIVER_PROPERTY);
    // TODO can the saucelabs driver stuff be leveraged here?
    if (driverParam != null && "chrome".equals(driverParam.toLowerCase())) {
        if (System.getProperty(WEBDRIVER_CHROME_DRIVER) == null) {
            if (System.getProperty(REMOTE_PUBLIC_CHROME) != null) {
                System.setProperty(WEBDRIVER_CHROME_DRIVER, System.getProperty(REMOTE_PUBLIC_CHROME));
            }
        }
        try {
            ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
                    .usingDriverExecutable(new File(System.getProperty(WEBDRIVER_CHROME_DRIVER)))
                    .usingAnyFreePort()
                    .build();
            return chromeDriverService;
        } catch (Throwable t) {
            throw new RuntimeException("Exception starting chrome driver service, is chromedriver ( http://code.google.com/p/chromedriver/downloads/list ) installed? You can include the path to it using -Dremote.public.chrome", t)   ;
        }
    }
    return null;
}
 
源代码4 项目: selenium   文件: TestChromeDriver.java
private static ChromeDriverService getService() {
  try {
    Path logFile = Files.createTempFile("chromedriver", ".log");
    ChromeDriverService service = new ChromeDriverService.Builder()
        .withLogLevel(ChromeDriverLogLevel.ALL)
        .withLogFile(logFile.toFile())
        .build();
    LOG.info("chromedriver will log to " + logFile);
    LOG.info("chromedriver will use log level " + ChromeDriverLogLevel.ALL.toString().toUpperCase());
    service.start();
    // Fugly.
    Runtime.getRuntime().addShutdownHook(new Thread(service::stop));
    return service;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码5 项目: camunda-bpm-platform   文件: AbstractWebappUiIT.java
@BeforeClass
public static void createDriver() {
  String chromeDriverExecutable = "chromedriver";
  if (System.getProperty( "os.name" ).toLowerCase(Locale.US).indexOf("windows") > -1) {
    chromeDriverExecutable += ".exe";
  }

  File chromeDriver = new File("target/chromedriver/" + chromeDriverExecutable);
  if (!chromeDriver.exists()) {
    throw new RuntimeException("chromedriver could not be located!");
  }

  ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
      .withVerbose(true)
      .usingAnyFreePort()
      .usingDriverExecutable(chromeDriver)
      .build();

  driver = new ChromeDriver(chromeDriverService);
}
 
@BeforeClass
public static void createDriver() {
  String chromeDriverExecutable = "chromedriver";
  if (System.getProperty( "os.name" ).toLowerCase(Locale.US).indexOf("windows") > -1) {
    chromeDriverExecutable += ".exe";
  }

  File chromeDriver = new File("target/chromedriver/" + chromeDriverExecutable);
  if (!chromeDriver.exists()) {
    throw new RuntimeException("chromedriver could not be located!");
  }

  ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
      .withVerbose(true)
      .usingAnyFreePort()
      .usingDriverExecutable(chromeDriver)
      .build();

  driver = new ChromeDriver(chromeDriverService);
}
 
源代码7 项目: coteafs-selenium   文件: Browser.java
private static WebDriver setupChromeDriver() throws MalformedURLException {
    LOG.i("Setting up Chrome driver...");
    System.setProperty("webdriver.chrome.silentOutput", "true");
    setupDriver(chromedriver());
    final ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--dns-prefetch-disable");
    if (appSetting().isHeadlessMode()) {
        chromeOptions.addArguments("--headless");
    }
    chromeOptions.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    final ChromeDriverService chromeService = ChromeDriverService.createDefaultService();
    return new ChromeDriver(chromeService, chromeOptions);
}
 
@Override
public void quitBrowser(final ChromeDriver browser) {
    super.quitBrowser(browser);
    final ChromeDriverService service = services.remove(currentThreadName());
    if (service != null && service.isRunning()) {
        service.stop();
    }
}
 
private ChromeDriverService getThreadService() {
    ChromeDriverService service = services.get(currentThreadName());
    if (service != null) {
        return service;
    }
    try {
        service = new ChromeDriverService.Builder().usingDriverExecutable(new File(getChromeDriverPath())).build();
        service.start();
        services.put(currentThreadName(), service);
    } catch (IOException e) {
        LOGGER.error("Failed to start chrome service");
        service = null;
    }
    return service;
}
 
@Test
public void shouldNotCreateChromeWhenStartingServiceThrowsAnException() throws Exception {
    ChromeDriverService.Builder mockServiceBuilder = mock(ChromeDriverService.Builder.class);
    whenNew(ChromeDriverService.Builder.class).withNoArguments().thenReturn(mockServiceBuilder);
    when(mockServiceBuilder.usingDriverExecutable(isA(File.class))).thenReturn(mockServiceBuilder);
    ChromeDriverService mockService = mock(ChromeDriverService.class);
    when(mockServiceBuilder.build()).thenReturn(mockService);
    doThrow(new IOException("Stubbed exception")).when(mockService).start();

    final ChromeDriver browser = config.createBrowser();

    assertThat(browser, is(nullValue()));
    assertThat(config.getServices(), is(Collections.<String, ChromeDriverService>emptyMap()));
    verify(mockServiceBuilder, times(1)).build();
}
 
@Test
public void shouldQuitWebDriverAndStopServiceWhenQuitBrowserIsInvoked() throws Exception {
    ChromeDriver mockChromeDriver = mock(ChromeDriver.class);
    ChromeDriverService mockService = mock(ChromeDriverService.class);
    when(mockService.isRunning()).thenReturn(true);
    config.getServices().put(config.currentThreadName(), mockService);

    config.quitBrowser(mockChromeDriver);

    verify(mockChromeDriver).quit();
    assertThat(config.getServices(), is(Collections.<String, ChromeDriverService>emptyMap()));
    verify(mockService, times(1)).stop();
}
 
@Test
public void shouldNotStopServiceIfNotRunningWhenQuitBrowserIsInvoked() throws Exception {
    ChromeDriver mockChromeDriver = mock(ChromeDriver.class);
    ChromeDriverService mockService = mock(ChromeDriverService.class);
    when(mockService.isRunning()).thenReturn(false);
    config.getServices().put(config.currentThreadName(), mockService);

    config.quitBrowser(mockChromeDriver);

    verify(mockChromeDriver).quit();
    assertThat(config.getServices(), is(Collections.<String, ChromeDriverService>emptyMap()));
    verify(mockService, times(0)).stop();
}
 
@Test
public void shouldBeAbleToCallQuitBrowserMultipleTimes() throws Exception {
    ChromeDriver mockChromeDriver = mock(ChromeDriver.class);
    ChromeDriverService mockService = mock(ChromeDriverService.class);
    when(mockService.isRunning()).thenReturn(true);
    config.getServices().put(config.currentThreadName(), mockService);

    config.quitBrowser(mockChromeDriver);
    config.quitBrowser(mockChromeDriver);

    assertThat(config.getServices(), is(Collections.<String, ChromeDriverService>emptyMap()));
    verify(mockService, times(1)).stop();
}
 
源代码14 项目: teasy   文件: StandaloneDriverFactory.java
private WebDriver chrome(DesiredCapabilities customCaps, Platform platform) {
    DriverHolder.setDriverName(CHROME);
    WebDriverManager.chromedriver().setup();
    ChromeDriverService service = ChromeDriverService.createDefaultService();
    ChromeDriver chromeDriver = new ChromeDriver(
            service,
            new ChromeCaps(customCaps, this.alertBehaviour, this.isHeadless, platform).get()
    );
    TestParamsHolder.setChromePort(service.getUrl().getPort());
    return chromeDriver;
}
 
@Bean(destroyMethod = "stop")
@Lazy
public ChromeDriverService chromeDriverService() {
	System.setProperty("webdriver.chrome.driver",
		"ext/chromedriver");
	return createDefaultService();
}
 
源代码16 项目: marathonv5   文件: ChromeWebDriverProxy.java
@Override
public DriverService createService(int port) {
    BrowserConfig config = BrowserConfig.instance();
    String wdPath = config.getValue(BROWSER, "webdriver-exe-path");
    ChromeDriverService.Builder builder = new ChromeDriverService.Builder();
    if (wdPath != null)
        builder.usingDriverExecutable(new File(wdPath));
    String environ = config.getValue(BROWSER, "browser-environment");
    if (environ != null) {
        Map<String, String> envMap = new HashMap<>();
        BufferedReader reader = new BufferedReader(new StringReader(environ));
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("=");
                if (parts != null && parts.length == 2) {
                    envMap.put(parts[0], parts[1]);
                }
            }
        } catch (IOException e) {
        }
        builder.withEnvironment(envMap);
    }
    String logFile = config.getValue(BROWSER, "webdriver-log-file-path");
    if (logFile != null) {
        builder.withLogFile(new File(logFile));
    }
    builder.withVerbose(config.getValue(BROWSER, "webdriver-verbose", false));
    builder.withSilent(config.getValue(BROWSER, "webdriver-silent", true));
    return builder.usingPort(port).build();
}
 
源代码17 项目: bromium   文件: ChromeDriverServiceSupplierTest.java
@Test
public void canStartDriverService() throws Exception {
    String pathToDriver = "chromedriver";
    String screenToUse = ":1";
    ChromeDriverService.Builder builder = mock(ChromeDriverService.Builder.class, RETURNS_MOCKS);

    ChromeDriverServiceSupplier chromeDriverServiceSupplier = new ChromeDriverServiceSupplier();

    whenNew(ChromeDriverService.Builder.class).withNoArguments().thenReturn(builder);
    chromeDriverServiceSupplier.getDriverService(pathToDriver, screenToUse);

    verify(builder).usingDriverExecutable(eq(new File(pathToDriver)));
}
 
源代码18 项目: bromium   文件: ChromeDriverSupplierTest.java
@Test
public void callsTheCorrectConstructor() throws Exception {
    ChromeDriverService chromeDriverService = mock(ChromeDriverService.class);
    DesiredCapabilities desiredCapabilities = mock(DesiredCapabilities.class);
    ChromeDriver expected = mock(ChromeDriver.class);

    whenNew(ChromeDriver.class).withArguments(chromeDriverService, desiredCapabilities).thenReturn(expected);

    ChromeDriverSupplier chromeDriverSupplier = new ChromeDriverSupplier();
    WebDriver actual = chromeDriverSupplier.get(chromeDriverService, desiredCapabilities);

    assertEquals(expected, actual);
}
 
public DebateFetcher(String chromeDriverFile)
        throws IOException
{
    service = new ChromeDriverService.Builder()
            .usingDriverExecutable(
                    new File(chromeDriverFile))
            .usingAnyFreePort()
            .withEnvironment(ImmutableMap.of("DISPLAY", ":20")).build();
    service.start();

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    driver = new RemoteWebDriver(service.getUrl(), capabilities);
}
 
源代码20 项目: oxTrust   文件: ApplicationDriver.java
public static void startService() {
	if (service == null) {
		File file = new File("/usr/bin/chromedriver");
		service = new ChromeDriverService.Builder().usingDriverExecutable(file).usingAnyFreePort().build();
	}
	try {
		service.start();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
public ChromeDriverService getService(){
    return service;
}
 
Map<String, ChromeDriverService> getServices() {
    return services;
}
 
@Override
protected ChromeDriver createBrowser() {
    final ChromeDriverService service = getThreadService();
    return service != null ? new ChromeDriver(service, createCapabilities()) : null;
}
 
源代码24 项目: QVisual   文件: ChromeDriverEx.java
public ChromeDriverEx(Capabilities capabilities) {
    this(ChromeDriverService.createDefaultService(), capabilities);
}
 
源代码25 项目: QVisual   文件: ChromeDriverEx.java
public ChromeDriverEx(ChromeDriverService service, Capabilities capabilities) {
    super(service, capabilities);
}
 
public ChromeDriverFactory(ChromeDriverService chromeDriverService,
						   WebDriverConfigurationProperties properties) {
	this.chromeDriverService = chromeDriverService;
	this.properties = properties;
}
 
源代码27 项目: NoraUi   文件: DriverFactory.java
/**
 * Generates a chrome webdriver.
 *
 * @return
 *         A chrome webdriver
 * @throws TechnicalException
 *             if an error occured when Webdriver setExecutable to true.
 */
private WebDriver generateGoogleChromeDriver() throws TechnicalException {
    final String pathWebdriver = DriverFactory.getPath(Driver.CHROME);
    if (!new File(pathWebdriver).setExecutable(true)) {
        throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_WEBDRIVER_SET_EXECUTABLE));
    }
    log.info("Generating Chrome driver ({}) ...", pathWebdriver);

    System.setProperty(Driver.CHROME.getDriverName(), pathWebdriver);

    final ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
    chromeOptions.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
    chromeOptions.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    chromeOptions.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);

    setLoggingLevel(chromeOptions);
    chromeOptions.addArguments("--ignore-certificate-errors");

    if (Context.isHeadless()) {
        chromeOptions.addArguments("--headless");
    }

    // Proxy configuration
    if (Context.getProxy().getProxyType() != ProxyType.UNSPECIFIED && Context.getProxy().getProxyType() != ProxyType.AUTODETECT) {
        chromeOptions.setCapability(CapabilityType.PROXY, Context.getProxy());
    }

    // add Modifyheader Extensions to Chrome
    if (Context.getWebdriversProperties(MODIFYHEADER_PATH) != null && !"".equals(Context.getWebdriversProperties(MODIFYHEADER_PATH))) {
        chromeOptions.addExtensions(new File(Context.getWebdriversProperties(MODIFYHEADER_PATH)));
    }

    // Set custom downloaded file path. When you check content of downloaded file by robot.
    final HashMap<String, Object> chromePrefs = new HashMap<>();
    chromePrefs.put("download.default_directory", System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER);
    chromeOptions.setExperimentalOption("prefs", chromePrefs);

    // Set custom chromium (if you not use default chromium on your target device)
    final String targetBrowserBinaryPath = Context.getWebdriversProperties(TARGET_BROWSER_BINARY_PATH);
    if (targetBrowserBinaryPath != null && !"".equals(targetBrowserBinaryPath)) {
        chromeOptions.setBinary(targetBrowserBinaryPath);
    }

    log.info("addArguments [{}] to webdriver.", Context.getWebdriversProperties(WEBDRIVER_OPTIONS_ADDITIONAL_ARGS));
    for (String additionalArgument : Context.getWebdriversProperties(WEBDRIVER_OPTIONS_ADDITIONAL_ARGS).split(",")) {
        log.info("addArgument [{}] to webdriver.", additionalArgument);
        chromeOptions.addArguments(additionalArgument);
    }

    if (Context.getWebdriversProperties(REMOTE_WEBDRIVER_URL) != null && !"".equals(Context.getWebdriversProperties(REMOTE_WEBDRIVER_URL))
            && Context.getWebdriversProperties(REMOTE_WEBDRIVER_BROWSER_VERSION) != null && !"".equals(Context.getWebdriversProperties(REMOTE_WEBDRIVER_BROWSER_VERSION))
            && Context.getWebdriversProperties(REMOTE_WEBDRIVER_PLATFORM_NAME) != null && !"".equals(Context.getWebdriversProperties(REMOTE_WEBDRIVER_PLATFORM_NAME))) {
        chromeOptions.setCapability("browserVersion", Context.getWebdriversProperties(REMOTE_WEBDRIVER_BROWSER_VERSION));
        chromeOptions.setCapability("platformName", Context.getWebdriversProperties(REMOTE_WEBDRIVER_PLATFORM_NAME));
        try {
            return new RemoteWebDriver(new URL(Context.getWebdriversProperties(REMOTE_WEBDRIVER_URL)), chromeOptions);
        } catch (MalformedURLException e) {
            throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_REMOTE_WEBDRIVER_URL));
        }
    } else {
        final String withWhitelistedIps = Context.getWebdriversProperties(WITH_WHITE_LISTED_IPS);
        if (withWhitelistedIps != null && !"".equals(withWhitelistedIps)) {
            final ChromeDriverService service = new ChromeDriverService.Builder().withWhitelistedIps(withWhitelistedIps).withVerbose(false).build();
            return new ChromeDriver(service, chromeOptions);
        } else {
            return new ChromeDriver(chromeOptions);
        }
    }
}
 
源代码28 项目: bromium   文件: ChromeDriverServiceSupplier.java
@Override
protected DriverService.Builder getBuilder() {
    return new ChromeDriverService
            .Builder();
}
 
源代码29 项目: bromium   文件: ChromeDriverSupplier.java
@Override
public WebDriver get(ChromeDriverService driverService, DesiredCapabilities desiredCapabilities) {
    return new ChromeDriver(driverService, desiredCapabilities);
}
 
@BeforeClass
public static void setup() throws IOException {
	logger.info("Starting ChromeDriverService...");
	_chromeDriverService = new ChromeDriverService.Builder().usingAnyFreePort().build();
	_chromeDriverService.start();
}
 
 类所在包
 同包方法