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-csharp/blob/master/SauceExamples/Web.Tests/OnboardingTests/InstantSauceTest.cs

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

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

Real Devices:  https://ondemand.us-west-1.saucelabs.com

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

SSO:

REST API 

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

Real Devices:  https://ondemand.eu-central-1.saucelabs.com

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

SSO:

REST API:

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-csharp/blob/master/SauceExamples/Web.Tests/OnboardingTests/InstantSauceTest2.cs

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

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-csharp/blob/master/SauceExamples/Web.Tests/OnboardingTests/InstantSauceTest4.cs

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

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. 

For more information, check out the example scripts in our GitHub repo.