Skip to end of metadata
Go to start of metadata

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

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


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

Not found

Could not read the file intstant-web-tests/junit/InstantSauceJunitTest1.java

 Click here to view the C# example

using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using ExpectedConditions = SeleniumExtras.WaitHelpers.ExpectedConditions;

namespace Web.Tests.OnboardingTests
{
    [TestFixture]
    [Category("InstantSauceTest"), Category("NUnit"), Category("Instant")]
    public class InstantSauceTest
    {
        private IWebDriver _driver;
        [Test]
        public void ShouldOpenOnSafari()
        {
            /*Easy Option For Sauce Authentication:
            *You can hardcode the values like this example below, but the best practice is to use environment variables
            */
            var sauceUserName = "YOUR USER NAME";
            var sauceAccessKey = "YOUR ACCESS KEY";
            
            /*
             * In this section, we will configure our test to run on some specific
             * browser/os combination in Sauce Labs
             */
            var 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 your test case name so that it shows up in Sauce Labs
            capabilities.SetCapability("name", TestContext.CurrentContext.Test.Name);

            //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
            _driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"),
                capabilities, TimeSpan.FromSeconds(600));
            //navigate to the url of the Sauce Labs Sample app
            _driver.Navigate().GoToUrl("https://www.saucedemo.com");

            //Create an instance of a Selenium explicit wait so that we can dynamically wait for an element
            var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5));
            //wait for the user name field to be visible and store that element into a variable
            var userNameField = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("[type='text']")));
            //type the user name string into the user name field
            userNameField.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
            var inventoryPageLocator =
                wait.Until(ExpectedConditions.ElementIsVisible(By.Id("inventory_container")));
            //Assert that the inventory page displayed appropriately
            Assert.IsTrue(inventoryPageLocator.Displayed);
        }

        /*
         *Below we are performing 2 critical actions. Quitting the driver and passing
         * the test result to Sauce Labs user interface.
         */
        [TearDown]
        public void CleanUpAfterEveryTestMethod()
        {
            var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
            ((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
            _driver?.Quit();
        }
    }
}

 Click here to view the Python example

Not found

Could not read the file pytest/instant-sauce-pytest3.py

 Click here to view the Ruby example

require "selenium-webdriver"
require "rspec"
require "sauce_whisk"

describe "Instant_RSpec_Test3" do

=begin
    'before is an RSpec method that allows us to define prerequisite test execution steps such as:
        - defining the browser name
        - defining the browser version
        - defining the OS version and platform
        - defining the sauce:options capabilities, in this case the test name, the SauceLabs credentials, and the selenium version
=end

  before(:each) do |test|
    caps = {
        browser_name: 'chrome',
        # platform_version now becomes platform_name with the W3C bridge.
        # For more details see: https://www.rubydoc.info/gems/selenium-webdriver/Selenium/WebDriver/Remote/W3C/Capabilities
        platform_name: 'windows 10',
        browser_version: '71.0',
        # w3c is note enabled by default in Chrome, set the w3c setting to true
        "goog:chromeOptions" => {w3c: true},
        # use sauce:options to handle all saucelabs.com-specific capabilities such as:
        # username, accesskey, build number, test name, timeouts etc.
        "sauce:options" => {
            build: 'Onboarding Sample App - Ruby',
            name: '3-cross-browser',
            seleniumVersion: '3.141.59',
            username: ENV['SAUCE_USERNAME'],
            accessKey: ENV['SAUCE_ACCESS_KEY']
        }
    }
    @driver = Selenium::WebDriver.for(:remote,
                                      url: 'https://ondemand.saucelabs.com:443/wd/hub',
                                      desired_capabilities: caps)
  end
  it "should_open_chrome" do
    @driver.get('https://www.saucedemo.com')
    puts "title of webpage is: #{@driver.title}"
  end
=begin
    Here we use 'after' which is another RSpec method that handles all postrequisite test execution steps such as:
        - sending the results to SauceLabs.com
        - Tearing down the current RemoteWebDriver session so that the test VM doesn't hang
=end
  after(:each) do |example|
    # SauceWhisk::Jobs is a Ruby wrapper for the SauceLabs REST API. Here we're updating the job method
    # For more info please visit the Sauce Labs REST API Documentation: https://wiki.saucelabs.com/display/DOCS/Job+Methods
    SauceWhisk::Jobs.change_status(@driver.session_id, !example.exception)
    @driver.quit
  end
end

 Click here to view the JavaScript example

var webdriver = require('selenium-webdriver'),
    assert = require('assert'),
    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(function (done) {
        var testName = this.currentTest.title;
        driver = new webdriver.Builder().withCapabilities({
            'browserName': 'chrome',
            'platform': 'Windows 10',
            'version': '59.0',
            'username': username,
            'accessKey': accessKey,
            'build': 'Onboarding Sample App - NodeJS',
            'name': '3-cross-browser',
        }).usingServer("http://" + username + ":" + accessKey +
            "@ondemand.saucelabs.com:80/wd/hub").build();

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

    /* Here we add any post-requisite tasks, such as sending the test results to Sauce Labs.com*/
    afterEach(function (done) {
        driver.executeScript("sauce:job-result=" + (true ? "passed" : "failed"));
        driver.quit();
        done();
    });

    it('should-open-chrome ', function (done) {
        driver.get(baseUrl);
        driver.getTitle().then(function (title) {
            console.log("title is: " + title);
            assert(true);
            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

Not found

Could not read the file intstant-web-tests/junit/InstantSauceJunitTest2.java

 Click here to view the C# example

using System;
using System.Threading;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace Web.Tests.OnboardingTests
{
    [TestFixture]
    [Category("InstantSauceTest"), Category("NUnit"), Category("Instant")]
    public class InstantSauceTest2
    {
        private IWebDriver _driver;
        [Test]
        public void ShouldOpenOnSafari()
        {
            /*
             * Best Practice
             * Instead of using hardcoded username and access key, you should store
             * the credentials in environment variables on your system. Not sure how to do this?
             * This document will help:
             * https://wiki.saucelabs.com/display/DOCS/Best+Practice%3A+Use+Environment+Variables+for+Authentication+Credentials
             */
            var sauceUserName =
                Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);       
            var sauceAccessKey = 
                Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);

            /*
             * In this section, we will configure our test to run on some specific
             * browser/os combination in Sauce Labs
             */
            var 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", TestContext.CurrentContext.Test.Name);
            _driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"),
                capabilities, TimeSpan.FromSeconds(600));
            
            //TODO Please supply your publicly available web url in place of saucedemo.com
            //In the future, you will learn how to access private URLs
            _driver.Navigate().GoToUrl("https://www.saucedemo.com");
            
            //Hardcoded sleep just for demonstration purposes
            Thread.Sleep(10000);
            //This test will always pass for demonstration purposes
            Assert.IsTrue(true);
        }

        /*
         *Below we are performing 2 critical actions. Quitting the driver and passing
         * the test result to Sauce Labs user interface.
         */
        [TearDown]
        public void CleanUpAfterEveryTestMethod()
        {
            var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
            ((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
            _driver?.Quit();
        }
    }
}

 Click here to view the Python example

Not found

Could not read the file pytest/instant-sauce-pytest2.py

 Click here to view the Ruby example

require 'selenium/webdriver'
require 'rspec'

=begin
    The basic structure of RSpec uses 'describe' and 'it' to format our script in a conversational tone.
    'describe' represents the highest context, for example if we were testing authentication features it would say something like: '.authentication', and the 'it' would say something like 'should login'
=end
describe "Instant_RSpec_Test2" do
=begin
  'it' represents the business-level logic that we're testing,
  in this case we're checking to see if our test in SauceLabs session can open Chrome using W3C, then check the title page.
=end
  it "should_open_safari" do |test|

    caps = {
        # the caps object allows us to pass test metadata to the VM such as:
        # broswer_name, platform_version, browser_version, etc.
        browser_name: 'Safari',
        platform_version: 'macOS 10.13',
        browser_version: '11.1',
        # the sauce:options field allows us to define sauce labs-specific test parameters
        # such as: sauce username and access key, timeouts, selenium version etc.
        "sauce:options" => {
            build: 'Onboarding Sample App - Ruby',
            name: '2-user-site',
            seleniumVersion: '3.141.59',
            username: ENV['SAUCE_USERNAME'],
            accessKey: ENV['SAUCE_ACCESS_KEY']
        }
    }
    driver = Selenium::WebDriver.for(:remote,
                                     url: 'https://ondemand.saucelabs.com:443/wd/hub',
                                     desired_capabilities: caps)
    driver.get('https://www.saucedemo.com')
    puts "title of webpage is: #{driver.title}"
    driver.quit
  end
end

 Click here to view the JavaScript example

var webdriver = require('selenium-webdriver'),
    /* 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
     */
    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 1', function() {
    this.timeout(40000);
    it('should-open-safari', function (done) {
        driver = new webdriver.Builder().withCapabilities({
            'browserName': 'safari',
            'platform': 'macOS 10.13',
            'version': '11.1',
            'username': username,
            'accessKey': accessKey,
            'build': 'Onboarding Sample App - NodeJS',
            'name': '2-user-site',
        }).usingServer("http://" + username + ":" + accessKey +
            "@ondemand.saucelabs.com:80/wd/hub").build();

        driver.get(baseUrl);
        driver.getTitle().then(function (title) {
            console.log("title is: " + title);
        });
        driver.quit();
        done();
    });
});

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

Not found

Could not read the file intstant-web-tests/junit/InstantSauceJunitTest3.java

 Click here to view the C# example

using System;
using System.Threading;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace Web.Tests.OnboardingTests
{
    [TestFixture]
    [Category("InstantSauceTest"), Category("NUnit"), Category("Instant")]
    public class InstantSauceTest3
    {
        private IWebDriver _driver;
        [Test]
        public void ShouldOpenOnDifferentBrowser()
        {
            var sauceUserName =
                Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);       
            var sauceAccessKey = 
                Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);

            /*
             * TODO use the Platform Configurator from Sauce Labs to configure your test to run on 
             * another browser/OS combination: https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/
             * Paste that code below.
             */
            DesiredCapabilities caps = new DesiredCapabilities();
            caps.SetCapability("browserName", "MicrosoftEdge");
            caps.SetCapability("platform", "Windows 10");
            caps.SetCapability("version", "16.16299");

            //Make sure that you leave this information alone when updating the DesiredCaps above
            caps.SetCapability("username", sauceUserName);
            caps.SetCapability("accessKey", sauceAccessKey);
            caps.SetCapability("name", TestContext.CurrentContext.Test.Name);
            _driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"),
                caps, TimeSpan.FromSeconds(600));
            
            //TODO Please supply your publicly available web url in place of saucedemo.com
            //In the future, you will learn how to access private URLs
            _driver.Navigate().GoToUrl("https://www.saucedemo.com");
            
            //Hardcoded sleep just for demonstration purposes
            Thread.Sleep(10000);
            //This test will always pass for demonstration purposes
            Assert.IsTrue(true);
        }

        /*
         *Below we are performing 2 critical actions. Quitting the driver and passing
         * the test result to Sauce Labs user interface.
         */
        [TearDown]
        public void CleanUpAfterEveryTestMethod()
        {
            var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
            ((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
            _driver?.Quit();
        }
    }
}

 Click here to view the Python example

Not found

Could not read the file pytest/instant-sauce-pytest1.py

 Click here to view the Ruby example

=begin
    The 'require' definitions define which gems dependencies our script needs. In this example we have
    - The selenium-webdriver gem
    - The rspec framework gem
    - The sauce_whisk gem (a wrapper for the SauceLabs REST API)
=end
require 'selenium/webdriver'

caps = {
    platform: 'macOS 10.13',
    browserName: 'Safari',
    version: '11.1',
    build: 'Onboarding Sample App - Ruby',
    name: '1-first-test'
}
driver = Selenium::WebDriver.for(:remote,
                                 url: 'https://SAUCE_USERNAME:SAUCE_ACCESS_KEY@ondemand.saucelabs.com:443/wd/hub',
                                 desired_capabilities: caps)

driver.get('https://www.saucedemo.com')
puts "title of webpage is: #{driver.title}"
driver.quit

 Click here to view the JavaScript example

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

    /* Describe is a way to group your tests together and set test suite parameters like timetous */
describe('Instant Sauce Test Module 1', function() {
    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',
            'platform': 'macOS 10.13',
            'version': '11.1',
            /* Pass Sauce User Name and Access Key */
            'username': username,
            'accessKey': accessKey,
            'build': 'Onboarding Sample App - NodeJS',
            'name': '1-first-test',
        }).usingServer("http://" + username + ":" + accessKey +
            "@ondemand.saucelabs.com:80/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);
        });
        /* This tears down the current WebDriver session and ends the test method*/
        driver.quit();
        done();
    });
});

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

Not found

Could not read the file intstant-web-tests/junit/InstantSauceJunitTest4.java

 Click here to view the C# example

using System;
using System.Collections.Generic;
using System.Threading;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace Web.Tests.OnboardingTests
{
    /*
     * These scripts are simply for demonstration purposes.
     * They should not be used as an example of good practices for how to do test automation.
     */
    [TestFixture]
    [Category("InstantSauceTest"), Category("NUnit"), Category("Instant")]
    [Parallelizable]
    public class InstantSauceTest4
    {
        private IWebDriver _driver;
        private readonly string _sauceUserName =
            Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);
        private readonly string _sauceAccessKey =
            Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
        private IJavaScriptExecutor _javascriptExecutor;

        [Test]
        public void BestPractices()
        {
            /*
             * Commenting is one of the most powerful ways to debug your failed tests.
             * Using the sauce:context command below will allow you to place
             * comments inside of Sauce Labs logs that you can read and analyze.
             * Comment your important methods and your automation will drastically improve
             */
            _javascriptExecutor.ExecuteScript("sauce:context=Open SauceDemo.com");
            _driver.Navigate().GoToUrl("https://www.saucedemo.com");

            _javascriptExecutor.ExecuteScript("sauce:context=Sleep for 10000ms");
            Thread.Sleep(10000);
            Assert.IsTrue(true);
        }

        [SetUp]
        public void ExecuteBeforeEveryTest()
        {
            DesiredCapabilities caps = new DesiredCapabilities();
            caps.SetCapability("browserName", "Safari");
            caps.SetCapability("platform", "macOS 10.13");
            caps.SetCapability("version", "11.1");
            caps.SetCapability("username", _sauceUserName);
            caps.SetCapability("accessKey", _sauceAccessKey);
            caps.SetCapability("name", TestContext.CurrentContext.Test.Name);

            //Tags are an excellent way to control and filter your test automation
            //in Sauce Analytics. Get a better view into your test automation.
            var tags = new List<string> { "demoTest", "sauceDemo" };
            caps.SetCapability("tags", tags);
            /*
             * One of the most important things that you can do to get started
             * is to set timeout capabilities for Sauce based on your organizations needs
             */
            //How long is the whole test allowed to run?
            caps.SetCapability("maxDuration", 3600);
            //Selenium crash might hang a command, this is the max time allowed to wait for a Selenium command
            //600sec is a great start for majority of engineers
            caps.SetCapability("commandTimeout", 600);
            //How long can the browser wait before a new command?
            //1000sec is max and is a good timeout duration for most engineers
            caps.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.
             * You should always group your tests into builds.
             */
            caps.SetCapability("build", "SauceDemo");

            _driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"),
                caps, TimeSpan.FromSeconds(600));

            _javascriptExecutor = ((IJavaScriptExecutor)_driver);
        }


        [TearDown]
        public void CleanUpAfterEveryTestMethod()
        {
            var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
            _javascriptExecutor.ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
            _driver?.Quit();
        }
    }
}

 Click here to view the Python example

Not found

Could not read the file pytest/instant-sauce-pytest4.py

 Click here to view the Ruby example

require "selenium-webdriver"
require "rspec"
require "sauce_whisk"

describe "Instant_RSpec_Test4" do
  before(:each) do |test|
    caps = {
        browser_name: 'chrome',
        platform_name: 'windows 10',
        browser_version: '71.0',
        "goog:chromeOptions" => {w3c: true},
        "sauce:options" => {
            build: 'Onboarding Sample App - Ruby',
            name: '4-best-practices',
            seleniumVersion: '3.141.59',
            username: ENV['SAUCE_USERNAME'],
            accessKey: ENV['SAUCE_ACCESS_KEY'],
            # tags to filter test reporting.
            tags: ['instant-sauce', 'ruby-rspec', 'module4'],
            # setting sauce-runner specific parameters such as timeouts helps
            # manage test execution speed.
            maxDuration: 1800,
            commandTimeout: 300,
            idleTimeout: 1000
        }
    }
    @driver = Selenium::WebDriver.for(:remote,
                                      url: 'https://ondemand.saucelabs.com:443/wd/hub',
                                      desired_capabilities: caps)
  end
  it "should_open_chrome" do
    @driver.get('https://www.saucedemo.com')
    puts "title of webpage is: #{@driver.title}"
  end
  after(:each) do |example|
    SauceWhisk::Jobs.change_status(@driver.session_id, !example.exception)
    @driver.quit
  end
end

 Click here to view the JavaScript example

var webdriver = require('selenium-webdriver'),
    assert = require('assert'),
    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", "demoTest", "module4", "nodeTest"],
    driver;


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

    beforeEach(function (done) {
        var testName = this.currentTest.title;
        driver = new webdriver.Builder().withCapabilities({
            'browserName': 'chrome',
            'platform': 'Windows 10',
            'version': '59.0',
            'username': username,
            'accessKey': accessKey,
            'build': 'Onboarding Sample App - NodeJS',
            '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("http://" + username + ":" + accessKey +
            "@ondemand.saucelabs.com:80/wd/hub").build();

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

    afterEach(function (done) {
        driver.executeScript("sauce:job-result=" + (true ? "passed" : "failed"));
        driver.quit();
        done();
    });

    it('should-open-chrome', function (done) {
        driver.get(baseUrl);
        driver.getTitle().then(function (title) {
            console.log("title is: " + title);
            assert(true);
            done();
        });
    });
});

Video Demo

  • No labels