Java源码示例:org.openqa.selenium.remote.service.DriverService
示例1
@Override
public synchronized void start() {
if (isRunning) {
return;
}
try {
DriverService.Builder builder = builderClass.newInstance();
builder.usingDriverExecutable(driverFile);
int port = PortProvider.getPcDriverServiceAvailablePort();
builder.usingPort(port);
driverService = builder.build();
log.info("start driver service, port: {}, driverFile: {}", port, driverFile.getAbsolutePath());
driverService.start();
url = driverService.getUrl();
isRunning = driverService.isRunning();
} catch (Exception e) {
throw new RuntimeException("启动driver service失败", e);
}
}
示例2
private ProxyDriverIntegrator getProxyDriverIntegrator(RequestFilter recordRequestFilter,
WebDriverSupplier webDriverSupplier,
DriverServiceSupplier driverServiceSupplier,
@Named(PATH_TO_DRIVER) String pathToDriverExecutable,
@Named(SCREEN) String screen,
@Named(TIMEOUT) int timeout,
ResponseFilter responseFilter) throws IOException {
BrowserMobProxy proxy = createBrowserMobProxy(timeout, recordRequestFilter, responseFilter);
proxy.start(0);
logger.info("Proxy running on port " + proxy.getPort());
Proxy seleniumProxy = createSeleniumProxy(proxy);
DesiredCapabilities desiredCapabilities = createDesiredCapabilities(seleniumProxy);
DriverService driverService = driverServiceSupplier.getDriverService(pathToDriverExecutable, screen);
WebDriver driver = webDriverSupplier.get(driverService, desiredCapabilities);
return new ProxyDriverIntegrator(driver, proxy, driverService);
}
示例3
private static FirefoxDriverCommandExecutor toExecutor(FirefoxOptions options) {
Require.nonNull("Options to construct executor from", options);
String sysProperty = System.getProperty(SystemProperty.DRIVER_USE_MARIONETTE);
boolean isLegacy = (sysProperty != null && ! Boolean.parseBoolean(sysProperty))
|| options.isLegacy();
FirefoxDriverService.Builder<?, ?> builder =
StreamSupport.stream(ServiceLoader.load(DriverService.Builder.class).spliterator(), false)
.filter(b -> b instanceof FirefoxDriverService.Builder)
.map(FirefoxDriverService.Builder.class::cast)
.filter(b -> b.isLegacy() == isLegacy)
.findFirst().orElseThrow(WebDriverException::new);
return new FirefoxDriverCommandExecutor(builder.withOptions(options).build());
}
示例4
public Factory(Tracer tracer, Predicate<Capabilities> key, String serviceClassName) {
this.tracer = Require.nonNull("Tracer", tracer);
this.key = Require.nonNull("Accepted capabilities predicate", key);
this.serviceClassName = Require.nonNull("Driver service class name", serviceClassName);
try {
Class<? extends DriverService> driverClazz =
Class.forName(serviceClassName).asSubclass(DriverService.class);
Function<Capabilities, ? extends DriverService> factory =
get(driverClazz, Capabilities.class);
if (factory == null) {
factory = get(driverClazz);
}
if (factory == null) {
throw new IllegalArgumentException(
"DriverService has no mechanism to create a default instance: " + serviceClassName);
}
this.createService = factory;
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(
"DriverService class does not exist: " + serviceClassName);
}
}
示例5
@Override
public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {
Require.nonNull("Session creation request", sessionRequest);
DriverService service = createService.apply(sessionRequest.getCapabilities());
try {
service.start();
PortProber.waitForPortUp(service.getUrl().getPort(), 30, SECONDS);
URL url = service.getUrl();
return performHandshake(
tracer,
service,
url,
sessionRequest.getDownstreamDialects(),
sessionRequest.getCapabilities());
} catch (IOException | IllegalStateException | NullPointerException | InvalidArgumentException e) {
log.log(Level.INFO, e.getMessage(), e);
service.stop();
return Optional.empty();
}
}
示例6
@Override
protected ServicedSession newActiveSession(
DriverService service,
Dialect downstream,
Dialect upstream,
HttpHandler codec,
SessionId id,
Map<String, Object> capabilities) {
return new ServicedSession(
service,
downstream,
upstream,
codec,
id,
capabilities);
}
示例7
private static Collection<SessionFactory> createSessionFactory(
Tracer tracer,
HttpClient.Factory clientFactory,
List<DriverService.Builder<?, ?>> builders,
WebDriverInfo info) {
ImmutableList.Builder<SessionFactory> toReturn = ImmutableList.builder();
Capabilities caps = info.getCanonicalCapabilities();
builders.stream()
.filter(builder -> builder.score(caps) > 0)
.forEach(builder -> {
DriverService.Builder<?, ?> freePortBuilder = builder.usingAnyFreePort();
toReturn.add(new DriverServiceSessionFactory(
tracer,
clientFactory,
c -> freePortBuilder.score(c) > 0,
freePortBuilder));
});
return toReturn.build();
}
示例8
@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();
}
示例9
@Override
public DriverService createService(int port) {
BrowserConfig config = BrowserConfig.instance();
SafariDriverService.Builder builder = new SafariDriverService.Builder();
builder.usingTechnologyPreview(config.getValue(BROWSER, "webdriver-use-technology-preview", false));
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));
}
return builder.usingPort(port).build();
}
示例10
@Override
public DriverService createService(int port) {
EdgeDriverService.Builder builder = new EdgeDriverService.Builder();
BrowserConfig config = BrowserConfig.instance();
String wdPath = config.getValue(BROWSER, "webdriver-exe-path");
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));
}
return builder.usingPort(port).build();
}
示例11
@Override
public DriverService createService(int port) {
GeckoDriverService.Builder builder = new GeckoDriverService.Builder();
BrowserConfig config = BrowserConfig.instance();
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 wdPath = config.getValue(BROWSER, "webdriver-exe-path");
if (wdPath != null)
builder.usingDriverExecutable(new File(wdPath));
String logFile = config.getValue(BROWSER, "webdriver-log-file-path");
if (logFile != null) {
builder.withLogFile(new File(logFile));
}
return builder.usingPort(port).build();
}
示例12
@Override
public DriverService createService(int port) {
InternetExplorerDriverService.Builder builder = new InternetExplorerDriverService.Builder();
BrowserConfig config = BrowserConfig.instance();
String wdPath = config.getValue(BROWSER, "webdriver-exe-path");
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));
}
String logLevel = config.getValue(BROWSER, "webdriver-ie-log-level");
if (logLevel != null)
builder.withLogLevel(InternetExplorerDriverLogLevel.valueOf(logLevel));
builder.withSilent(config.getValue(BROWSER, "webdriver-silent", true));
return builder.usingPort(port).build();
}
示例13
@Override
public DriverService createService(int port) {
BrowserConfig config = BrowserConfig.instance();
String wdPath = config.getValue(BROWSER, "webdriver-exe-path");
OperaDriverService.Builder builder = new OperaDriverService.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();
}
示例14
@Override
public DriverService getDriverService(String pathToDriverExecutable, String screenToUse) throws IOException {
return getBuilder()
.usingDriverExecutable(new File(pathToDriverExecutable))
.usingAnyFreePort()
.withEnvironment(ImmutableMap.of("DISPLAY", screenToUse))
.build();
}
示例15
@Test
public void invokesTheCorrectMethodsOfTheBuilder() throws IOException {
DriverService.Builder builder = mock(DriverService.Builder.class, RETURNS_DEEP_STUBS);
DriverServiceSupplierBase driverServiceSupplierBase = new DriverServiceSupplierBase() {
@Override
protected DriverService.Builder getBuilder() {
return builder;
}
};
DriverService driverService = driverServiceSupplierBase.getDriverService(driverExecutableFileName, screenToUse);
verify(builder).usingDriverExecutable(eq(driverExecutableFile));
}
示例16
@Test
public void providesAccessToConnectedDriverProxyAndDriverService() {
WebDriver driver = mock(WebDriver.class);
BrowserMobProxy proxy = mock(BrowserMobProxy.class);
DriverService driverService = mock(DriverService.class);
ProxyDriverIntegrator proxyDriverIntegrator = new ProxyDriverIntegrator(driver, proxy, driverService);
assertEquals(driver, proxyDriverIntegrator.getWebDriver());
assertEquals(proxy, proxyDriverIntegrator.getProxy());
assertEquals(driverService, proxyDriverIntegrator.getDriverService());
}
示例17
private AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
URL addressOfRemoteServer,
HttpClient.Factory httpClientFactory) {
super(additionalCommands,
ofNullable(service)
.map(DriverService::getUrl)
.orElse(addressOfRemoteServer), httpClientFactory);
serviceOptional = ofNullable(service);
}
示例18
/**
* Actually create a new WebDriver session. The returned webdriver is not guaranteed to be a
* {@link RemoteWebDriver}.
*/
public WebDriver build() {
if (options.isEmpty() && additionalCapabilities.isEmpty()) {
throw new SessionNotCreatedException("Refusing to create session without any capabilities");
}
Plan plan = getPlan();
CommandExecutor executor;
if (plan.isUsingDriverService()) {
AtomicReference<DriverService> serviceRef = new AtomicReference<>();
executor = new SpecCompliantExecutor(
() -> {
if (serviceRef.get() != null && serviceRef.get().isRunning()) {
throw new SessionNotCreatedException(
"Attempt to start the underlying service more than once");
}
try {
DriverService service = plan.getDriverService();
serviceRef.set(service);
service.start();
return service.getUrl();
} catch (IOException e) {
throw new SessionNotCreatedException(e.getMessage(), e);
}
},
plan::writePayload,
() -> serviceRef.get().stop());
} else {
executor = new SpecCompliantExecutor(() -> remoteHost, plan::writePayload, () -> {});
}
return new RemoteWebDriver(executor, new ImmutableCapabilities());
}
示例19
DriverService getDriverService() {
if (service != null) {
return service;
}
ServiceLoader<DriverService.Builder> allLoaders =
ServiceLoader.load(DriverService.Builder.class);
// We need to extract each of the capabilities from the payload.
return options
.stream()
.map(HashMap::new) // Make a copy so we don't alter the original values
.peek(map -> map.putAll(additionalCapabilities))
.map(ImmutableCapabilities::new)
.map(
caps ->
StreamSupport.stream(allLoaders.spliterator(), true)
.filter(builder -> builder.score(caps) > 0)
.findFirst()
.orElse(null))
.filter(Objects::nonNull)
.map(
bs -> {
try {
return bs.build();
} catch (Throwable e) {
return null;
}
})
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new IllegalStateException("Unable to find a driver service"));
}
示例20
@Test
public void shouldUseADriverServiceIfGivenOneRegardlessOfOtherChoices() throws IOException {
DriverService expected = new FakeDriverService();
RemoteWebDriverBuilder builder = RemoteWebDriver.builder()
.addAlternative(new InternetExplorerOptions())
.withDriverService(expected);
RemoteWebDriverBuilder.Plan plan = builder.getPlan();
assertThat(plan.isUsingDriverService()).isTrue();
assertThat(plan.getDriverService()).isEqualTo(expected);
}
示例21
public ServicedSession(
DriverService service,
Dialect downstream,
Dialect upstream,
HttpHandler codec,
SessionId id,
Map<String, Object> capabilities) {
super(downstream, upstream, codec, id, capabilities);
this.service = service;
new JMXHelper().register(this);
}
示例22
public static Node create(Config config) {
LoggingOptions loggingOptions = new LoggingOptions(config);
EventBusOptions eventOptions = new EventBusOptions(config);
BaseServerOptions serverOptions = new BaseServerOptions(config);
NodeOptions nodeOptions = new NodeOptions(config);
NetworkOptions networkOptions = new NetworkOptions(config);
Tracer tracer = loggingOptions.getTracer();
HttpClient.Factory clientFactory = networkOptions.getHttpClientFactory(tracer);
LocalNode.Builder builder = LocalNode.builder(
tracer,
eventOptions.getEventBus(),
serverOptions.getExternalUri(),
nodeOptions.getPublicGridUri().orElseGet(serverOptions::getExternalUri),
serverOptions.getRegistrationSecret());
List<DriverService.Builder<?, ?>> builders = new ArrayList<>();
ServiceLoader.load(DriverService.Builder.class).forEach(builders::add);
nodeOptions.getSessionFactories(info -> createSessionFactory(tracer, clientFactory, builders, info))
.forEach((caps, factories) -> factories.forEach(factory -> builder.add(caps, factory)));
new DockerOptions(config).getDockerSessionFactories(tracer, clientFactory)
.forEach((caps, factories) -> factories.forEach(factory -> builder.add(caps, factory)));
return builder.build();
}
示例23
public DriverServiceSessionFactory(
Tracer tracer,
HttpClient.Factory clientFactory,
Predicate<Capabilities> predicate,
DriverService.Builder builder) {
this.tracer = Require.nonNull("Tracer", tracer);
this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);
this.predicate = Require.nonNull("Accepted capabilities predicate", predicate);
this.builder = Require.nonNull("Driver service bulder", builder);
}
示例24
private Map<WebDriverInfo, Collection<SessionFactory>> discoverDrivers(
int maxSessions,
Function<WebDriverInfo, Collection<SessionFactory>> factoryFactory) {
if (!config.getBool("node", "detect-drivers").orElse(false)) {
return ImmutableMap.of();
}
// We don't expect duplicates, but they're fine
List<WebDriverInfo> infos =
StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false)
.filter(WebDriverInfo::isAvailable)
.sorted(Comparator.comparing(info -> info.getDisplayName().toLowerCase()))
.collect(Collectors.toList());
// Same
List<DriverService.Builder<?, ?>> builders = new ArrayList<>();
ServiceLoader.load(DriverService.Builder.class).forEach(builders::add);
Multimap<WebDriverInfo, SessionFactory> toReturn = HashMultimap.create();
infos.forEach(info -> {
Capabilities caps = info.getCanonicalCapabilities();
builders.stream()
.filter(builder -> builder.score(caps) > 0)
.forEach(builder -> {
for (int i = 0; i < Math.min(info.getMaximumSimultaneousSessions(), maxSessions); i++) {
toReturn.putAll(info, factoryFactory.apply(info));
}
});
});
return toReturn.asMap();
}
示例25
@Before
public void setUp() throws MalformedURLException {
tracer = DefaultTestTracer.createTracer();
clientFactory = mock(HttpClient.Factory.class);
driverService = mock(DriverService.class);
when(driverService.getUrl()).thenReturn(new URL("http://localhost:1234/"));
builder = mock(DriverService.Builder.class);
when(builder.build()).thenReturn(driverService);
}
示例26
private EventFiringAppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
URL addressOfRemoteServer,
HttpClient.Factory httpClientFactory) {
super(additionalCommands,
ofNullable(service)
.map(DriverService::getUrl)
.orElse(addressOfRemoteServer),
httpClientFactory);
serviceOptional = ofNullable(service);
}
示例27
public DriverService getDriverService() {
return driverService;
}
示例28
@Override
protected DriverService.Builder getBuilder() {
return new ChromeDriverService
.Builder();
}
示例29
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
HttpClient.Factory httpClientFactory) {
this(additionalCommands, checkNotNull(service), null, httpClientFactory);
}
示例30
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
DriverService service) {
this(additionalCommands, service, HttpClient.Factory.createDefault());
}