Skip to end of metadata
Go to start of metadata

If you want to get up and running with Sauce Labs but don't have any Selenium test scripts, you can use the ones in this topic to see how how it works. All you need to do is add your Sauce Labs username and password, and then run the script from the local machine where you have your Selenium environment set up. When the script runs, it will connect to Sauce Labs using your authentication credentials, launch the browser set in the test script, load the Sauce Labs demo website, and then close the browser and quit the test.

After running the test, you can log into the Sauce Labs web interface to see the test listed on your dashboard, and view information about the test, including video, by clicking on the test name to view the Test Details page.

If you want to experiment with the sample script further, try using the Platform Configurator to change the Desired Capabilities of the test, or substitute the URL of the web app you want to test for the sauce.demo URL. 

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.

Prerequisites

Instant Test

Download this script from the GitHub repo to your local machine, provide the information for SAUCE_USERNAME and SAUCE_ACCESS_CODE as indicated in the script, and then save and run the script. If you log in to saucelabs.com before you run the script, you'll be able to watch the script's progress as it executes.

 Click here to view the example script

Clone from:https://github.com/saucelabs-training/demo-java/blob/master/intstant-web-tests/testng/InstantSauceTestNGTest1.java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import org.testng.Assert;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;

public class InstantSauceTestNGTest1 {
    private WebDriver driver;

    @Test
    public void shouldOpenSafari() throws MalformedURLException {

        /**
         * In this section, we will configure our SauceLabs credentials in order to run our tests on saucelabs.com
         */
        String sauceUserName = "SAUCE_USERNAME";
        String sauceAccessKey = "SAUCE_ACCESS_KEY";

        /**
         * In this section, we will configure our test to run a specific
         * browser/os combination in Sauce Labs
         */

        DesiredCapabilities capabilities = new DesiredCapabilities();

        //set your user name and access key to run tests in Sauce
        capabilities.setCapability("username", sauceUserName);

        //set your sauce labs access key
        capabilities.setCapability("accessKey", sauceAccessKey);

        //set browser to Safari
        capabilities.setCapability("browserName", "Safari");

        //set operating system to macOS version 10.13
        capabilities.setCapability("platform", "macOS 10.13");

        //set the browser version to 11.1
        capabilities.setCapability("version", "11.1");

        //set the build name of the application
        capabilities.setCapability("build", "Onboarding Sample App - Java");

        //set your test case name so that it shows up in Sauce Labs
        capabilities.setCapability("name", "1-first-test");

        /**
         * In this section, we will set the WebDriver to a Remote driver to run on sauce, and pass the capabilities
         * we just set. Then we perform som actions on the page before quitting the driver.
         */

        //create a new Remote driver that will allow your test to send
        // commands to the Sauce Labs grid so that Sauce can execute your tests
        /** 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("http://ondemand.saucelabs.com:80/wd/hub"), capabilities);

        //navigate to the url of the Sauce Labs Sample app
        driver.navigate().to("https://www.saucedemo.com");

        //Create an instance of a Selenium explicit wait so that we can dynamically wait for an element
        WebDriverWait wait = new WebDriverWait(driver, 5);

        //wait for the user name field to be visible and store that element into a variable
        By userNameFieldLocator = By.cssSelector("[type='text']");
        wait.until(ExpectedConditions.visibilityOfElementLocated(userNameFieldLocator));

        //type the user name string into the user name field
        driver.findElement(userNameFieldLocator).sendKeys("standard_user");

        //type the password into the password field
        driver.findElement(By.cssSelector("[type='password']")).sendKeys("secret_sauce");

        //hit Login button
        driver.findElement(By.cssSelector("[type='submit']")).click();

        //Synchronize on the next page and make sure it loads
        By inventoryPageLocator = By.id("inventory_container");
        wait.until(ExpectedConditions.visibilityOfElementLocated(inventoryPageLocator));

        /**
         * In this section, we confirm the test ran correctly, howerver we don't post the results to saucelabs.com
         */
        //Assert that the inventory page displayed appropriately
        Assert.assertTrue(driver.findElement(inventoryPageLocator).isDisplayed());

        //Here we tear down the WebDriver session
        driver.quit();
    }
}

To find your Sauce Labs access key:

  1. Sign in to https://saucelabs.com with the username you set up when you created your account. 
    You will use this same username in your test script. 
  2. To find your access key:
    1. Click your name in the Account Profile menu in the upper-right corner.
    2. Click User Settings.
    3. Scroll down to Access Key and click Show.
    4. Enter the password you use to sign in to Sauce Labs to view the access key.
    5. Click the Copy icon.

IP Ranges and Data Center Endpoints
Sauce Labs has data centers in both the US and EU. You can access Sauce Labs services from either location by providing the appropriate URL endpoints, and whitelisting their associated IP ranges. 

 Click here to view US Data Center Endpoints

Virtual Device Cloudhttps://ondemand.saucelabs.com/wd/hub

Sauce Connect Proxyhttps://saucelabs.com/rest/v1 (do not need to specify, Sauce Connect Proxy will use this by default)

SSO:

  • https://saucelabs.com/sso/metadata for Signing/Encryption Certificate
  • https://saucelabs.com/sso/acs for Entity AssertionConsumeURL

REST API 

  • Virtual Devices and Desktops: api.us-west-1.saucelabs.com/v1
  • Real Devices: api.us-west-1.saucelabs.com/v1/rdc

IP Ranges:

162.222.72.0/21 (this is equivalent to the range 162.222.72.1 – 162.222.79.254)
66.85.48.0/21 (this is equivalent to the range 66.85.48.0 - 66.85.55.255)

 Click here to view EU Data Center endpoints

For more information, including framework configuration for the European data center, check out Sauce Labs European Data Center Configuration Information.

Virtual Device Cloudhttps://ondemand.eu-central-1.saucelabs.com/wd/hub

Sauce Connect Proxyhttps://eu-central-1.saucelabs.com/rest/v1 (specify with -x argument)

SSO:

  • https://eu-central-1.saucelabs.com/sso/metadata for Signing/Encryption Certificate
  • https://eu-central-1.saucelabs.com/sso/acs for Entity AssertionConsumeURL

REST API: https://eu-central-1.saucelabs.com/rest

IP Range:

185.94.24.0/22 (this is equivalent to the range 185.94.24.0 - 185.94.27.255


Instant Test with Environment Variables

This example script follows the best practice of using environment variables in place of hardcoded authentication credentials. Once you've been able to successfully run the instant test with hardcoded credentials, you can use this test to make sure that you've correctly set up your environment variables for authentication.

 Click here to view the example script

Clone from: https://github.com/saucelabs-training/demo-java/blob/master/intstant-web-tests/testng/InstantSauceTestNGTest2.java

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
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;

public class InstantSauceTestNGTest2 {

    private WebDriver driver;

    @Test
    public void shouldOpenSafari() 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 = System.getenv("SAUCE_URL");

        /**
         * In this section, we will configure our test to run on some specific
         * browser/os combination in Sauce Labs.*/
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("username", sauceUserName);
        capabilities.setCapability("accessKey", sauceAccessKey);
        capabilities.setCapability("browserName", "Safari");
        capabilities.setCapability("platform", "macOS 10.13");
        capabilities.setCapability("version", "11.1");
        capabilities.setCapability("name", "2-user-site");

        /**
         * In this section, we set the Remote WebDriver to run on Sauce Labs, and pass the capabilities.
         * Then we perform some actions on an application.
         * For this script, enter in your application's URL in place of 'https://www.saucedemo.com'. */

        /** 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);
        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. */
    @AfterMethod
    public void cleanUpAfterTestMethod(ITestResult result) {
        ((JavascriptExecutor)driver).executeScript("sauce:job-result=" + (result.isSuccess() ? "passed" : "failed"));
        driver.quit();
    }
}

Instant Test with Best Practices and Sauce Labs Reporting

This example script illustrates the use of several best practices in test design, and will report Pass/Fail status to the Sauce Labs dashboard.

 Click here to view the example script

Clone from: https://github.com/saucelabs-training/demo-java/blob/master/intstant-web-tests/testng/InstantSauceTestNGTest4.java

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.MalformedURLException;
import java.net.URL;

import static org.junit.jupiter.api.Assertions.*;

public class InstantSauceJunitTest2 {
    private WebDriver driver;

    @Test
    public void shouldOpenSafari() 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 = System.getenv("SAUCE_URL");

        /**
         * In this section, we will configure our test to run on some specific
         * browser/os combination in Sauce Labs.*/
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("username", sauceUserName);
        capabilities.setCapability("accessKey", sauceAccessKey);
        capabilities.setCapability("browserName", "Safari");
        capabilities.setCapability("platform", "macOS 10.13");
        capabilities.setCapability("version", "11.1");
        capabilities.setCapability("build", "Onboarding Sample App - Java");
        capabilities.setCapability("name", "2-user-site");
        /**
         * In this section, we set the Remote WebDriver to run on Sauce Labs, and pass the capabilities.
         * Then we perform some actions on an application.
         * For this script, enter in your application's URL in place of 'https://www.saucedemo.com'. */

        /** 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);
        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=" + (true ? "passed" : "failed"));
        driver.quit();
    }
}

Running Local Tests

Developing websites/apps within your local network is secure and efficient. The drawback to this method is that local assets are not publicly-accessible on the Internet, so the browsers/devices in the Sauce Labs cloud can't load and test your app. The solution is to use Sauce ConnectSauce Connect is a proxy server that creates a secure tunnel connection between the Sauce Labs virtual machine that runs your test and your local  network. You can also use Sauce Connect to test applications and websites that are located within your corporate firewall. Sauce Connect is not required to run tests on Sauce Labs, only in situations where the application or website you want to test is not publicly accessible. 

Running Tests in Parallel

Now that you’re running tests on Sauce, you may wonder how you can run your tests faster. One way to increase speed is by running tests in parallel across multiple virtual machines.

You can run your tests in parallel at two levels, and you can run your tests in parallel across multiple browsers. For example, if you have 10 tests and want to run on five browsers, this would be parallelism of five. You can also run tests across browsers and each test in parallel. Using our previous example this would be more like 50 parallel tests. Doing this requires that your tests are written in a way that they do not collide with one another, as described in our Best Practice topics avoiding external test dependencies and avoiding dependencies between tests.

Check out Using Frameworks to Run Tests in Parallel for more information, and examples of framework setups for Java, Python, and other programming languages.