The Sauce Labs Cookbook

Sauce Headless

Front End Performance Testing

Analytics

External Resources

More Info


Page tree
Skip to end of metadata
Go to start of metadata

This script illustrates the basic set up of a test that runs in the Sauce Labs virtual browser cloud. It includes using environment variables for authentication credentials, using tags and build numbers for test result management, and reporting the Pass/Fail status of the test to the Sauce Labs dashboard.

Example Only

The code in this topic is presented as an example only, since your tests and testing environments may require specialized scripting. This information should be taken only as an illustration of how you could set up your tests with Sauce Labs, and is not directly supported by Sauce.

See the following sections for more information.

What You'll Need

Setup Example Script

When this script runs, it opens the browser specified in the script, navigates to the saucelabs.demo web app, and then closes the browser. If you want to run this script using your Sauce Labs credentials and have it navigate to your own web app:

  1. Follow the instructions in Best Practice: Use Environment Variables for Authentication Credentials to set up your Sauce Labs account access.
  2. Enter the URL for the web app you want to test in the place of saucedemo.com.
  3. Once you've been able to run the test against your web app, you can use the Platform Configurator to experiment with changing the desired capabilities of the test. 

You can clone this script from the saucelabs-training repository on GitHub: https://github.com/saucelabs-training/demo-java

There are examples using both Junit and TestNG frameworks, change directories to the relevant module before running your tests:

  • https://github.com/saucelabs-training/demo-java/blob/master/on-boarding-modules/junit/src/test/java/Module4JunitTest.java

     Click here to view the full script

    import org.junit.jupiter.api.*;
    
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.MutableCapabilities;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Arrays;
    import java.util.List;
    
    import static org.junit.jupiter.api.Assertions.*;
    
    
    public class Module4JunitTest {
        private WebDriver driver;
    
        @Test
        public void shouldOpenChrome() throws MalformedURLException {
            /** Here we set environment variables from your local machine, or IntelliJ run configuration,
             *  and store these values in the variables below. Doing this is a best practice in terms of test execution
             *  and security. If you're not sure how to use env variables, refer to this guide -
             * https://wiki.saucelabs.com/display/DOCS/Best+Practice%3A+Use+Environment+Variables+for+Authentication+Credentials
             * or check junit5-README.md */
            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.
             */
            List<String> tags = Arrays.asList("sauceDemo", "demoTest", "module4", "javaTest");
            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-Junit5");
    
            /** 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);
            /** Don't forget to enter in your application's URL in place of 'https://www.saucedemo.com'. */
            driver.navigate().to("https://www.saucedemo.com");
            assertTrue(true);
        }
    
        /**
         * Below we are performing 2 critical actions. Quitting the driver and passing
         * the test result to Sauce Labs user interface.
         */
        @AfterEach
        public void cleanUpAfterTestMethod() {
            ((JavascriptExecutor) driver).executeScript("sauce:job-result=" + ("passed"));
            driver.quit();
        }
    }

  • https://github.com/saucelabs-training/demo-java/blob/master/on-boarding-modules/testng/src/test/java/Module4TestNGTest.java

     Click here to view the full script

    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.MutableCapabilities;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import org.testng.Assert;
    import org.testng.ITestResult;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.Test;
    
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Arrays;
    import java.util.List;
    
    public class Module4TestNGTest {
    
        private WebDriver driver;
    
        @Test
        public void shouldOpenChrome() throws MalformedURLException {
            /** Here we set environment variables from your local machine, or IntelliJ run configuration,
             *  and store these values in the variables below. Doing this is a best practice in terms of test execution
             *  and security. If you're not sure how to use env variables, refer to this guide -
             * https://wiki.saucelabs.com/display/DOCS/Best+Practice%3A+Use+Environment+Variables+for+Authentication+Credentials
             * or check testng-README.md */
    
            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);
            /** Don't forget to enter in your application's URL in place of 'https://www.saucedemo.com'. */
            driver.navigate().to("https://www.saucedemo.com");
            Assert.assertTrue(true);
    
        }
        /**
         * Below we are performing 2 critical actions. Quitting the driver and passing
         * the test result to Sauce Labs user interface using the Javascript Executor.
         */
        @AfterMethod
        public void cleanUpAfterTestMethod(ITestResult result) {
            ((JavascriptExecutor)driver).executeScript("sauce:job-result=" + (result.isSuccess() ? "passed" : "failed"));
            driver.quit();
        }
    }

Testing with a Proxy

If you're trying to run this script from behind a VPN or a corporate proxy, you must use either IPSec or Sauce Connect Proxy. Once you've downloaded and installed the relevant software, add the following capability to the test script:

capabilities.setCapability("tunnelIdentifier", "<tunnel ID>");

Running your Test

  1. Use maven to resolve any dependencies:

    $ mvn dependency:resolve
  2. Set your Sauce Labs Credentials in the following environment variables:

             * https://wiki.saucelabs.com/display/DOCS/Best+Practice%3A+Use+Environment+Variables+for+Authentication+Credentials
             * or check junit5-README.md */

  3. Use the following maven command to run the test:

    $ mvn test -Dtest=<java_class_name>