Skip to end of metadata
Go to start of metadata

Sauce Labs is a cloud platform for executing automated and manual mobile and web tests. Sauce Labs supports running automated tests with Selenium WebDriver (for web applications) and Appium (for native and mobile web applications). This topic will provide you with an example of how to get your Python tests up and running on Sauce.

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

Before getting started, you should read the Best Practices for Running Tests.
  • You will need to install the Selenium WebDriver client driver to your local Python environment
    You can either download the driver from the link, or use pip to install it.

    pip install selenium
  • You should also install the Sauce Python client, which provides features for reporting job information to the Sauce Labs dashboard. 

    pip install sauceclient

Code Example

This Python example script executes a simple test to open a browser, navigate to the Sauce Labs demo web app, and then close the browser. It also incorporate a number of best practices, such as using environment variables for authentication credentials. You can clone this script directly from the saucelabs-training GitHub repo and modify it as you want to test your authentication credentials, set desired capabilities, and run tests against your own web app. Y
 Click here to view the example script

import pytest
import os
from selenium import webdriver
from _pytest.runner import runtestprotocol
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


@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",
        'name': 'Example Pytest4',
        "username": sauce_username,
        "accessKey": sauce_access_key,
        # best practices involve setting a build number for version control
        "build": "build-0.0.1",
        # 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
    }

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

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

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

Wait!

The explicit wait method tells the browser to wait a set amount of time (in seconds) for elements to appear on the page before giving up. Using explicit waits is one of our recommended best practices.

Analyzing the Code

If you look at the code closely, you'll see that basics for setting up a test to run on sauce are very straightforward, and really only require two elements.

It's very easy to get your existing Python tests up and running on Sauce. 

Set Sauce URL and Access Credentials

If you wanted to run a Selenium test on Selenium locally, you would initiate a driver for the browser you want to test against like this.

Running a Local Python Test
driver = webdriver.Firefox() 

To run a test on a remote service like Sauce Labs, all you need to change is your driver definition, make sure that the sauce_endpoint variable includes your Sauce USERNAME and ACCESSKEY, and then pass it two parameters: command_executor, which points to the Sauce cloud and uses your Sauce Labs authentication to log in, and desired_capabilties, which specifies the browsers and operating systems to run the tests against.

Running a Python Test Remotely on Sauce
# this is how you set up a test to run on Sauce Labs
desired_cap = {
    'platform': "Mac OS X 10.9",
    'browserName': "chrome",
    'version': "31",
}
username = os.environ['SAUCE_USERNAME']
access_key = os.environ['SAUCE_ACCESS_KEY']
driver = webdriver.Remote(
    command_executor='https://{}:{}@ondemand.saucelabs.com/wd/hub'.format(username, access_key),
    desired_capabilities=desired_cap)

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. 

 US Data Center

Virtual Device Cloud: https://ondemand.saucelabs.com/wd/hub
Sauce Connect Proxy: https://saucelabs.com/rest
REST API:  https://saucelabs.com/rest/v1
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)

Set Desired Capabilities

Once you have your tests set up to run in the Sauce cloud, you need to define the platform, browser, and version you want the test to run against, which is where desired capabilities come into play. 

desired_cap = {
    'platform': "Mac OS X 10.9",
    'browserName': "chrome",
    'version': "31",

You can manually enter the values you want for platformbrowsername, and version, or you can use the handy Platform Configurator to generate the desired_caps values for any combination of platform, browser, and browser version. 

Running the Test

  1. Copy the example code and save it into a file called first_test.py.
    Make sure your username and access key are included in the URL passed through to the command_executor.
  2. Open a command line terminal and navigate to the directory where the file is located.
  3. Execute the test:

    python first_test.py

    Check your dashboard and you will see that your test has just run on Sauce!

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.

Match Thread Count to Concurrency Limit

You should match your thread count to your concurrency limit, which is shown in the My Account section of your user profile information on the Sauce Labs dashboard.  


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

Reporting on Test Results

"Wait," you might be asking, "My test says 'Complete' but what happens if it fails?"

Unfortunately, Sauce has no way to determine whether your test passed or failed automatically, since it is determined entirely by your business logic. You can, however, tell Sauce about the results of our tests automatically using the Sauce python client and adding these lines to your test. 

# this authenticates you 
from sauceclient import SauceClient
sauce_client = SauceClient("YOUR_SAUCE_USERNAME", "YOUR_SAUCE_ACCESSKEY")

# this belongs in your test logic
sauce_client.jobs.update_job(driver.session_id, passed=True) 

You should also follow our recommended best practice of adding build numbers, tags, and other identifying information to your tests so you can easily find and manage them in your test results and archives pages