Java Code Examples for org.openqa.selenium.MutableCapabilities#setCapability()

The following examples show how to use org.openqa.selenium.MutableCapabilities#setCapability() . 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: CustomDriverProvider.java    From akita with Apache License 2.0 6 votes vote down vote up
/**
 * Задает capabilities для запуска Remote драйвера для Selenoid
 *
 * @param capabilities - capabilities для установленного браузера
 * @param remoteUrl    - url для запуска тестов, например http://remoteIP:4444/wd/hub
 * @return WebDriver
 */
private WebDriver getRemoteDriver(MutableCapabilities capabilities, String remoteUrl) {
    log.info("---------------run Remote Driver---------------------");
    Boolean isSelenoidRun = loadSystemPropertyOrDefault(SELENOID, true);
    if (isSelenoidRun) {
        capabilities.setCapability("enableVNC", true);
        capabilities.setCapability("screenResolution", String.format("%sx%s", loadSystemPropertyOrDefault(WINDOW_WIDTH, DEFAULT_WIDTH),
                loadSystemPropertyOrDefault(WINDOW_HEIGHT, DEFAULT_HEIGHT)));
        String sessionName = loadSystemPropertyOrDefault(SELENOID_SESSION_NAME, "");
        if (!sessionName.isEmpty()) {
            capabilities.setCapability("name", String.format("%s %s", sessionName, AkitaScenario.getInstance().getScenario().getName()));
        }
    }
    try {
        RemoteWebDriver remoteWebDriver = new RemoteWebDriver(
            URI.create(remoteUrl).toURL(),
            capabilities
        );
        remoteWebDriver.setFileDetector(new LocalFileDetector());
        return remoteWebDriver;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConvertAProxyCorrectly() {
  Proxy proxy = new Proxy();
  proxy.setHttpProxy("localhost:4444");

  MutableCapabilities caps = new DesiredCapabilities("foo", "1", Platform.LINUX);
  caps.setCapability(CapabilityType.PROXY, proxy);
  Map<String, ?> asMap = ImmutableMap.of("desiredCapabilities", caps);
  Command command = new Command(new SessionId("empty"), DriverCommand.NEW_SESSION, asMap);

  String json = convert(command.getParameters());

  JsonObject converted = new JsonParser().parse(json).getAsJsonObject();
  JsonObject capsAsMap = converted.get("desiredCapabilities").getAsJsonObject();

  assertThat(capsAsMap.get(CapabilityType.PROXY).getAsJsonObject().get("httpProxy").getAsString())
      .isEqualTo(proxy.getHttpProxy());
}
 
Example 3
Source File: TestBase.java    From demo-java with MIT License 5 votes vote down vote up
/**
 * Constructs a new {@link IOSDriver} instance which is configured to use the capabilities defined by the browser,
 * version and os parameters, and which is configured to run against ondemand.saucelabs.com, using
 * the username and access key populated by the {@link #authentication} instance.
 *
 * @param platformName      name of the platformName. (Android, iOS, etc.)
 * @param deviceName        name of the device
 * @param platformVersion   Os version of the device
 * @param appiumVersion     appium version
 * @param deviceOrientation device orientation
 * @return
 * @throws MalformedURLException if an error occurs parsing the url
 */
protected void createDriver(
        String platformName,
        String deviceName,
        String platformVersion,
        String appiumVersion,
        String deviceOrientation,
        String methodName)
        throws MalformedURLException, UnexpectedException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("platformName", platformName);
    capabilities.setCapability("platformVersion", platformVersion);
    capabilities.setCapability("deviceName", deviceName);
    capabilities.setCapability("browserName", "");
    capabilities.setCapability("deviceOrientation", deviceOrientation);
    capabilities.setCapability("appiumVersion", appiumVersion);
    capabilities.setCapability("name", methodName);
    capabilities.setCapability("build","Java-TestNG-Appium-iOS");
    capabilities.setCapability("app", app);

    if (buildTag != null) {
        capabilities.setCapability("build", buildTag);
    }

    // Launch remote browser and set it as the current thread
    iosDriver.set(new IOSDriver(
            new URL("https://" + authentication.getUsername() + ":" + authentication.getAccessKey() + seleniumURI +"/wd/hub"),
            capabilities));

    String id = ((RemoteWebDriver) getiosDriver()).getSessionId().toString();
    sessionId.set(id);
}
 
Example 4
Source File: DriverFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
static void addDefaultCapabilities(MutableCapabilities capabilities) {
    Set<String> capabilityNames = capabilities.getCapabilityNames();
    if (capabilityNames.contains(CapabilityType.BROWSER_NAME)
            && !capabilityNames.contains(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR)) {
        capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
    }
}
 
Example 5
Source File: MobileOptionsTest.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void acceptsExistingCapabilities() {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("deviceName", "Pixel");
    capabilities.setCapability("platformVersion", "10");
    capabilities.setCapability("newCommandTimeout", 60);

    mobileOptions = new MobileOptions<>(capabilities);

    assertEquals("Pixel", mobileOptions.getDeviceName());
    assertEquals("10", mobileOptions.getPlatformVersion());
    assertEquals(Duration.ofSeconds(60), mobileOptions.getNewCommandTimeout());
}
 
Example 6
Source File: DriverFactory.java    From restful-booker-platform with GNU General Public License v3.0 5 votes vote down vote up
private WebDriver prepareRemoteDriver(){
    if(System.getenv("SAUCE_USERNAME") == null){
        throw new RuntimeException("To use remote driver a Sauce lab account is required. Please assign your Sauce labs account name to the environmental variable 'sauce_username'");
    }

    if(System.getenv("SAUCE_ACCESS_KEY") == null){
        throw new RuntimeException("To use remote driver a Sauce lab account is required. Please assign your Sauce labs access key to the environmental variable 'sauce_access_key'");
    }

    String URL = "http://" + System.getenv("SAUCE_USERNAME") + ":" + System.getenv("SAUCE_ACCESS_KEY") + "@ondemand.saucelabs.com:80/wd/hub";

    FirefoxOptions firefoxOptions = new FirefoxOptions();

    firefoxOptions.setCapability("platformName", "Windows 10");
    firefoxOptions.setCapability("browserVersion", "65.0");

    MutableCapabilities sauceCaps = new MutableCapabilities();
    sauceCaps.setCapability("username", System.getenv("SAUCE_USERNAME"));
    sauceCaps.setCapability("accessKey", System.getenv("SAUCE_ACCESS_KEY"));
    sauceCaps.setCapability("seleniumVersion", "3.141.59");
    sauceCaps.setCapability("name", "Restful-booker-platform");
    firefoxOptions.setCapability("sauce:options", sauceCaps);

    try {
        return new RemoteWebDriver(new URL(URL), firefoxOptions);
    } catch (MalformedURLException e) {
        throw new RuntimeException("WARN: An error occurred attempting to create a remote driver connection. See the following error: " + e);
    }
}
 
Example 7
Source File: DistributorTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void creatingASessionAddsItToTheSessionMap() throws URISyntaxException {
  URI nodeUri = new URI("http://example:5678");
  URI routableUri = new URI("http://localhost:1234");

  LocalSessionMap sessions = new LocalSessionMap(tracer, bus);
  LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, null)
      .add(caps, new TestSessionFactory((id, c) -> new Session(id, nodeUri, c)))
      .build();

  Distributor distributor = new LocalDistributor(
      tracer,
      bus,
      new PassthroughHttpClient.Factory(node),
      sessions,
      null);
  distributor.add(node);

  MutableCapabilities sessionCaps = new MutableCapabilities(caps);
  sessionCaps.setCapability("sausages", "gravy");
  try (NewSessionPayload payload = NewSessionPayload.create(sessionCaps)) {
    Session returned = distributor.newSession(createRequest(payload)).getSession();

    Session session = sessions.get(returned.getId());
    assertThat(session.getCapabilities()).isEqualTo(sessionCaps);
    assertThat(session.getUri()).isEqualTo(routableUri);
  }
}
 
Example 8
Source File: DriverFactory.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Sets the logging level of the generated web driver.
 *
 * @param caps
 *            The web driver's MutableCapabilities (FirefoxOptions)
 * @param level
 *            The logging level
 */
private void setLoggingLevel(MutableCapabilities caps) {
    final LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.BROWSER, Level.ALL);
    logPrefs.enable(LogType.CLIENT, Level.OFF);
    logPrefs.enable(LogType.DRIVER, Level.OFF);
    logPrefs.enable(LogType.PERFORMANCE, Level.OFF);
    logPrefs.enable(LogType.PROFILER, Level.OFF);
    logPrefs.enable(LogType.SERVER, Level.OFF);
    caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
}
 
Example 9
Source File: CrossBrowserTest.java    From demo-java with MIT License 5 votes vote down vote up
private void createSauceDriver(MutableCapabilities capabilities, String methodName) {
    String username = System.getenv("SAUCE_USERNAME");
    String accesskey = System.getenv("SAUCE_ACCESS_KEY");

    //Create a map of capabilities called "sauce:options", which contain the info necessary to run on Sauce
    // Labs, using the credentials stored in the environment variables. Also runs using the new W3C standard.
    MutableCapabilities sauceOptions = new MutableCapabilities();
    sauceOptions.setCapability("username", username);
    sauceOptions.setCapability("accessKey", accesskey);
    sauceOptions.setCapability("seleniumVersion", "3.141.59");
    sauceOptions.setCapability("name", methodName);
    sauceOptions.setCapability("build", "Sample Headless Tests");

    //Assign the Sauce Options to the base capabilities
    capabilities.setCapability("sauce:options", sauceOptions);

    //Create a new RemoteWebDriver, which will initialize the test execution on Sauce Labs servers
    String SAUCE_REMOTE_URL = "https://ondemand.us-east-1.saucelabs.com/wd/hub";
    try {
        webDriver.set(new RemoteWebDriver(new URL(SAUCE_REMOTE_URL), capabilities));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    sessionId.set(((RemoteWebDriver)webDriver.get()).getSessionId().toString());

    // set current sessionId
    String id = ((RemoteWebDriver) getWebDriver()).getSessionId().toString();
    sessionId.set(id);
}
 
Example 10
Source File: SampleHeadlessSauceTest.java    From demo-java with MIT License 5 votes vote down vote up
@Test
public void main() throws MalformedURLException {
    String sauceUserName = System.getenv("SAUCE_USERNAME");
    String sauceAccessKey = System.getenv("SAUCE_ACCESS_KEY");
    String URL = "https://ondemand.us-east-1.saucelabs.com/wd/hub";

    ChromeOptions chromeOpts = new ChromeOptions();
    chromeOpts.setExperimentalOption("w3c", true);

    MutableCapabilities sauceOptions = new MutableCapabilities();
    sauceOptions.setCapability("username", sauceUserName);
    sauceOptions.setCapability("accessKey", sauceAccessKey);
    sauceOptions.setCapability("seleniumVersion", "3.141.59");
    sauceOptions.setCapability("name", "headless-chrome-test-java");
    sauceOptions.setCapability("build", "Sample Headless Tests");

    MutableCapabilities caps = new MutableCapabilities();
    caps.setCapability("goog:chromeOptions", chromeOpts);
    caps.setCapability("browserName", "chrome");
    caps.setCapability("browserVersion", "latest");
    caps.setCapability("platformName", "Linux");
    caps.setCapability("sauce:options", sauceOptions);

    driver = new RemoteWebDriver(new URL(URL), caps);

    /* Goes to Sauce Lab's demo page and prints title */

    driver.get("https://www.saucedemo.com");
    System.out.println("title of page is: " + driver.getTitle());
    Assert.assertEquals(driver.getTitle(), "Swag Labs" );
}
 
Example 11
Source File: TestBase.java    From demo-java with MIT License 5 votes vote down vote up
/**
 * Constructs a new {@link AndroidDriver} instance which is configured to use the capabilities defined by the browser,
 * version and os parameters, and which is configured to run against ondemand.saucelabs.com, using
 * the username and access key populated by the {@link #authentication} instance.
 *
 * @param platformName      name of the platformName. (Android, iOS, etc.)
 * @param deviceName        name of the device
 * @param platformVersion   Os version of the device
 * @param appiumVersion     appium version
 * @param deviceOrientation device orientation
 * @return
 * @throws MalformedURLException if an error occurs parsing the url
 */
protected void createDriver(
        String platformName,
        String deviceName,
        String platformVersion,
        String appiumVersion,
        String deviceOrientation,
        String methodName)
        throws MalformedURLException, UnexpectedException {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("platformName", platformName);
    capabilities.setCapability("platformVersion", platformVersion);
    capabilities.setCapability("deviceName", deviceName);
    capabilities.setCapability("browserName", "");
    capabilities.setCapability("deviceOrientation", deviceOrientation);
    capabilities.setCapability("appiumVersion", appiumVersion);
    capabilities.setCapability("name", methodName);
    capabilities.setCapability("app", app);
    capabilities.setCapability("build", "Java-TestNG-Appium-Android");

    if (buildTag != null) {
        capabilities.setCapability("build", buildTag);
    }

    // Launch remote browser and set it as the current thread
    androidDriver.set(new AndroidDriver(
            new URL("https://" + authentication.getUsername() + ":" + authentication.getAccessKey() + seleniumURI + "/wd/hub"),
            capabilities));

    String id = ((RemoteWebDriver) getAndroidDriver()).getSessionId().toString();
    sessionId.set(id);
}
 
Example 12
Source File: BaseWebDriverTest.java    From demo-java with MIT License 5 votes vote down vote up
private void createSauceDriver(MutableCapabilities capabilities, String methodName) {
    String username = System.getenv("SAUCE_USERNAME");
    String accesskey = System.getenv("SAUCE_ACCESS_KEY");

    //Create a map of capabilities called "sauce:options", which contain the info necessary to run on Sauce
    // Labs, using the credentials stored in the environment variables. Also runs using the new W3C standard.
    MutableCapabilities sauceOptions = new MutableCapabilities();
    sauceOptions.setCapability("username", username);
    sauceOptions.setCapability("accessKey", accesskey);
    sauceOptions.setCapability("seleniumVersion", "3.141.59");
    sauceOptions.setCapability("name", methodName);
    sauceOptions.setCapability("build", "parallel-TestNG-cross-browser-and-platform-demo");

    //Assign the Sauce Options to the base capabilities
    capabilities.setCapability("sauce:options", sauceOptions);

    //Create a new RemoteWebDriver, which will initialize the test execution on Sauce Labs servers
    String SAUCE_REMOTE_URL = "https://ondemand.saucelabs.com/wd/hub";
    try {
        webDriver.set(new RemoteWebDriver(new URL(SAUCE_REMOTE_URL), capabilities));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    sessionId.set(((RemoteWebDriver)webDriver.get()).getSessionId().toString());

    // set current sessionId
    String id = ((RemoteWebDriver) getWebDriver()).getSessionId().toString();
    sessionId.set(id);
}
 
Example 13
Source File: BaseWebDriverTest.java    From demo-java with MIT License 5 votes vote down vote up
private void createSauceDriver(MutableCapabilities capabilities, String methodName) {
    String username = System.getenv("SAUCE_USERNAME");
    String accesskey = System.getenv("SAUCE_ACCESS_KEY");

    //Create a map of capabilities called "sauce:options", which contain the info necessary to run on Sauce
    // Labs, using the credentials stored in the environment variables. Also runs using the new W3C standard.
    MutableCapabilities sauceOptions = new MutableCapabilities();
    sauceOptions.setCapability("username", username);
    sauceOptions.setCapability("accessKey", accesskey);
    sauceOptions.setCapability("seleniumVersion", "3.141.59");
    sauceOptions.setCapability("name", methodName);
    sauceOptions.setCapability("build", "parallel-TestNG-single-browser-demo");

    //Assign the Sauce Options to the base capabilities
    capabilities.setCapability("sauce:options", sauceOptions);

    //Create a new RemoteWebDriver, which will initialize the test execution on Sauce Labs servers
    String SAUCE_REMOTE_URL = "https://ondemand.saucelabs.com/wd/hub";
    try {
        webDriver.set(new RemoteWebDriver(new URL(SAUCE_REMOTE_URL), capabilities));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    sessionId.set(((RemoteWebDriver)webDriver.get()).getSessionId().toString());

    // set current sessionId
    String id = ((RemoteWebDriver) getWebDriver()).getSessionId().toString();
    sessionId.set(id);
}
 
Example 14
Source File: IOSOptionsTest.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void acceptsExistingCapabilities() {
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("deviceName", "Pixel");
    capabilities.setCapability("platformVersion", "10");
    capabilities.setCapability("newCommandTimeout", 60);

    iosOptions = new IOSOptions(capabilities);

    assertEquals("Pixel", iosOptions.getDeviceName());
    assertEquals("10", iosOptions.getPlatformVersion());
    assertEquals(Duration.ofSeconds(60), iosOptions.getNewCommandTimeout());
}
 
Example 15
Source File: TeasyCaps.java    From teasy with MIT License 4 votes vote down vote up
void setLoggingPrefs(MutableCapabilities options) {
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.BROWSER, Level.ALL);
    options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
}
 
Example 16
Source File: TestNGW3CFirefoxTest.java    From demo-java with MIT License 4 votes vote down vote up
/**
 * @BeforeMethod is a TestNG annotation that defines specific prerequisite test method behaviors.
In the example below we:
- Define Environment Variables for Sauce Credentials ("SAUCE_USERNAME" and "SAUCE_ACCESS_KEY")
- Define Firefox Options such as W3C protocol
- Define the "sauce:options" capabilities, indicated by the "sauceOpts" MutableCapability object
- Define the WebDriver capabilities, indicated by the "caps" DesiredCapabilities object
- Define the service URL for communicating with SauceLabs.com indicated by "sauceURL" string
- Set the URL to sauceURl
- Set the driver instance to a RemoteWebDriver
- Pass "url" and "caps" as parameters of the RemoteWebDriver
For more information visit the docs: http://static.javadoc.io/org.testng/testng/6.9.4/org/testng/annotations/BeforeMethod.html
 */
@BeforeMethod
public void setup(Method method) throws MalformedURLException {
    String username = System.getenv("SAUCE_USERNAME");
    String accessKey = System.getenv("SAUCE_ACCESS_KEY");
    String methodName = method.getName();

    /** FirefoxOptions allows us to set browser-specific behavior such as profile settings, headless capabilities, insecure tls certs,
     and in this example--the W3C protocol
     For more information see: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/firefox/FirefoxOptions.html */

    FirefoxOptions foxOpts = new FirefoxOptions();
    foxOpts.setCapability("w3c", true);

    /** The MutableCapabilities class  came into existence with Selenium 3.6.0 and acts as the parent class for
     all browser implementations--including the FirefoxOptions class extension.
     Fore more information see: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/MutableCapabilities.html */

    MutableCapabilities sauceOpts = new MutableCapabilities();
    sauceOpts.setCapability("name", methodName);
    sauceOpts.setCapability("build", "Java-W3C-Examples");
    sauceOpts.setCapability("seleniumVersion", "3.141.59");
    sauceOpts.setCapability("username", username);
    sauceOpts.setCapability("accessKey", accessKey);
    sauceOpts.setCapability("tags", "w3c-chrome-tests");

    /** Below we see the use of our other capability objects, 'foxOpts' and 'sauceOpts',
     defined in 'moz:firefoxOptions' and sauce:options respectively.
     */
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("moz:firefoxOptions",  foxOpts);
    caps.setCapability("sauce:options", sauceOpts);
    caps.setCapability("browserName", "firefox");
    caps.setCapability("browserVersion", "latest");
    caps.setCapability("platformName", "windows 10");

    /** Finally, we pass our DesiredCapabilities object 'caps' as a parameter of our RemoteWebDriver instance */
    String sauceUrl = "https://ondemand.saucelabs.com:443/wd/hub";
    URL url = new URL(sauceUrl);
    driver = new RemoteWebDriver(url, caps);
}
 
Example 17
Source File: TestNGW3CChromeTest.java    From demo-java with MIT License 4 votes vote down vote up
/**
 * @BeforeMethod is a TestNG annotation that defines specific prerequisite test method behaviors.
In the example below we:
- Define Environment Variables for Sauce Credentials ("SAUCE_USERNAME" and "SAUCE_ACCESS_KEY")
- Define Chrome Options such as W3C protocol
- Define the "sauce:options" capabilities, indicated by the "sauceOpts" MutableCapability object
- Define the WebDriver capabilities, indicated by the "caps" DesiredCapabilities object
- Define the service URL for communicating with SauceLabs.com indicated by "sauceURL" string
- Set the URL to sauceURl
- Set the driver instance to a RemoteWebDriver
- Pass "url" and "caps" as parameters of the RemoteWebDriver
For more information visit the docs: http://static.javadoc.io/org.testng/testng/6.9.4/org/testng/annotations/BeforeMethod.html
 */
@BeforeMethod
public void setup(Method method) throws MalformedURLException {
    String username = System.getenv("SAUCE_USERNAME");
    String accessKey = System.getenv("SAUCE_ACCESS_KEY");
    String methodName = method.getName();

    /** ChomeOptions allows us to set browser-specific behavior such as profile settings, headless capabilities, insecure tls certs,
     and in this example--the W3C protocol
     For more information see: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/chrome/ChromeOptions.html */

    ChromeOptions chromeOpts = new ChromeOptions();
    chromeOpts.setExperimentalOption("w3c", true);

    /** The MutableCapabilities class  came into existence with Selenium 3.6.0 and acts as the parent class for
     all browser implementations--including the ChromeOptions class extension.
     Fore more information see: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/MutableCapabilities.html */

    MutableCapabilities sauceOpts = new MutableCapabilities();
    sauceOpts.setCapability("name", methodName);
    sauceOpts.setCapability("build", "Java-W3C-Examples");
    sauceOpts.setCapability("seleniumVersion", "3.141.59");
    sauceOpts.setCapability("username", username);
    sauceOpts.setCapability("accessKey", accessKey);
    sauceOpts.setCapability("tags", "w3c-chrome-tests");

    /** Below we see the use of our other capability objects, 'chromeOpts' and 'sauceOpts',
     defined in ChromeOptions.CAPABILITY and sauce:options respectively.
     */
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(ChromeOptions.CAPABILITY,  chromeOpts);
    caps.setCapability("sauce:options", sauceOpts);
    caps.setCapability("browserName", "googlechrome");
    caps.setCapability("browserVersion", "latest");
    caps.setCapability("platformName", "windows 10");

    /** Finally, we pass our DesiredCapabilities object 'caps' as a parameter of our RemoteWebDriver instance */
    String sauceUrl = "https://ondemand.saucelabs.com:443/wd/hub";
    URL url = new URL(sauceUrl);
    driver = new RemoteWebDriver(url, caps);
}
 
Example 18
Source File: JUnit5W3CChromeTest.java    From demo-java with MIT License 4 votes vote down vote up
/**
 * @BeforeEach is a JUnit 5 annotation that defines specific prerequisite test method behaviors.
In the example below we:
- Define Environment Variables for Sauce Credentials ("SAUCE_USERNAME" and "SAUCE_ACCESS_KEY")
- Define Chrome Options such as W3C protocol
- Define the "sauce:options" capabilities, indicated by the "sauceOpts" MutableCapability object
- Define the WebDriver capabilities, indicated by the "caps" DesiredCapabilities object
- Define the service URL for communicating with SauceLabs.com indicated by "sauceURL" string
- Set the URL to sauceURl
- Set the driver instance to a RemoteWebDriver
- Pass "url" and "caps" as parameters of the RemoteWebDriver
For more information visit the docs: https://junit.org/junit5/docs/5.0.2/api/org/junit/jupiter/api/BeforeEach.html
 */

@BeforeEach
public void setup(TestInfo testInfo) throws MalformedURLException {
    String username = System.getenv("SAUCE_USERNAME");
    String accessKey = System.getenv("SAUCE_ACCESS_KEY");
    String methodName = testInfo.getDisplayName();

    /** ChomeOptions allows us to set browser-specific behavior such as profile settings, headless capabilities, insecure tls certs,
     and in this example--the W3C protocol
     For more information see: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/chrome/ChromeOptions.html */

    ChromeOptions chromeOpts = new ChromeOptions();
    chromeOpts.setExperimentalOption("w3c", true);

    /** The MutableCapabilities class  came into existence with Selenium 3.6.0 and acts as the parent class for
     all browser implementations--including the ChromeOptions class extension.
     Fore more information see: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/MutableCapabilities.html */

    MutableCapabilities sauceOpts = new MutableCapabilities();
    sauceOpts.setCapability("name", methodName);
    sauceOpts.setCapability("build", "Java-W3C-Examples");
    sauceOpts.setCapability("seleniumVersion", "3.141.59");
    sauceOpts.setCapability("username", username);
    sauceOpts.setCapability("accessKey", accessKey);
    sauceOpts.setCapability("tags", testInfo.getTags());


    /** Below we see the use of our other capability objects, 'chromeOpts' and 'sauceOpts',
     defined in ChromeOptions.CAPABILITY and sauce:options respectively.
     */
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(ChromeOptions.CAPABILITY,  chromeOpts);
    caps.setCapability("sauce:options", sauceOpts);
    caps.setCapability("browserName", "googlechrome");
    caps.setCapability("browserVersion", "latest");
    caps.setCapability("platformName", "windows 10");

    /** Finally, we pass our DesiredCapabilities object 'caps' as a parameter of our RemoteWebDriver instance */
    String sauceUrl = "https://ondemand.saucelabs.com:443/wd/hub";
    URL url = new URL(sauceUrl);
    driver = new RemoteWebDriver(url, caps);
}
 
Example 19
Source File: RemoteWebDriver.java    From selenium with Apache License 2.0 4 votes vote down vote up
protected void startSession(Capabilities capabilities) {
  Response response = execute(DriverCommand.NEW_SESSION(capabilities));

  Map<String, Object> rawCapabilities = (Map<String, Object>) response.getValue();
  MutableCapabilities returnedCapabilities = new MutableCapabilities();
  for (Map.Entry<String, Object> entry : rawCapabilities.entrySet()) {
    // Handle the platform later
    if (PLATFORM.equals(entry.getKey()) || PLATFORM_NAME.equals(entry.getKey())) {
      continue;
    }
    returnedCapabilities.setCapability(entry.getKey(), entry.getValue());
  }
  String platformString = (String) rawCapabilities.getOrDefault(PLATFORM,
                                                                rawCapabilities.get(PLATFORM_NAME));
  Platform platform;
  try {
    if (platformString == null || "".equals(platformString)) {
      platform = Platform.ANY;
    } else {
      platform = Platform.fromString(platformString);
    }
  } catch (WebDriverException e) {
    // The server probably responded with a name matching the os.name
    // system property. Try to recover and parse this.
    platform = Platform.extractFromSysProperty(platformString);
  }
  returnedCapabilities.setCapability(PLATFORM, platform);
  returnedCapabilities.setCapability(PLATFORM_NAME, platform);

  if (rawCapabilities.containsKey(SUPPORTS_JAVASCRIPT)) {
    Object raw = rawCapabilities.get(SUPPORTS_JAVASCRIPT);
    if (raw instanceof String) {
      returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, Boolean.parseBoolean((String) raw));
    } else if (raw instanceof Boolean) {
      returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, ((Boolean) raw).booleanValue());
    }
  } else {
    returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, true);
  }

  this.capabilities = returnedCapabilities;
  sessionId = new SessionId(response.getSessionId());
}
 
Example 20
Source File: Module4TestNGTest.java    From demo-java with MIT License 4 votes vote down vote up
@BeforeMethod
public void setupTestMethod() throws MalformedURLException {
    String sauceUserName = System.getenv("SAUCE_USERNAME");
    String sauceAccessKey = System.getenv("SAUCE_ACCESS_KEY");
    String sauceURL = "https://ondemand.saucelabs.com/wd/hub";

    /**
     * * Here we set the MutableCapabilities for "sauce:options", which is required for newer versions of Selenium
     * and the w3c protocol, for more info read the documentation:
     * https://wiki.saucelabs.com/display/DOCS/Selenium+W3C+Capabilities+Support+-+Beta */
    MutableCapabilities sauceOpts = new MutableCapabilities();
    sauceOpts.setCapability("username", sauceUserName);
    sauceOpts.setCapability("accessKey", sauceAccessKey);
    /** In order to use w3c you must set the seleniumVersion **/
    sauceOpts.setCapability("seleniumVersion", "3.141.59");
    sauceOpts.setCapability("name", "4-best-practices");

    /**
     * in this exercise we set additional capabilities below that align with
     * testing best practices such as tags, timeouts, and build name/numbers.
     *
     * Tags are an excellent way to control and filter your test automation
     * in Sauce Analytics. Get a better view into your test automation.
     */

    /** Tags are an excellent way to control and filter your test automation
     * in Sauce Analytics. Get a better view into your test automation.
     */
    List<String> tags = Arrays.asList("sauceDemo", "demoTest", "module4");
    sauceOpts.setCapability("tags", tags);

    /** Another of the most important things that you can do to get started
     * is to set timeout capabilities for Sauce based on your organizations needs. For example:
     * How long is the whole test allowed to run?*/
    sauceOpts.setCapability("maxDuration", 3600);
    /** A Selenium crash might cause a session to hang indefinitely.
     * Below is the max time allowed to wait for a Selenium command*/
    sauceOpts.setCapability("commandTimeout", 600);
    /** How long can the browser wait for a new command */
    sauceOpts.setCapability("idleTimeout", 1000);

    /** Setting a build name is one of the most fundamental pieces of running
     * successful test automation. Builds will gather all of your tests into a single
     * 'test suite' that you can analyze for results.
     * It's a best practice to always group your tests into builds. */
    sauceOpts.setCapability("build", "Onboarding Sample App - Java-TestNG");


    /** Required to set w3c protoccol **/
    ChromeOptions chromeOpts = new ChromeOptions();
    chromeOpts.setExperimentalOption("w3c", true);

    /** Set a second MutableCapabilities object to pass Sauce Options and Chrome Options **/
    MutableCapabilities capabilities = new MutableCapabilities();
    capabilities.setCapability("sauce:options", sauceOpts);
    capabilities.setCapability("goog:chromeOptions", chromeOpts);
    capabilities.setCapability("browserName", "chrome");
    capabilities.setCapability("platformVersion", "Windows 10");
    capabilities.setCapability("browserVersion", "latest");

    /** If you're accessing the EU data center, use the following endpoint:.
     * https://ondemand.eu-central-1.saucelabs.com/wd/hub
     * */
    driver = new RemoteWebDriver(new URL(sauceURL), capabilities);
}