org.openqa.selenium.HasCapabilities Java Examples

The following examples show how to use org.openqa.selenium.HasCapabilities. 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 File: WebDriverManager.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
public void resize(WebDriver webDriver, BrowserWindowSize browserWindowSize)
{
    if (isElectronApp() || isMobile(WebDriverUtil.unwrap(webDriver, HasCapabilities.class).getCapabilities()))
    {
        return;
    }
    Window window = webDriver.manage().window();
    if (browserWindowSize == null)
    {
        window.maximize();
    }
    else
    {
        window.setSize(browserWindowSize.toDimension());
    }
}
 
Example #2
Source File: InMemorySession.java    From selenium with Apache License 2.0 6 votes vote down vote up
private InMemorySession(WebDriver driver, Capabilities capabilities, Dialect downstream) {
  this.driver = Require.nonNull("Driver", driver);

  Capabilities caps;
  if (driver instanceof HasCapabilities) {
    caps = ((HasCapabilities) driver).getCapabilities();
  } else {
    caps = capabilities;
  }

  this.capabilities = caps.asMap().entrySet().stream()
      .filter(e -> e.getValue() != null)
      .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));

  this.id = new SessionId(UUID.randomUUID().toString());
  this.downstream = Require.nonNull("Downstream dialect", downstream);

  File tempRoot = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), id.toString());
  Require.stateCondition(tempRoot.mkdirs(), "Could not create directory %s", tempRoot);
  this.filesystem = TemporaryFilesystem.getTmpFsBasedOn(tempRoot);

  this.handler = new JsonHttpCommandHandler(
      new PretendDriverSessions(),
      LOG);
}
 
Example #3
Source File: WebDriverFactoryTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testGetWebDriverWithWebDriverType() throws Exception
{
    mockCapabilities((HasCapabilities) driver);
    WebDriverType webDriverType = mock(WebDriverType.class);
    webDriverFactory.setWebDriverType(webDriverType);
    WebDriverConfiguration configuration = mock(WebDriverConfiguration.class);
    Map<String, Object> capablities = Map.of(KEY1, TRUE, KEY2, FALSE);
    when(propertyParser.getPropertyValuesTreeByPrefix(SELENIUM_CAPABILITIES)).thenReturn(capablities);
    configuration.setBinaryPath(Optional.of(PATH));
    injectConfigurations(webDriverType, configuration);
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities(Map.of(KEY2, true));
    when(webDriverType.getWebDriver(new DesiredCapabilities(Map.of(KEY1, Boolean.TRUE, KEY2,  Boolean.TRUE)),
            configuration)).thenReturn(driver);
    mockTimeouts(driver);
    WebDriver actualDriver = webDriverFactory.getWebDriver(desiredCapabilities);
    assertThat(actualDriver, instanceOf(TextFormattingWebDriver.class));
    assertEquals(driver, ((WrapsDriver) actualDriver).getWrappedDriver());
    assertLogger();
    verify(propertyParser, never()).getPropertyValuesTreeByPrefix(SELENIUM_GRID_CAPABILITIES);
}
 
Example #4
Source File: FindSessionITCase.java    From find with MIT License 6 votes vote down vote up
@Test
public void testDocumentPreview(){
    assumeThat(((HasCapabilities) getDriver()).getCapabilities().getBrowserName(), is("firefox"));

    final ListView results = findService.search("The Season");
    final FindResult searchResult = results.searchResult(1);

    deleteCookies();

    final DocumentViewer docViewer = searchResult.openDocumentPreview();
    final Frame frame = new Frame(getDriver(), docViewer.frame());
    frame.operateOnContent(content -> {
        verifyThat("Authentication Fail frame displayed correctly", content, allOf(
                containsText("403"),
                containsText("Authentication Failed"),
                containsText("You do not have permission to view this page")
        ));
        return null;
    });
}
 
Example #5
Source File: WebDriverFactoryTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testGetWebDriverWithWebDriverTypeAndBinaryPathConfiguration()
{
    mockCapabilities((HasCapabilities) driver);
    WebDriverType webDriverType = mock(WebDriverType.class);
    when(webDriverType.isBinaryPathSupported()).thenReturn(Boolean.TRUE);
    webDriverFactory.setWebDriverType(webDriverType);
    lenient().when(propertyParser.getPropertyValue("web.driver." + webDriverType + ".driver-executable-path"))
            .thenReturn(PATH);
    lenient().when(propertyParser.getPropertyValue(String.format(BINARY_PATH_PROPERTY_FORMAT, webDriverType)))
            .thenReturn(PATH);
    DesiredCapabilities desiredCapabilities = mock(DesiredCapabilities.class);
    when(webDriverType.getWebDriver(eq(new DesiredCapabilities()),
            argThat(config -> Optional.of(PATH).equals(config.getBinaryPath())
                    && Optional.of(PATH).equals(config.getDriverExecutablePath())))).thenReturn(driver);
    Timeouts timeouts = mockTimeouts(driver);
    assertEquals(driver,
            ((WrapsDriver) webDriverFactory.getWebDriver(desiredCapabilities)).getWrappedDriver());
    verify(timeoutConfigurer).configure(timeouts);
    assertLogger();
}
 
Example #6
Source File: WebDriverFactoryTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testGetWebDriverWithWebDriverTypeAndCommandLineArgumentsConfiguration()
{
    mockCapabilities((HasCapabilities) driver);
    WebDriverType webDriverType = mock(WebDriverType.class);
    when(webDriverType.isCommandLineArgumentsSupported()).thenReturn(Boolean.TRUE);
    webDriverFactory.setWebDriverType(webDriverType);
    lenient().when(propertyParser.getPropertyValue(String.format(BINARY_PATH_PROPERTY_FORMAT, webDriverType)))
            .thenReturn(null);
    lenient().when(
            propertyParser.getPropertyValue(String.format(COMMAND_LINE_ARGUMENTS_PROPERTY_FORMAT, webDriverType)))
            .thenReturn(ARGS);
    DesiredCapabilities desiredCapabilities = mock(DesiredCapabilities.class);
    when(webDriverType.getWebDriver(eq(new DesiredCapabilities()),
            argThat(config -> Arrays.equals(new String[] { ARG_1, ARG_2 }, config.getCommandLineArguments()))))
            .thenReturn(driver);
    Timeouts timeouts = mockTimeouts(driver);
    assertEquals(driver,
            ((WrapsDriver) webDriverFactory.getWebDriver(desiredCapabilities)).getWrappedDriver());
    verify(timeoutConfigurer).configure(timeouts);
    assertLogger();
}
 
Example #7
Source File: WebDriverFactoryTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testGetWebDriverWithWebDriverTypeAndExperimentalOptionsConfiguration()
{
    mockCapabilities((HasCapabilities) driver);
    WebDriverType webDriverType = mock(WebDriverType.class);
    webDriverFactory.setWebDriverType(webDriverType);
    lenient().when(propertyParser.getPropertyValue(String.format(BINARY_PATH_PROPERTY_FORMAT, webDriverType)))
            .thenReturn(null);
    lenient().when(
            propertyParser.getPropertyValue(String.format(EXPERIMENTAL_OPTIONS_PROPERTY_FORMAT, webDriverType)))
            .thenReturn("{\"mobileEmulation\": {\"deviceName\": \"iPhone 8\"}}");
    DesiredCapabilities desiredCapabilities = mock(DesiredCapabilities.class);
    when(webDriverType.getWebDriver(eq(new DesiredCapabilities()),
            argThat(config ->  Map.of("mobileEmulation", Map.of("deviceName", "iPhone 8"))
                    .equals(config.getExperimentalOptions())))).thenReturn(driver);
    Timeouts timeouts = mockTimeouts(driver);
    assertEquals(driver,
            ((WrapsDriver) webDriverFactory.getWebDriver(desiredCapabilities)).getWrappedDriver());
    verify(timeoutConfigurer).configure(timeouts);
    assertLogger();
}
 
Example #8
Source File: PageSourceUtils.java    From Selenium-Foundation with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if the specified driver is capable of producing page source.
 * 
 * @param optDriver optional web driver object
 * @param logger SLF4J logger object; may be 'null'
 * @return 'true' if driver can produce page source; otherwise 'false
 */
public static boolean canGetArtifact(final Optional<WebDriver> optDriver, final Logger logger) {
    if (optDriver.isPresent()) {
        WebDriver driver = optDriver.get();
        if (driver instanceof HasCapabilities) {
            Capabilities caps = ((HasCapabilities) driver).getCapabilities();
            // if driver explicitly reports that it cannot produce page source
            if (Boolean.FALSE.equals(caps.getCapability(TAKES_ELEMENT_SCREENSHOT))) {
                if (logger != null) {
                    logger.warn("This driver is not capable of producing page source."); //NOSONAR
                }
            } else {
                return true;
            }
        } else {
            if (logger != null) {
                logger.warn("Unable to determine if this driver can capture page source."); //NOSONAR
            }
        }
    }
    return false;
}
 
Example #9
Source File: BrowserLogCleanningListenerTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> testCleanBeforeNavigate()
{
    WebDriver driver = mock(WebDriver.class, withSettings().extraInterfaces(HasCapabilities.class));
    Consumer<Runnable> test = methodUnderTest ->
    {
        Options options = mock(Options.class);
        when(driver.manage()).thenReturn(options);
        Logs logs = mock(Logs.class);
        when(options.logs()).thenReturn(logs);
        when(logs.get(LogType.BROWSER)).thenReturn(mock(LogEntries.class));
        methodUnderTest.run();
    };
    return Stream.of(
            dynamicTest("beforeNavigateBack", () -> test.accept(() -> listener.beforeNavigateBack(driver))),
            dynamicTest("beforeNavigateForward", () -> test.accept(() -> listener.beforeNavigateForward(driver))),
            dynamicTest("beforeNavigateRefresh", () -> test.accept(() -> listener.beforeNavigateRefresh(driver))),
            dynamicTest("beforeNavigateTo", () -> test.accept(() -> listener.beforeNavigateTo("url", driver))));
}
 
Example #10
Source File: WebDriverManagerTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testGetSize()
{
    MobileDriver<?> mobileDriver = mock(MobileDriver.class, withSettings().extraInterfaces(HasCapabilities.class));
    Set<String> contexts = new HashSet<>();
    contexts.add(WEBVIEW_CONTEXT);
    contexts.add(NATIVE_APP_CONTEXT);
    mockMobileDriverContext(mobileDriver, WEBVIEW_CONTEXT, contexts);
    lenient().when(webDriverManagerContext.getParameter(WebDriverManagerParameter.SCREEN_SIZE)).thenReturn(null);
    lenient().when(webDriverManagerContext.getParameter(WebDriverManagerParameter.ORIENTATION))
            .thenReturn(ScreenOrientation.PORTRAIT);
    WebDriverManager spy = spyIsMobile(true);
    Window window = mock(Window.class);
    when(mockOptions(mobileDriver).window()).thenReturn(window);
    when(window.getSize()).thenReturn(mock(Dimension.class));
    assertNotNull(spy.getSize());
}
 
Example #11
Source File: DeviceWebDriver.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Capabilities getCapabilities()
{
    if ( webDriver instanceof HasCapabilities )
        return ((HasCapabilities) webDriver).getCapabilities();
    else
        return null;
}
 
Example #12
Source File: DefaultExtWebDriver.java    From JTAF-ExtWebDriver with Apache License 2.0 5 votes vote down vote up
@Override
public String getBrowserVersion() {
	if (wd != null) {
		Capabilities capabilities = ((HasCapabilities) wd)
				.getCapabilities();
		if (capabilities != null) {
			return capabilities.getVersion();
		}
		return null;
	}
	return null;
}
 
Example #13
Source File: SeleniumCdpConnection.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static Optional<Connection> create(WebDriver driver) {
  if (!(driver instanceof HasCapabilities)) {
    throw new IllegalStateException("Given webdriver instance must have capabilities");
  }

  return create(((HasCapabilities) driver).getCapabilities());
}
 
Example #14
Source File: EventFiringWebDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Capabilities getCapabilities() {
  if (driver instanceof HasCapabilities) {
    return ((HasCapabilities) driver).getCapabilities();
  }
  throw new UnsupportedOperationException(
      "Underlying driver does not implement getting capabilities yet.");
}
 
Example #15
Source File: WebDriverBackedSelenium.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Capabilities getCapabilities() {
  WebDriver driver = getWrappedDriver();
  if (driver instanceof HasCapabilities) {
    return ((HasCapabilities) driver).getCapabilities();
  }

  return null;
}
 
Example #16
Source File: WebDriverCommandProcessor.java    From selenium with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected void assertDriverSupportsJavascript(WebDriver driver) {
  if (!(driver instanceof JavascriptExecutor)) {
    throw new IllegalStateException("Driver instance must support JS.");
  }

  if (!(driver instanceof HasCapabilities)) {
    // Might be proxy. Bail.
    return;
  }

  if (!((HasCapabilities) driver).getCapabilities().is(SUPPORTS_JAVASCRIPT)) {
    throw new IllegalStateException("JS support must be enabled.");
  }
}
 
Example #17
Source File: Html5CapabilitiesTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private void configureCapability(String capability, boolean isEnabled) {
  Capabilities desiredCaps = new ImmutableCapabilities(capability, isEnabled);
  localDriver = new WebDriverBuilder().get(desiredCaps);
  Capabilities caps = ((HasCapabilities) localDriver).getCapabilities();
  assertThat(caps.getCapability(capability)).isNotNull();
  assertThat(caps.is(capability)).isEqualTo(isEnabled);
}
 
Example #18
Source File: EventFiringWebDriverTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnCapabilitiesWhenUnderlyingDriverImplementsInterfac() {
  WebDriver mockedDriver = mock(WebDriver.class, withSettings().extraInterfaces(HasCapabilities.class));
  EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver);

  final Capabilities caps = new ImmutableCapabilities();
  when(((HasCapabilities) mockedDriver).getCapabilities()).thenReturn(caps);

  assertThat(testedDriver.getCapabilities()).isSameAs(caps);
}
 
Example #19
Source File: AugmenterTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeAbleToAugmentMultipleTimes() {
  Capabilities caps = new ImmutableCapabilities("canRotate", true, "magic.numbers", true);

  StubExecutor stubExecutor = new StubExecutor(caps);
  stubExecutor.expect(DriverCommand.GET_SCREEN_ORIENTATION,
    Collections.emptyMap(),
    ScreenOrientation.PORTRAIT.name());
  RemoteWebDriver driver = new RemoteWebDriver(stubExecutor, caps);

  WebDriver augmented = getAugmenter()
    .addDriverAugmentation(
      "canRotate",
      Rotatable.class,
      (c, exe) -> new RemoteRotatable(exe))
    .augment(driver);

  assertThat(driver).isNotSameAs(augmented);
  assertThat(augmented).isInstanceOf(Rotatable.class);
  assertThat(augmented).isNotInstanceOf(HasMagicNumbers.class);

  WebDriver augmentedAgain = getAugmenter()
    .addDriverAugmentation(
      "magic.numbers",
      HasMagicNumbers.class,
      (c, exe) -> () -> 42)
    .augment(augmented);

  assertThat(augmented).isNotSameAs(augmentedAgain);
  assertThat(augmentedAgain).isInstanceOf(Rotatable.class);
  assertThat(augmentedAgain).isInstanceOf(HasMagicNumbers.class);

  ((Rotatable) augmentedAgain).getOrientation();  // Should not throw.

  assertThat(((HasCapabilities) augmentedAgain).getCapabilities())
    .isSameAs(driver.getCapabilities());
}
 
Example #20
Source File: TestUtilities.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static int getChromeVersion(WebDriver driver) {
  if (!(driver instanceof HasCapabilities)) {
    // Driver does not support capabilities -- not a chromedriver at all.
    return 0;
  }
  Capabilities caps = ((HasCapabilities) driver).getCapabilities();
  String chromedriverVersion = (String) caps.getCapability("chrome.chromedriverVersion");
  if (chromedriverVersion == null) {
    Object chrome = caps.getCapability("chrome");
    if (chrome != null) {
      chromedriverVersion = (String) ((Map<?,?>) chrome).get("chromedriverVersion");
    }
  }
  if (chromedriverVersion != null) {
    String[] versionMajorMinor = chromedriverVersion.split("\\.", 2);
    if (versionMajorMinor.length > 1) {
      try {
        return Integer.parseInt(versionMajorMinor[0]);
      } catch (NumberFormatException e) {
        // First component of the version is not a number -- not a chromedriver.
        return 0;
      }
    }
  }
  return 0;

}
 
Example #21
Source File: TestUtilities.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Returns Platform where the browser (driven by given WebDriver) runs on.
 */
public static Platform getEffectivePlatform(WebDriver driver) {
  if (!(driver instanceof HasCapabilities)) {
    throw new RuntimeException("WebDriver must implement HasCapabilities");
  }

  Capabilities caps = ((HasCapabilities) driver).getCapabilities();
  return caps.getPlatform();
}
 
Example #22
Source File: TestClickAt.java    From selenium with Apache License 2.0 5 votes vote down vote up
private boolean isUsingNativeEvents() {
  if (!(selenium instanceof WrapsDriver)) {
    return false;
  }

  WebDriver driver = ((WrapsDriver) selenium).getWrappedDriver();
  if (!(driver instanceof HasCapabilities)) {
    return false;
  }

  Capabilities capabilities = ((HasCapabilities) driver).getCapabilities();
  return capabilities.is(CapabilityType.HAS_NATIVE_EVENTS);
}
 
Example #23
Source File: DefaultExtWebDriver.java    From JTAF-ExtWebDriver with Apache License 2.0 5 votes vote down vote up
@Override
public String getBrowserName() {
	if (wd != null) {
		Capabilities capabilities = ((HasCapabilities) wd)
				.getCapabilities();
		if (capabilities != null) {
			return capabilities.getBrowserName();
		}
		return null;
	}
	return null;
}
 
Example #24
Source File: WebDriverUtils.java    From Selenium-Foundation with Apache License 2.0 5 votes vote down vote up
/**
 * Get the capabilities of the specified search context
 * 
 * @param context search context
 * @return context capabilities
 */
public static Capabilities getCapabilities(final SearchContext context) {
    WebDriver driver = getDriver(context);
    
    if (driver instanceof HasCapabilities) {
        return ((HasCapabilities) driver).getCapabilities();
    } else {
        throw new UnsupportedOperationException("The specified context is unable to describe its capabilities");
    }
}
 
Example #25
Source File: DelegatingWebDriver.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public Capabilities getCapabilities()
{
    if (wrappedDriver instanceof HasCapabilities)
    {
        return ((HasCapabilities) wrappedDriver).getCapabilities();
    }
    throw new IllegalStateException(DRIVER_NOT_IMPLEMENT_HAS_CAPABILITIES);
}
 
Example #26
Source File: WebDriverFactory.java    From vividus with Apache License 2.0 5 votes vote down vote up
private WebDriver createWebDriver(WebDriver webDriver)
{
    WebDriver driver = new TextFormattingWebDriver(webDriver);
    timeoutConfigurer.configure(driver.manage().timeouts());

    LOGGER.atInfo()
          .addArgument(() -> jsonUtils
                  .toPrettyJson(WebDriverUtil.unwrap(driver, HasCapabilities.class).getCapabilities().asMap()))
          .log("Session capabilities:\n{}");
    return driver;
}
 
Example #27
Source File: WebDriverFactoryTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testGetWebDriverWithWebDriverTypeWOBinary() throws Exception
{
    mockCapabilities((HasCapabilities) driver);
    WebDriverConfiguration configuration = new WebDriverConfiguration();
    WebDriverType webDriverType = mock(WebDriverType.class);
    webDriverFactory.setWebDriverType(webDriverType);
    injectConfigurations(webDriverType, configuration);
    DesiredCapabilities desiredCapabilities = mock(DesiredCapabilities.class);
    when(webDriverType.getWebDriver(new DesiredCapabilities(), configuration)).thenReturn(driver);
    Timeouts timeouts = mockTimeouts(driver);
    assertEquals(driver, ((WrapsDriver) webDriverFactory.getWebDriver(desiredCapabilities)).getWrappedDriver());
    verify(timeoutConfigurer).configure(timeouts);
    assertLogger();
}
 
Example #28
Source File: WebDriverManagerTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private WebDriver mockWebDriverHavingCapabilities(Map<String, Object> capabilities)
{
    Capabilities capabilitiesMock = mock(Capabilities.class);
    capabilities.forEach((capabilityType, capabilityValue) ->
            setCapabilities(capabilitiesMock, capabilityType, capabilityValue));

    WebDriver webDriver = mockWebDriverHavingCapabilities();
    when(((HasCapabilities) webDriver).getCapabilities()).thenReturn(capabilitiesMock);
    return webDriver;
}
 
Example #29
Source File: WebDriverManagerTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void shouldNotResizeElectronApps()
{
    webDriverManager.setElectronApp(true);
    WebDriver webDriver = mock(WebDriver.class, withSettings().extraInterfaces(HasCapabilities.class));
    BrowserWindowSize browserWindowSize = mock(BrowserWindowSize.class);
    webDriverManager.resize(browserWindowSize);
    verify(webDriver, never()).manage();
    verifyNoInteractions(webDriverProvider);
}
 
Example #30
Source File: WebDriverManagerTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testPerformActionInNativeContext()
{
    MobileDriver<?> mobileDriver = mock(MobileDriver.class, withSettings().extraInterfaces(HasCapabilities.class));
    Set<String> contexts = new HashSet<>();
    contexts.add(WEBVIEW_CONTEXT);
    contexts.add(NATIVE_APP_CONTEXT);
    mockMobileDriverContext(mobileDriver, WEBVIEW_CONTEXT, contexts);
    WebDriverManager spy = spyIsMobile(true);
    spy.performActionInNativeContext(webDriver -> assertEquals(mobileDriver, webDriver));
    verify(mobileDriver).context(NATIVE_APP_CONTEXT);
    verify(mobileDriver).context(WEBVIEW_CONTEXT);
}