Java Code Examples for org.openqa.selenium.Capabilities

The following examples show how to use org.openqa.selenium.Capabilities. These examples are extracted from open source projects. 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 Project: vividus   Source File: WebDriverFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public WebDriver getRemoteWebDriver(DesiredCapabilities desiredCapabilities)
{
    DesiredCapabilities mergedDesiredCapabilities = getWebDriverCapabilities(false, desiredCapabilities);
    WebDriverType webDriverType = WebDriverManager.detectType(mergedDesiredCapabilities);

    Capabilities capabilities = mergedDesiredCapabilities;
    if (webDriverType != null)
    {
        webDriverType.prepareCapabilities(mergedDesiredCapabilities);
        if (webDriverType == WebDriverType.CHROME)
        {
            WebDriverConfiguration configuration = getWebDriverConfiguration(webDriverType, false);
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments(configuration.getCommandLineArguments());
            configuration.getExperimentalOptions().forEach(chromeOptions::setExperimentalOption);
            capabilities = chromeOptions.merge(mergedDesiredCapabilities);
        }
    }
    return createWebDriver(remoteWebDriverFactory.getRemoteWebDriver(remoteDriverUrl, capabilities));
}
 
Example 2
Source Project: selenium   Source File: LocalNode.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public NodeStatus getStatus() {
  Map<Capabilities, Integer> stereotypes = factories.stream()
    .collect(groupingBy(SessionSlot::getStereotype, summingInt(caps -> 1)));

  ImmutableSet<NodeStatus.Active> activeSessions = currentSessions.asMap().values().stream()
    .map(slot -> new NodeStatus.Active(
      slot.getStereotype(),
      slot.getSession().getId(),
      slot.getSession().getCapabilities()))
    .collect(toImmutableSet());

  return new NodeStatus(
    getId(),
    externalUri,
    maxSessionCount,
    stereotypes,
    activeSessions,
    registrationSecret);
}
 
Example 3
@Override
public void resolve() {
    try {
        Optional<Object> testInstance = context.getTestInstance();
        Optional<Capabilities> capabilities = annotationsReader
                .getCapabilities(parameter, testInstance);
        InternetExplorerOptions internetExplorerOptions = (InternetExplorerOptions) getOptions(
                parameter, testInstance);
        if (capabilities.isPresent()) {
            internetExplorerOptions.merge(capabilities.get());
        }
        object = new InternetExplorerDriver(internetExplorerOptions);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 4
Source Project: selenium   Source File: JsonTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseCapabilitiesWithLoggingPreferences() {
  String caps = String.format(
      "{\"%s\": {" +
      "\"browser\": \"WARNING\"," +
      "\"client\": \"DEBUG\", " +
      "\"driver\": \"ALL\", " +
      "\"server\": \"OFF\"}}",
      CapabilityType.LOGGING_PREFS);

  Capabilities converted = new Json().toType(caps, Capabilities.class);

  LoggingPreferences lp =
      (LoggingPreferences) converted.getCapability(CapabilityType.LOGGING_PREFS);
  assertThat(lp).isNotNull();
  assertThat(lp.getLevel(BROWSER)).isEqualTo(WARNING);
  assertThat(lp.getLevel(CLIENT)).isEqualTo(FINE);
  assertThat(lp.getLevel(DRIVER)).isEqualTo(ALL);
  assertThat(lp.getLevel(SERVER)).isEqualTo(OFF);
}
 
Example 5
Source Project: vividus   Source File: VividusWebDriverFactoryTests.java    License: Apache License 2.0 6 votes vote down vote up
private void runCreateTest(boolean remoteExecution, String browserName) throws Exception
{
    vividusWebDriverFactory.setRemoteExecution(remoteExecution);
    vividusWebDriverFactory.setWebDriverEventListeners(List.of(webDriverEventListener));

    when(bddRunContext.getRunningStory()).thenReturn(createRunningStory(browserName));
    EventFiringWebDriver eventFiringWebDriver = mock(EventFiringWebDriver.class);
    PowerMockito.whenNew(EventFiringWebDriver.class).withArguments(driver).thenReturn(eventFiringWebDriver);
    Options options = mock(Options.class);
    when(eventFiringWebDriver.manage()).thenReturn(options);
    Window window = mock(Window.class);
    when(options.window()).thenReturn(window);
    when(eventFiringWebDriver.getCapabilities()).thenReturn(mock(Capabilities.class));
    BrowserWindowSize windowSize = new BrowserWindowSize("1920x1080");
    when(browserWindowSizeProvider.getBrowserWindowSize(remoteExecution))
            .thenReturn(windowSize);
    VividusWebDriver vividusWebDriver = vividusWebDriverFactory.create();
    assertEquals(eventFiringWebDriver, vividusWebDriver.getWrappedDriver());
    verify(eventFiringWebDriver).register(webDriverEventListener);
    assertEquals(remoteExecution, vividusWebDriver.isRemote());
    verify(webDriverManagerContext).reset(WebDriverManagerParameter.DESIRED_CAPABILITIES);
    verify(webDriverManager).resize(eventFiringWebDriver, windowSize);
}
 
Example 6
Source Project: selenium   Source File: SyntheticNewSessionPayloadTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldExpandAllW3CMatchesToFirstMatchesAndRemoveAlwaysMatchIfSynthesizingAPayload() {
  Map<String, Object> payload = ImmutableMap.of(
    // OSS capabilities request a chrome webdriver
    "desiredCapabilities", ImmutableMap.of("browserName", "chrome"),
    // Yet the w3c ones ask for IE and edge
    "capabilities", ImmutableMap.of(
          "alwaysMatch", ImmutableMap.of("se:cake", "cheese"),
          "firstMatch", Arrays.asList(
            ImmutableMap.of("browserName", "edge"),
            ImmutableMap.of("browserName", "cheese"))));

  try (NewSessionPayload newSession = NewSessionPayload.create(payload)) {
    List<Capabilities> allCaps = newSession.stream().collect(toList());

    assertThat(allCaps).containsExactlyInAnyOrder(
        new ImmutableCapabilities("browserName", "cheese", "se:cake", "cheese"),
        new ImmutableCapabilities("browserName", "chrome"),
        new ImmutableCapabilities("browserName", "edge", "se:cake", "cheese"));
  }
}
 
Example 7
Source Project: selenium   Source File: Host.java    License: Apache License 2.0 6 votes vote down vote up
public DistributorStatus.NodeSummary asSummary() {
  Map<Capabilities, Integer> stereotypes = new HashMap<>();
  Map<Capabilities, Integer> used = new HashMap<>();

  slots.forEach(slot -> {
    stereotypes.compute(slot.getStereotype(), (key, curr) -> curr == null ? 1 : curr + 1);
    if (slot.getStatus() != AVAILABLE) {
      used.compute(slot.getStereotype(), (key, curr) -> curr == null ? 1 : curr + 1);
    }
  });

  return new DistributorStatus.NodeSummary(
      nodeId,
      uri,
      getHostStatus() == UP,
      maxSessionCount,
      stereotypes,
      used);
}
 
Example 8
Source Project: selenium-jupiter   Source File: RemoteDriverHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void resolveOtherThanDocker(Optional<Object> testInstance)
        throws IllegalAccessException, MalformedURLException {
    Optional<Capabilities> capabilities = annotationsReader
            .getCapabilities(parameter, testInstance);

    Optional<URL> url;
    if (browser != null && browser.getUrl() != null
            && !browser.getUrl().isEmpty()) {
        url = Optional.of(new URL(browser.getUrl()));
        capabilities = Optional.of(new DesiredCapabilities(
                browser.getType(), browser.getVersion(), ANY));
    } else {
        url = annotationsReader.getUrl(parameter, testInstance,
                config.getSeleniumServerUrl());
    }

    if (url.isPresent() && capabilities.isPresent()) {
        object = resolveRemote(url.get(), capabilities.get());
    } else {
        object = resolveGeneric();
    }
}
 
Example 9
Source Project: selenium   Source File: CapabilitiesComparatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPickCorrectBrowser() {
  Capabilities chrome = new DesiredCapabilities(BrowserType.CHROME, "10", Platform.ANY);
  Capabilities firefox = new DesiredCapabilities(BrowserType.FIREFOX, "10", Platform.ANY);
  Capabilities opera = new DesiredCapabilities(BrowserType.OPERA_BLINK, "10", Platform.ANY);
  List<Capabilities> list = asList(chrome, firefox, opera);

  DesiredCapabilities desired = new DesiredCapabilities();

  desired.setBrowserName(BrowserType.CHROME);
  assertThat(getBestMatch(desired, list)).isEqualTo(chrome);

  desired.setBrowserName(BrowserType.FIREFOX);
  assertThat(getBestMatch(desired, list)).isEqualTo(firefox);

  desired.setBrowserName(BrowserType.OPERA_BLINK);
  assertThat(getBestMatch(desired, list)).isEqualTo(opera);
}
 
Example 10
Source Project: selenium   Source File: DefaultSession.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getDescription(WebDriver instance, Capabilities capabilities) {
  DesiredCapabilities caps = new DesiredCapabilities(capabilities.asMap());
  caps.setJavascriptEnabled(instance instanceof JavascriptExecutor);
  if (instance instanceof TakesScreenshot) {
    caps.setCapability(CapabilityType.TAKES_SCREENSHOT, true);
  }
  if (instance instanceof LocationContext) {
    caps.setCapability(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true);
  }
  if (instance instanceof ApplicationCache) {
    caps.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, true);
  }
  if (instance instanceof NetworkConnection) {
    caps.setCapability(CapabilityType.SUPPORTS_NETWORK_CONNECTION, true);
  }
  if (instance instanceof WebStorage) {
    caps.setCapability(CapabilityType.SUPPORTS_WEB_STORAGE, true);
  }
  if (instance instanceof Rotatable) {
    caps.setCapability(CapabilityType.ROTATABLE, true);
  }
  if (instance instanceof HasTouchScreen) {
    caps.setCapability(CapabilityType.HAS_TOUCHSCREEN, true);
  }
  return caps.asMap();
}
 
Example 11
@Test
public void shouldCreateInternetExplorerAndStartService() throws Exception {
    InternetExplorerDriver mockInternetExplorerDriver = mock(InternetExplorerDriver.class);
    whenNew(InternetExplorerDriver.class).withParameterTypes(InternetExplorerDriverService.class, Capabilities.class).withArguments(isA(InternetExplorerDriverService.class), isA(Capabilities.class)).thenReturn(mockInternetExplorerDriver);
    InternetExplorerDriverService.Builder mockServiceBuilder = mock(InternetExplorerDriverService.Builder.class);
    whenNew(InternetExplorerDriverService.Builder.class).withNoArguments().thenReturn(mockServiceBuilder);
    when(mockServiceBuilder.usingDriverExecutable(isA(File.class))).thenReturn(mockServiceBuilder);
    InternetExplorerDriverService mockService = mock(InternetExplorerDriverService.class);
    when(mockServiceBuilder.build()).thenReturn(mockService);

    final InternetExplorerDriver browser = config.createBrowser();

    assertThat(browser, is(mockInternetExplorerDriver));
    verifyNew(InternetExplorerDriver.class, times(1)).withArguments(isA(InternetExplorerDriverService.class), isA(Capabilities.class));
    verify(mockServiceBuilder, times(1)).build();
    assertThat(config.getServices().size(), is(1));
    assertThat(config.getServices().values(), hasItem(mockService));
}
 
Example 12
Source Project: selenium   Source File: RemoteWebDriver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
  Capabilities caps = getCapabilities();
  if (caps == null) {
    return super.toString();
  }

  // w3c name first
  Object platform = caps.getCapability(PLATFORM_NAME);
  if (!(platform instanceof String)) {
    platform = caps.getCapability(PLATFORM);
  }
  if (platform == null) {
    platform = "unknown";
  }

  return String.format(
      "%s: %s on %s (%s)",
      getClass().getSimpleName(),
      caps.getBrowserName(),
      platform,
      getSessionId());
}
 
Example 13
protected BiFunction<URL, Capabilities, RemoteWebDriver> getRemoteWebDriverConstructor() {
    if (webDriverConstructor == null) {
        if (isPropertySet(SELENIUM_DRIVER_CLASS)) {
            String driverClass = getProperty(SELENIUM_DRIVER_CLASS);
            try {
                Class<?> clazz = Class.forName(driverClass);
                if (RemoteWebDriver.class.isAssignableFrom(clazz)) {
                    Class<? extends RemoteWebDriver> rmd = (Class<? extends RemoteWebDriver>) clazz;
                    webDriverConstructor = new LambdaMetaHelper().getConstructor(rmd, URL.class, Capabilities.class);
                } else {
                    throw new IllegalArgumentException(driverClass + " does not implement RemoteWebDiver");
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("Unable to create RemoteWebDriver using: " + driverClass, e);
            }
        } else {
            webDriverConstructor = RemoteWebDriver::new;
        }
    }

    return webDriverConstructor;
}
 
Example 14
Source Project: coteafs-appium   Source File: Device.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private D init(final URL url, final Capabilities capability) {
    LOG.trace("Initializing driver...");
    final TypeToken<D> token = new TypeToken<D>(getClass()) {
        private static final long serialVersionUID = 1562415938665085306L;
    };
    final Class<D> cls = (Class<D>) token.getRawType();
    final Class<?>[] argTypes = new Class<?>[] { URL.class, Capabilities.class };
    try {
        final Constructor<D> ctor = cls.getDeclaredConstructor(argTypes);
        return ctor.newInstance(url, capability);
    } catch (final NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        fail(DeviceDriverInitializationFailedError.class, "Error occured while initializing device driver.", e);
    }
    return null;
}
 
Example 15
Source Project: selenium   Source File: DefaultSession.java    License: Apache License 2.0 6 votes vote down vote up
private DefaultSession(
    final DriverFactory factory,
    TemporaryFilesystem tempFs,
    final Capabilities capabilities) {
  this.knownElements = new KnownElements();
  this.tempFs = tempFs;
  final BrowserCreator browserCreator = new BrowserCreator(factory, capabilities);

  // Ensure that the browser is created on the single thread.
  EventFiringWebDriver initialDriver = browserCreator.call();

  if (!isQuietModeEnabled(browserCreator, capabilities)) {
    // Memo to self; this is not a constructor escape of "this" - probably ;)
    initialDriver.register(new SnapshotScreenListener(this));
  }

  this.driver = initialDriver;
  this.capabilities = browserCreator.getCapabilityDescription();
  this.sessionId = browserCreator.getSessionId();
}
 
Example 16
Source Project: adf-selenium   Source File: WebDriverResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    logger.fine("starting browser...");
    driver = createDriver(locale.toLanguageTag());
    if (logger.isLoggable(Level.FINE)) {
        Capabilities capabilities = driver.getCapabilities();
        logger.fine("running " + capabilities.getBrowserName() + " version " + capabilities.getVersion() + " on " +
                    capabilities.getPlatform());
    }
    DialogManager.init(driver, 10000); // timeout of 10 seconds
    driver.manage().window().setSize(new Dimension(width, height));
}
 
Example 17
Source Project: selenium   Source File: RemoteWebDriverBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, Object> validate(Capabilities options) {
  return options.asMap().entrySet().stream()
      // Ensure that the keys are ok
      .peek(
          entry -> {
            if (!OK_KEYS.test(entry.getKey())) {
              throw new IllegalArgumentException(
                  "Capability key is not a valid w3c key: " + entry.getKey());
            }
          })
      // And remove null values, as these are ignored.
      .filter(entry -> entry.getValue() != null)
      .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
}
 
Example 18
Source Project: bobcat   Source File: DesiredCapabilitiesProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void mapCapabilitiesTest() {
  properties.clear();
  properties.put("webdriver.map.cap.themap.key1", "mvalue1");
  properties.put("webdriver.map.cap.themap.key2", "mvalue2");

  Capabilities capabilities = tested.get();

  assertThat(capabilities.getCapability(THEMAP)).isInstanceOf(Map.class);
  assertThat(((Map<?, ?>) capabilities.getCapability(THEMAP)).get("key1")).isEqualTo("mvalue1");
  assertThat(((Map<?, ?>) capabilities.getCapability(THEMAP)).get("key2")).isEqualTo("mvalue2");
}
 
Example 19
Source Project: vividus   Source File: ScreenshotFileNameGeneratorTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGenerateScreenshotFileNameWithBrowserName()
{
    Capabilities capabilities = mock(Capabilities.class);
    Dimension dimension = new Dimension(WIDTH, HEIGHT);
    when(webDriverManager.getSize()).thenReturn(dimension);
    when(webDriverManager.getCapabilities()).thenReturn(capabilities);
    String browserName = "firefox";
    when(capabilities.getBrowserName()).thenReturn(browserName);
    String screenshotFileName = screenshotFileNameGenerator.generateScreenshotFileName(SCREENSHOT_NAME);
    assertTrue(screenshotFileName
            .matches(FILE_DATE_PATTERN + SCREENSHOT_NAME + SEPARATOR + browserName + WIDTH_X_HEIGHT_EXTENSION));
}
 
Example 20
Source Project: selenium   Source File: NodeStatus.java    License: Apache License 2.0 5 votes vote down vote up
private List<Map<String, Object>> asCapacity(Map<Capabilities, Integer> toConvert) {
  ImmutableList.Builder<Map<String, Object>> toReturn = ImmutableList.builder();
  toConvert.forEach((caps, count) -> toReturn.add(ImmutableMap.of(
      "capabilities", caps,
      "count", count)));
  return toReturn.build();
}
 
Example 21
Source Project: selenium   Source File: NewSessionPayloadTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCorrectlyExtractPlatformFromW3cCapabilities() {
  List<Capabilities> capabilities = create(singletonMap(
      "capabilities", singletonMap(
          "alwaysMatch", singletonMap(
              "platformName", "linux"))));

  assertEquals(Platform.LINUX, capabilities.get(0).getPlatform());
  assertNull(capabilities.get(0).getCapability("platform"));
  assertEquals("linux", capabilities.get(0).getCapability("platformName"));
}
 
Example 22
Source Project: aquality-selenium-java   Source File: BrowserFactory.java    License: Apache License 2.0 5 votes vote down vote up
default <T extends RemoteWebDriver> T getDriver(Class<T> driverClass, CommandExecutor commandExecutor, Capabilities capabilities) {
    return AqualityServices.get(IActionRetrier.class).doWithRetry(() -> {
        try {
            if (commandExecutor != null) {
                return driverClass.getDeclaredConstructor(CommandExecutor.class, Capabilities.class).newInstance(commandExecutor, capabilities);
            }

            return driverClass.getDeclaredConstructor(Capabilities.class).newInstance(capabilities);
        } catch (ReflectiveOperationException e) {
            throw new UnsupportedOperationException(String.format("Cannot instantiate driver with type '%1$s'.", driverClass), e);
        }
    }, Collections.emptyList());
}
 
Example 23
Source Project: selenium   Source File: DistributorStatus.java    License: Apache License 2.0 5 votes vote down vote up
private static Map<Capabilities, Integer> readCapabilityCounts(JsonInput input) {
  Map<Capabilities, Integer> toReturn = new HashMap<>();

  input.beginArray();
  while (input.hasNext()) {
    Capabilities caps = null;
    int count = 0;
    input.beginObject();
    while (input.hasNext()) {
      switch (input.nextName()) {
        case "capabilities":
          caps = input.read(Capabilities.class);
          break;

        case "count":
          count = input.nextNumber().intValue();
          break;

        default:
          input.skipValue();
          break;
      }
    }
    input.endObject();

    toReturn.put(caps, count);
  }
  input.endArray();

  return toReturn;
}
 
Example 24
Source Project: selenium   Source File: DefaultSessionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldClearTempFsWhenSessionCloses() {
  final DriverFactory factory = mock(DriverFactory.class);
  when(factory.newInstance(any(Capabilities.class))).thenReturn(mock(WebDriver.class));
  final TemporaryFilesystem tempFs = mock(TemporaryFilesystem.class);

  Session session = DefaultSession.createSession(
      factory, tempFs,
      new DesiredCapabilities(BrowserType.FIREFOX, "10", Platform.ANY));

  session.close();
  verify(tempFs).deleteTemporaryFiles();
  verify(tempFs).deleteBaseDir();
}
 
Example 25
Source Project: selenium   Source File: Augmenter.java    License: Apache License 2.0 5 votes vote down vote up
public Augmentation(
  Predicate<Capabilities> whenMatches,
  Class<X> interfaceClass,
  BiFunction<Capabilities, ExecuteMethod, X> implementation) {
  this.whenMatches = Require.nonNull("Capabilities predicate", whenMatches);
  this.interfaceClass = Require.nonNull("Interface to implement", interfaceClass);
  this.implementation = Require.nonNull("Interface implementation", implementation);

  Require.precondition(
    interfaceClass.isInterface(),
    "%s must be an interface, not a concrete class",
    interfaceClass);
}
 
Example 26
Source Project: qaf   Source File: UiDriverFactory.java    License: MIT License 5 votes vote down vote up
private static void onInitializationFailure(Capabilities desiredCapabilities, Throwable e,
		Collection<QAFWebDriverCommandListener> listners) {
	if ((listners != null) && !listners.isEmpty()) {
		for (QAFWebDriverCommandListener listener : listners) {
			listener.onInitializationFailure(desiredCapabilities, e);
		}
	}

}
 
Example 27
Source Project: selenium   Source File: FirefoxOptionsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void canInitFirefoxOptionsWithCapabilitiesThatContainFirefoxOptionsAsMap() {
  FirefoxProfile profile = new FirefoxProfile();
  Capabilities caps = new ImmutableCapabilities(
      FIREFOX_OPTIONS, ImmutableMap.of("profile", profile));

  FirefoxOptions options = new FirefoxOptions(caps);

  assertThat(options.getProfile()).isSameAs(profile);
}
 
Example 28
Source Project: selenium   Source File: SafariOptions.java    License: Apache License 2.0 5 votes vote down vote up
public SafariOptions(Capabilities source) {
  this();

  source.asMap().forEach((key, value)-> {
    if (CAPABILITY.equals(key) && value instanceof Map) {

      @SuppressWarnings("unchecked")
      Map<? extends String, ?> map = (Map<? extends String, ?>) value;
      options.putAll(map);
    } else if (value != null) {
      setCapability(key, value);
    }
  });
}
 
Example 29
Source Project: selenium   Source File: OneShotNode.java    License: Apache License 2.0 5 votes vote down vote up
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);

  Map<String, Object> raw = new Json().toType(
    config.get("k8s", "stereotype")
      .orElseThrow(() -> new ConfigException("Unable to find node stereotype")),
    MAP_TYPE);

  Capabilities stereotype = new ImmutableCapabilities(raw);

  Optional<String> driverName = config.get("k8s", "driver_name").map(String::toLowerCase);

  // Find the webdriver info corresponding to the driver name
  WebDriverInfo driverInfo = StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false)
    .filter(info -> info.isSupporting(stereotype))
    .filter(info -> driverName.map(name -> name.equals(info.getDisplayName().toLowerCase())).orElse(true))
    .findFirst()
    .orElseThrow(() -> new ConfigException(
      "Unable to find matching driver for %s and %s", stereotype, driverName.orElse("any driver")));

  LOG.info(String.format("Creating one-shot node for %s with stereotype %s", driverInfo, stereotype));
  LOG.info("Grid URI is: " + nodeOptions.getPublicGridUri());

  return new OneShotNode(
    loggingOptions.getTracer(),
    eventOptions.getEventBus(),
    serverOptions.getRegistrationSecret(),
    UUID.randomUUID(),
    serverOptions.getExternalUri(),
    nodeOptions.getPublicGridUri().orElseThrow(() -> new ConfigException("Unable to determine public grid address")),
    stereotype,
    driverInfo);
}
 
Example 30
@Test
public void shouldCreateRemoteDriver() throws Exception {
	config.setSeleniumGridUrl("http://my.awesomegrid.com");
    RemoteWebDriver mockRemoteWebDriver = Mockito.mock(RemoteWebDriver.class);
    whenNew(RemoteWebDriver.class)
        .withParameterTypes(URL.class, Capabilities.class)
        .withArguments(isA(URL.class), isA(Capabilities.class))
        .thenReturn(mockRemoteWebDriver);

    final RemoteWebDriver browser = config.createBrowser();

    assertThat(browser, is(mockRemoteWebDriver));
    verifyNew(RemoteWebDriver.class, times(1)).withArguments(isA(URL.class), isA(Capabilities.class));
}