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

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

With Sauce Labs you can run automated tests of your web apps on a variety of operating system/browser versions for desktop and mobile browsers. This topic provides an overview of setting up and running an automated Selenium test, with example test scripts that show how to set your connection and authentication to Sauce Labs, set desired capabilities for your tests, and make sure that the Sauce Labs browser cloud can connect to your app.

Set Up

  • You need a Sauce Labs account
  • You need to have a Selenium environment already set up on your local machine to run automated tests on Sauce Labs. If you need help with that, you can find setup instructions for popular programming languages in the demo directories (for example, demo-java) of the Sauce Labs Training repository on GitHub
  • You should already have a Selenium script that you run locally, or remotely on a Selenium grid or another service, that you want to update to run on Sauce Labs. If you don't, you can find example scripts that are already set up to run on Sauce using the Sauce Labs demo app, and that you can modify to set up your own tests, in the demo directories (for example, demo-java) of the Sauce Labs Training repository on GitHub.  
  • The web app you want to test must be accessible over the Internet for our virtual machines to be able to connect to it. If it's on your local machine or behind a firewall, you'll need to set up and use Sauce Connect Proxy

Log in to Sauce Labs to Run the Tests

Before you start modifying your existing test scripts or the examples, you should log into Sauce Labs with your username and password, and navigate to Dashboard > Automated Tests. As you modify the scripts, you can verify that the changes are valid by running the script on Sauce and making sure that it executes and completes on the dashboard.

Set the RemoteWebDriver Connection

If you have an existing Selenium script that you want to update to run on Sauce Labs, the first thing you need to do is to set the RemoteWebDriver to connect to the Sauce Labs browser cloud. For example, if your Selenium test is written in Java, you would set the connection to Sauce Labs like this:

RemoteWebDriver Java Example
 driver = new RemoteWebDriver(new URL("http://ondemand.saucelabs.com:80/wd/hub"), capabilities);

The example scripts in the next section are already set to connect to the Sauce Labs US data center. 

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

Desktop Browser and Virtual Device Cloudhttps://ondemand.saucelabs.com/wd/hub

Real Devices:  

  • Unified Platform: https://ondemand.us-west-1.saucelabs.com
  • Test Object: https://us1.appium.testobject.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: https://api.us-west-1.saucelabs.com/v1
  • Real Devices on Unified Platform: https://api.us-west-1.saucelabs.com/v1/rdc
  • Real Devices on Test Object: https://app.testobject.com/api/rest/

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.

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

Real Devices:

  • Unified Platform: https://ondemand.eu-central-1.saucelabs.com
  • Test Object: https://eu1.appium.testobject.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:

  • Virtual Devices and Desktops: https://api.eu-central-1.saucelabs.com/v1
  • Real Devices on Unified Platform: https://api.eu-central-1.saucelabs.com/v1/rdc
  • Real Devices on Test Object: https://app.testobject.com/api/rest/

IP Range:

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



 Click here to view US Data Center (Headless) endpoints

For more information on Sauce Headless, including a full test walkthroughs, check out Getting Started with Sauce Headless.

Desktop Browser and Virtual Device Cloudhttps://ondemand.us-east-1.saucelabs.com/wd/hub

Real Devices: n/a

Sauce Connect Proxy https://us-east-1.saucelabs.com/rest/v1 (specify with -x argument)

SSO:

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

REST API:

  • Virtual Devices and Desktops: https://us-east-1.saucelabs.com/rest/v1
  • Real Devices: n/a

IP Range:

TBD


Verify Your Authentication Credentials

Once you've set the RemoteWebDriver connection to Sauce Labs, you need to add your username and access key for Sauce Labs to your test script, as shown in the examples below. You can find the access key in the Account Profile page of the Sauce Labs web interface:

  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.

If you want to make sure your credentials work without having to update an existing script, copy and paste your credentials into the code as indicated in the appropriate example script, and then run it from your local machine. This will launch a test to open a browser, connect to the Sauce Labs sample app, and then close the browser and quit the test. 

 Click here to view the Java example

import org.junit.jupiter.api.*;

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

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
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 java.net.MalformedURLException;
import java.net.URL;


public class Module1JunitTest {
    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 on some 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-Junit5");

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

        /** 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("https://ondemand.saucelabs.com/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));

        //Assert that the inventory page displayed appropriately
        Boolean result = driver.findElements(inventoryPageLocator).size() > 0;
        assertTrue(result);

        /**
         * Here we teardown the driver session and send the results to Sauce Labs
         */
        if (result){
            ((JavascriptExecutor)driver).executeScript("sauce:job-result=passed");
        }
        else {
            ((JavascriptExecutor)driver).executeScript("sauce:job-result=failed");
        }
        driver.quit();

    }

}

 Click here to view the C# example

Not found

Could not read the file SauceExamples/Web.Tests/OnboardingTests/InstantSauceTest.cs

 Click here to view the Python example

# Selenium 3.14+ doesn't enable certificate checking
import pytest
import os
from selenium import webdriver
from _pytest.runner import runtestprotocol


@pytest.fixture
def driver(request):
    sauce_username = "SAUCE_USERNAME"
    sauce_access_key = "SAUCE_ACCESS_KEY"
    remote_url = "https://ondemand.saucelabs.com:443/wd/hub"

    # the desired_capabilities parameter tells us which browsers and OS to spin up.
    desired_cap = {
        'platform': 'Mac OS X 10.13',
        'browserName': 'safari',
        'version': "11.1",
        'build': 'Onboarding Sample App - Python + Pytest',
        'name': '1-first-test',
        'username': sauce_username,
        'accessKey': sauce_access_key
    }

    # This creates a webdriver object to send to Sauce Labs including the desired capabilities
    browser = webdriver.Remote(remote_url, desired_capabilities=desired_cap)
    yield browser
    # This is where you tell Sauce Labs to stop running tests on your behalf.
    # It's important so that you aren't billed after your test finishes.
    browser.quit()


# Here is our actual test code. In this test we open the saucedemo app in chrome and assert that the title is correct.
def test_should_open_chrome(driver):
    driver.get("https://www.saucedemo.com")
    actual_title = driver.title
    expected_title = "Swag Labs"
    assert expected_title == actual_title

 Click here to view the Ruby example

Not found

Could not read the file spec/instant_sauce_test1_spec.rb

 Click here to view the JavaScript example

let webdriver = require('selenium-webdriver'),
    chai = require('chai'),
    assert = chai.assert,
    /* Change the username and accessKey to your Saucelabs.com credentials
    username = "SAUCE_USERNAME",
    accessKey = "SAUCE_ACCESS_KEY",*/
    username = process.env.SAUCE_USERNAME,
    accessKey = process.env.SAUCE_ACCESS_KEY,
    /* Base URL sets the target test application */
    baseUrl = "https://www.saucedemo.com",
    /* driver instantiates via callback */
    driver;

/* The describe() function is a way to group your tests together and set test suite parameters like timeouts */
/* The `x` in front of the describe() function indicates this test suite will be skipped. */
/* Enter your Sauce Labs credentials and then remove the `x` to run this test suite */

xdescribe('Instant Sauce Test Module 1', function() {
    /* There is latency when testing on Sauce Labs cloud, it's recommended to increase the default Timeout from 2000ms */
    this.timeout(40000);
    /* it represents an actual test, the parameters are the title of the test case */
    it('should-open-safari', function (done) {
        /* Instantiate a WebDriver and set browser capabilities */
        driver = new webdriver.Builder().withCapabilities({
            'browserName': 'safari',
            'platformName': 'macOS 10.13',
            'browserVersion': '11.1',
            /* Pass Sauce User Name and Access Key */
            'sauce:options': {
                'username': username,
                'accessKey': accessKey,
                'build': 'Onboarding Sample App - NodeJS + Mocha',
                'name': '1-first-test'
            }
        }).usingServer("https://ondemand.saucelabs.com:443/wd/hub").build();
        /* The driver navigates to the target application, stored in this variable baseUrl*/
        driver.get(baseUrl);
        /* The driver grabs the title of the web page and displays it in your console */
        driver.getTitle().then(function (title) {
            /* console.log("title is: " + title); */
            assert.equal(title, 'Swag Labs');
        });

        /* This sends the results to Sauce Labs.com. */
        /* `currentTest.state` is a part of the runner.js script in the Mocha library. */
        /* Documentation here: https://mochajs.org/api/runner.js.html  */
        driver.executeScript("sauce:job-result=" + (this.currentTest.state));

        /* This tears down the current WebDriver session and ends the test method*/
        driver.quit();
        done();
    });
});

Use Environment Variables for Authentication Credentials

It's a recommended Best Practice to use environment variables for your credentials, rather than hardcoding them into your scripts. This makes it easy to run a test written by anyone from your local machine or continuous integration server, and also prevents security issues with having your authentication credentials exposed in the script. After you've run your first test with hardcoded credentials, you should set it to use environment variables. Set up the environment variables on your local machine as shown in the Best Practices topic, and then you can incorporate them into your scripts as shown in these examples.

 Click here to view the Java example

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
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 Module2JunitTest {
    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 = "https://ondemand.saucelabs.com/wd/hub";

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

 Click here to view the C# example

Not found

Could not read the file SauceExamples/Web.Tests/OnboardingTests/InstantSauceTest2.cs

 Click here to view the Python example

import pytest
from selenium import webdriver
import os
from _pytest.runner import runtestprotocol


@pytest.fixture
def driver(request):
    sauce_username = os.environ["SAUCE_USERNAME"]
    sauce_access_key = os.environ["SAUCE_ACCESS_KEY"]
    remote_url = "https://ondemand.saucelabs.com:443/wd/hub"

    desired_cap = {
        'platform': 'Mac OS X 10.13',
        'browserName': 'safari',
        'version': '11.1',
        'build': 'Onboarding Sample App - Python + Pytest',
        'name': '2-user-site',
        'username': sauce_username,
        'accessKey': sauce_access_key
    }

    browser = webdriver.Remote(command_executor=remote_url, desired_capabilities=desired_cap)
    yield browser
    browser.quit()


# Here is our actual test code. In this test we open the saucedemo app in chrome and assert that the title is correct.
def test_should_open_chrome(driver):
    # Substitute 'http://www.saucedemo.com' for your own application URL
    driver.get("https://www.saucedemo.com")
    actual_title = driver.title
    expected_title = "Swag Labs"
    assert expected_title == actual_title

 Click here to view the Ruby example

Not found

Could not read the file spec/instant_sauce_test2_spec.rb

 Click here to view the JavaScript example

const promise = require('selenium-webdriver');
let expect = require('chai').expect;
let webdriver = require('selenium-webdriver');

promise.USE_PROMISE_MANAGER = false;
/* Use a run configuration and/or a bash profile to set your environment variables, */
/* for more information on how to do this, please visit:
https://wiki.saucelabs.com/display/DOCS/Best+Practice%3A+Use+Environment+Variables+for+Authentication+Credentials
*/
let username = process.env.SAUCE_USERNAME,
    accessKey = process.env.SAUCE_ACCESS_KEY,
    /* Change the baseURL to your application URL */
    baseUrl = "https://www.saucedemo.com",
    driver;

describe('Instant Sauce Test Module 2', function() {
    this.timeout(40000);
    beforeEach(async function () {
        driver = await new webdriver.Builder().withCapabilities({
            'browserName': 'safari',
            'platformName': 'macOS 10.13',
            'browserVersion': 'latest',
            'sauce:options': {
                'username': username,
                'accessKey': accessKey,
                'build': 'Onboarding Sample App - NodeJS + Mocha',
                'name': '2-user-site'
            }
        }).usingServer("https://ondemand.saucelabs.com/wd/hub").build();

        await driver.getSession().then(function (sessionid) {
            driver.sessionID = sessionid.id_;
        });
    });

    afterEach(async function() {
        await driver.executeScript("sauce:job-result=" + (this.currentTest.state));
        await driver.quit();
    });

    it('should-open-safari ', async function() {
        await driver.get(baseUrl);
        const title = await driver.getTitle();
        console.log('Page Title is: ' + title);
        expect(title).equals('Swag Labs');
    });
});

Add Desired Capabilities

Desired capabilities are the platform, operating system, and browser you want to test against. You can use the Platform Configurator tool to automatically generates the code snippets for these capabilities. 

  1. Go to the Platform Configurator.
  2. Under API, select Selenium.

    Selecting Desired Capabilities for Mobile Native Browser Tests

    To run a test against a mobile native browser, select Appium, select the mobile device you want to test with, and then select Web Testing.

  3. Select the operating system and browser you want to test against. 
  4. Under Copy Code, select the language you are using. 
    The Platform Configurator will generate the code snippet for the desired capabilities. 
  5. Click Copy.
  6. Paste the code into your Selenium test script, or into one of the example test scripts, and then run the test to see how the web app performs on that platform/OS/browser combination. If you use one of the example test scripts, the test will open the selected browser, load the Sauce Labs sample web app, and close the browser. 
 Click here to view the Java example

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.assertTrue;

public class Module3JunitTest {
    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";
        /**
         * In this exercise use the Platform Configurator, located here:
         * https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/
         * in order to replace the following DesiredCapabilities: browserName, platform, and version
         * For example, I chose to use Windows 10 with Chrome version 59.
         * Note: If you use Chrome version 61+ you must use the sauce:options capability.
         * More info here: https://wiki.saucelabs.com/display/DOCS/Selenium+W3C+Capabilities+Support+-+Beta
         */
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("username", sauceUserName);
        capabilities.setCapability("accessKey", sauceAccessKey);
        capabilities.setCapability("browserName", "Chrome");
        capabilities.setCapability("platform", "Windows 10");
        capabilities.setCapability("version", "59.0");
        capabilities.setCapability("build", "Onboarding Sample App - Java-Junit5");
        capabilities.setCapability("name", "3-cross-browser");

        /** 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();
    }
}

 Click here to view the C# example

Not found

Could not read the file SauceExamples/Web.Tests/OnboardingTests/InstantSauceTest3.cs

 Click here to view the Python example

# In the following examples we implement the pytest-examples and seleniumbase test frameworks
# pytest-examples docs: https://docs.pytest.org/en/latest/contents.html
# seleniumbase docs: https://github.com/seleniumbase/SeleniumBase
import pytest
import os
from selenium import webdriver
from _pytest.runner import runtestprotocol


@pytest.fixture
def driver(request):
    sauce_username = os.environ["SAUCE_USERNAME"]
    sauce_access_key = os.environ["SAUCE_ACCESS_KEY"]
    remote_url = "https://ondemand.saucelabs.com:443/wd/hub"
    # use sauce:options to handle all saucelabs.com-specific capabilities such as:
    # username, accesskey, build number, test name, timeouts etc.
    sauceOptions = {
        'screenResolution': '1280x768',
        'seleniumVersion': '3.141.59',
        'build': 'Onboarding Sample App - Python + Pytest',
        'name': '3-cross-browser',
        'username': sauce_username,
        'accessKey': sauce_access_key
    }
    # In ChromeOpts, we define browser and/or WebDriver capabilities such as
    # the browser name, browser version, platform name, platform version
    chromeOpts = {
        'platformName': 'Windows 10',
        'browserName': 'chrome',
        'browserVersion': 'latest',
        'goog:chromeOptions': {'w3c': True},
        'sauce:options': sauceOptions
    }

    browser = webdriver.Remote(command_executor=remote_url, desired_capabilities=chromeOpts)
    yield browser
    browser.quit()


# Here is our actual test code. In this test we open the saucedemo app in chrome and assert that the title is correct.
def test_should_open_chrome(driver):
    driver.get("https://www.saucedemo.com")
    actual_title = driver.title
    expected_title = "Swag Labs"
    assert expected_title == actual_title

 Click here to view the Ruby example

Not found

Could not read the file spec/instant_sauce_test3_spec.rb

 Click here to view the JavaScript example

const promise = require('selenium-webdriver');
let expect = require('chai').expect;
let webdriver = require('selenium-webdriver');

promise.USE_PROMISE_MANAGER = false;
/* Use a run configuration and/or a bash profile to set your environment variables,
for more information on how to do this, please visit:
https://wiki.saucelabs.com/display/DOCS/Best+Practice%3A+Use+Environment+Variables+for+Authentication+Credentials
 */
let username = process.env.SAUCE_USERNAME,
    accessKey = process.env.SAUCE_ACCESS_KEY,
    /* Change the baseURL to your application URL */
    baseUrl = "https://www.saucedemo.com",
    driver;


describe('Instant Sauce Test Module 3', function() {
    this.timeout(40000);
    /* Now we will add a beforeEach method using the Mocha framework in order to
    set prerequiste tasks for each test case, in this case we're setting the driver capabilities.
     */
    beforeEach(async function () {
        driver = await new webdriver.Builder().withCapabilities({
            'browserName': 'chrome',
            'platformName': 'Windows 10',
            'browserVersion': 'latest',
            /* required for w3c protocol */
            'goog:chromeOptions' : { 'w3c' : true },
            'sauce:options': {
                'username': username,
                'accessKey': accessKey,
                'build': 'Onboarding Sample App - NodeJS + Mocha',
                'name': '3-cross-browser'
            }
        }).usingServer("https://ondemand.saucelabs.com/wd/hub").build();

        await driver.getSession().then(function (sessionid) {
            driver.sessionID = sessionid.id_;
        });
    });

    /* Here we add any post-requisite tasks, such as sending the test results to Sauce Labs.com*/
    afterEach(async function() {
        await driver.executeScript("sauce:job-result=" + (this.currentTest.state));
        await driver.quit();
    });

    it('should open chrome ', async function() {
        await driver.get(baseUrl);
        const title = await driver.getTitle();
        console.log('Page Title is: ' + title);
        expect(title).equals('Swag Labs');
    });
});

Set the Web App to Test

The final step in setting up your Selenium tests on Sauce is to use the driver.get command to set the URL of the web app you want to test, as shown in this example. The example tests scripts are all set to run against the Sauce Labs demo app, so you can paste the URL for your web app in place of the saucedemo URL to make sure that the Sauce Labs browser cloud can connect to your app. If your app is hosted on your local machine or behind a firewall, you'll need to set up Sauce Connect Proxy, which launches a secure tunnel to establish the connection. 

driver.navigate().to("https://www.saucedemo.com");

Best Practices and Reporting Test Results

Now that you've been able to get a test running on Sauce, there are a few other modifications you can make to your scripts to incorporate testing best practices, and to also make sure that you can report Pass/Fail results to your dashboard. You can find more information on both of these topics under Best Practices for Running Tests and Setting Test Status to Pass or Fail. These example scripts show how to implement the best practices of using timeouts to control text execution times, annotating tests, and setting identifying information for your tests, as well as a way to send Pass/Fail results to the Sauce Labs dashboard. 

 Click here to view the Java example

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();
    }
}

 Click here to view the C# example

Not found

Could not read the file SauceExamples/Web.Tests/OnboardingTests/InstantSauceTest4.cs

 Click here to view the Python example

import pytest
import os
from selenium import webdriver
from _pytest.runner import runtestprotocol

@pytest.fixture
def driver(request):
    sauce_username = os.environ["SAUCE_USERNAME"]
    sauce_access_key = os.environ["SAUCE_ACCESS_KEY"]
    remote_url = "https://ondemand.saucelabs.com:443/wd/hub"

    sauceOptions = {
        'screenResolution': '1280x768',
        'seleniumVersion': '3.141.59',
        # best practices involve setting a build number for version control
        'build': 'Onboarding Sample App - Python + Pytest',
        'name': '4-best-practices',
        'username': sauce_username,
        'accessKey': sauce_access_key,
        # tags to filter test reporting.
        'tags': ['instant-sauce', 'pytest', 'module4'],
        # setting sauce-runner specific parameters such as timeouts helps
        # manage test execution speed.
        'maxDuration': 1800,
        'commandTimeout': 300,
        'idleTimeout': 1000,
    }

    chromeOpts = {
        'platformName': 'Windows 10',
        'browserName': 'chrome',
        'browserVersion': 'latest',
        'goog:chromeOptions': {'w3c': True},
        'sauce:options': sauceOptions
    }

    browser = webdriver.Remote(command_executor=remote_url, desired_capabilities=chromeOpts)
    yield browser
    browser.quit()


def test_should_open_chrome(driver):
    driver.get("https://www.saucedemo.com")
    actual_title = driver.title
    expected_title = "Swag Labs"
    assert expected_title == actual_title

 Click here to view the Ruby example

Not found

Could not read the file spec/instant_sauce_test4_spec.rb

 Click here to view the JavaScript example

const promise = require('selenium-webdriver');
let expect = require('chai').expect;
let webdriver = require('selenium-webdriver');

promise.USE_PROMISE_MANAGER = false;

let username = process.env.SAUCE_USERNAME,
    accessKey = process.env.SAUCE_ACCESS_KEY,
    /* Change the baseURL to your application URL */
    baseUrl = "https://www.saucedemo.com",
    tags = ["sauceDemo", "on-boarding", "node", "mocha" ],
    driver;


describe('Instant Sauce Test Module 4', function() {
    this.timeout(40000);

    beforeEach(async function () {
        driver = await new webdriver.Builder().withCapabilities({
            'browserName': 'chrome',
            'platformName': 'Windows 10',
            'browserVersion': 'latest',
            'goog:chromeOptions' : { 'w3c' : true },
            'sauce:options': {
                'username': username,
                'accessKey': accessKey,
                'build': 'Onboarding Sample App - NodeJS + Mocha',
                'name': '4-best-practices',
                /* As a best practice, set important test metadata and execution options
                such as build info, tags for reporting, and timeout durations.
                */
                'maxDuration': 3600,
                'idleTimeout': 1000,
                'tags': tags
            }
        }).usingServer("https://ondemand.saucelabs.com/wd/hub").build();

        await driver.getSession().then(function (sessionid) {
            driver.sessionID = sessionid.id_;
        });
    });

    afterEach(async function() {
        await driver.executeScript("sauce:job-result=" + (this.currentTest.state));
        await driver.quit();
    });

    it('should open chrome ', async function() {
        await driver.get(baseUrl);
        const title = await driver.getTitle();
        console.log('Page Title is: ' + title);
        expect(title).equals('Swag Labs');
    });
});

Video Demo

  • No labels