Sauce Labs Documentation v1.0
Sauce Labs Documentation v1.0
1. Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.1 Instant C# Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Instant JavaScript Unit Testing with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3 Instant Java Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.4 Instant Node.js Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.5 Instant PHP Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.6 Instant Python Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.7 Instant Ruby Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2. Known Issues and Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3. Introducing Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.1 A Tour of the Sauce Labs Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.2 Sauce Labs FAQs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.3 Sauce Labs Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.4 Supported Browsers and Operating Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4. Running Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.1 Tips and Best Practices for Running Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.1.1 Best Practices for Running Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.1.1.1 Best Practice: Avoid External Test Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.1.1.2 Best Practice: Avoid Dependencies between Tests to Run Tests in Parallel . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.1.1.3 Best Practice: Don't Use Brittle Locators in Your Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.1.1.4 Best Practice: Have a Retry Strategy for Handling Flakes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.1.1.5 Best Practice: Keep Functional Tests Separate from Performance Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.1.1.6 Best Practice: Use Build IDs, Tags, and Names to Identify Your Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.1.1.7 Best Practice: Use Environment Variables for Authentication Credentials . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.1.1.8 Best Practice: Use Explicit Waits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.1.1.9 Best Practice: Use the Latest Version of Selenium Client Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.1.1.10 Best Practices: Use Small, Atomic, Autonomous Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
4.1.2 Tips for Lean, Speedy Tests with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.1.3 Handling Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.1.3.1 Basic HTTP Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.1.3.2 Injecting Cookies to Bypass Authentication Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.1.3.3 Running an AutoIt Script as a Pre-run Executable to Handle Windows Security Authentication Dialogs . . . . 62
4.2 Pre-Run Executables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.2.1 Setting Up Pre-Run Executables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
4.3 Test Configuration and Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.3.1 Configuring Tests with the WebDriver API DesiredCapabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.3.2 Configuring Tests with the Sauce Labs REST API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.3.3 Configuring Tests with Selenium's JavaScript Executor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.3.4 Test Configuration Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.3.5 Examples of Desired Capabilities for iWebDriver and Appium iOS Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.4 Manual Testing with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.4.1 Running a Manual Testing Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
4.4.2 Starting Manual Tests from Automated Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
4.4.3 Troubleshooting Manual Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
4.5 Automated Testing with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.5.1 Troubleshooting Automated Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.5.2 Common Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.6 Mobile Testing with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
4.6.1 Mobile Testing with Appium . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
4.6.2 Support and Requirements for Mobile Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.6.2.1 Supported Android Emulators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
4.6.2.2 Supported Mobile Operating Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
4.6.2.3 Requirements for Testing Mobile Native and Hybrid Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
4.6.3 Manual Testing for Mobile Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
4.6.3.1 Getting to the JavaScript Console for Manual iOS Browser Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
4.6.4 Running Emulator and Simulator Mobile Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
4.6.5 Types of Mobile Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
4.6.6 FAQs for Mobile Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
4.6.7 Example Appium Mobile Testing Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
4.6.7.1 Android Example Scripts Written for Mobile Testing on Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
4.6.7.1.1 Example Java Script for Testing Android Mobile Applications on Sauce Labs . . . . . . . . . . . . . . . . . . . 108
4.6.7.1.2 Example Node.js Script for Testing Android Mobile Applications on Sauce Labs . . . . . . . . . . . . . . . . . 110
4.6.7.1.3 Example Python Script for Testing Android Mobile Applications on Sauce . . . . . . . . . . . . . . . . . . . . . 113
4.6.7.1.4 Example Ruby Script for Testing Android Mobile Applications on Sauce Labs . . . . . . . . . . . . . . . . . . 116
4.6.7.2 iOS Example Scripts for Mobile Testing on Sauce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
4.6.7.2.1 Example Java Script for Testing iOS Mobile Applications on Sauce Labs . . . . . . . . . . . . . . . . . . . . . . 120
4.6.7.2.2 Example Node.js Script for Testing iOS Mobile Applications on Sauce . . . . . . . . . . . . . . . . . . . . . . . . 123
4.6.7.2.3 Example PHP Script for Testing iOS Mobile Applications on Sauce Labs . . . . . . . . . . . . . . . . . . . . . . 126
4.6.7.2.4 Example Python Script for Testing iOS Mobile Applications on Sauce Labs . . . . . . . . . . . . . . . . . . . . 128
4.6.7.2.5 Example Ruby Script for Testing iOS Mobile Applications on Sauce Labs . . . . . . . . . . . . . . . . . . . . . . 129
4.7 Running Tests in Parallel with Sauce Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
4.7.1 Running Tests in Parallel with C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Page 2
Copyright Sauce Labs 2015
Page 3
Copyright Sauce Labs 2015
Page 4
Copyright Sauce Labs 2015
Quick Start
These topics are intended to provide you with a quick start overview of how you can set up testing in the Sauce Labs cloud using several popular
scripting languages.
Page 5
Copyright Sauce Labs 2015
Prerequisites
Quick Start
Code Sample
GuineaPigTests.cs
Constants.cs
Running Local Tests
Running Tests in Parallel
Reporting on Test Results
Prerequisites
Before getting started, you should review the Best Practices for Running Tests with Sauce Labs.
You need to have these components installed to set up testing on Sauce with C#.NET:
Visual Studio
Selenium WebDriver
Selenium DLLs for .NET installed and referenced by your project
Quick Start
Configuring Selenium tests to run on Sauce Labs is simple. The basic change is to switch from using a local Selenium driver to using a remote
driver pointed at ondemand.saucelabs.com, specifying your Sauce Labs account credentials and desired browser configuration.
Code Sample
GuineaPigTests.cs
This example verifies the title, a link, and the presence of a user agent element on the page https://saucelabs.com/test/guinea-pig. It connects to
Sauce Labs, run commands to remote control the target browser, and reports the results. It also includes the code for running tests in parallel and
reporting the results to your Sauce Labs dashboard.
You can use the Platform Configurator to specify the desired capabilities for any browser/platform combination you want for your test.
Constants.cs
Use this class to set your Sauce Labs account name and access key. You can find these in the User Profile menu of your Sauce Labs
Page 6
Copyright Sauce Labs 2015
dashboard.
desiredCapabilites.SetCapability("username", Constants.SAUCE_LABS_ACCOUNT_NAME);
// supply sauce labs username
desiredCapabilites.SetCapability("accessKey", Constants.SAUCE_LABS_ACCOUNT_KEY);
// supply sauce labs account key
Where you would substitute your account name and access key for Constants.SAUCE_LABS_ACCOUNT_NAME and Constants.SAU
CE_LABS_ACCOUNT_KEY. However, as a best practice we recommend using environment variables stored in a local file or system for
authentication, as this improves the security of your tests, and enables other members of your team to run tests on your account by
referencing the authentication credentials.
{
/// <summary>contains constants used by the tests such as the user name and
password for the sauce labs</summary>
internal static class Constants
{
/// <summary>name of the sauce labs account that will be used</summary>
internal const string SAUCE_LABS_ACCOUNT_NAME = "Your Account Name";
/// <summary>account key for the sauce labs account that will be
used</summary>
internal const string SAUCE_LABS_ACCOUNT_KEY = "Your Access Key";
// NOTE:
// To change the maximum number of parallel tests edit DegreeOfParallelism in
AssemblyInfo.cs
}
}
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. For more on this see the Selenium WebDriver - Running Your Tests in Parallel blog.
Before you start running tests in parallel, you should review the Best Practices for Running Tests with Sauce Labs, especially the topics on avoidi
ng external test dependencies and avoiding dependencies between tests.
Page 7
Copyright Sauce Labs 2015
Check out the topics under Running Tests in Parallel with C# for code examples and recommendations on running tests in parallel with C#.
C# Code for Reporting Test Results to the Sauce Labs Dashboard Expand source
[TearDown]
public void Cleanup()
{
// Gets the status of the current test
bool passed = TestContext.CurrentContext.Result.Status ==
TestStatus.Passed;
try
{
// Logs the result to Sauce Labs
((IJavaScriptExecutor)driver).ExecuteScript("sauce:job-result=" +
(passed ? "passed" : "failed"));
}
finally
{
// Terminates the remote webdriver session
driver.Quit();
}
Page 8
Copyright Sauce Labs 2015
You can use our JavaScript Unit Testing Methods to run your tests and report the results to your Sauce Labs dashboard
You can use the Grunt-Saucelabs grunt task to run Jasmine, Mocha, YUI, QUnit, and custom tests on Sauce. Each framework/test suite
has its own task, which in addition to setting up your test to run on Sauce, also opens a Sauce Connect tunnel so you can test
applications and websites that are on localhost or located behind a firewall.
The topics in Setting Up the Reporting Code for Your JavaScript Unit Tests explain how to set up your testing frameworks to report the
results to your Sauce Labs dashboard
Page 9
Copyright Sauce Labs 2015
Prerequisites
Quick Start
Code Sample
Running Local Tests
Running Tests in Parallel
Reporting on Test Results
Prerequisites
Before getting started, you should review the Best Practices for Running Tests with Sauce Labs.
You need to have these components installed to set up testing on Sauce with Java.
Quick Start
Configuring your existing Java-based Selenium tests to run on Sauce Labs is simple. The basic change is just to switch from using a local
Selenium driver, to using a remote driver pointed at ondemand.saucelabs.com, specifying your Sauce Labs account credentials and desired
browser configuration.
Code Sample
This code example illustrates setting up a simple Java test to find the title of a page hosted by Sauce Labs.
Page 10
Copyright Sauce Labs 2015
Example Java Code for Testing with Sauce Labs Expand source
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
/**
* Goes to Sauce Lab's guinea-pig page and prints title
*/
driver.get("https://saucelabs.com/test/guinea-pig");
System.out.println("title of page is: " + driver.getTitle());
driver.quit();
}
}
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. For more on this see the Selenium WebDriver - Running Your Tests in Parallel blog.
Before you start running tests in parallel, you should review the Best Practices for Running Tests with Sauce Labs, especially the topics on avoidi
ng external test dependencies and avoiding dependencies between tests.
Page 11
Copyright Sauce Labs 2015
Most Java users use one of two popular third party testing frameworks: TestNG or Junit. These links are for two example projects written in each.
They are designed to run in parallel. You can clone them and add your own test cases if you want:
1. https://github.com/ndmanvar/SeleniumJavaJunit
2. https://github.com/ndmanvar/SeleniumJavaTestNG
For more information, see the topics under Running Tests in Parallel with Java.
You should also check out the topic Viewing and Managing Sauce Labs Test Results for more suggestions on how to improve test reporting and
using build numbers for your continuous integration platform.
Page 12
Copyright Sauce Labs 2015
This tutorial will provide you with step-by-step information to get your node.js tests up and running on Sauce. This tutorial includes setting up Web
DriverIO as the Node.js client for Selenium 2.0, and Jasmine as the Behavior Driven Development testing framework. While there are many
options for setting up your Node.js toolchain, this tutorial focuses on these tools as the fastest way for you to get up and running with your Node.js
tests. WebDriverIO will also work with Mocha or Cucumber as your testing framework.
Prerequisites
Quick Start
Running the Sample Test
Code Sample
Running Local Tests
Running Tests in Parallel
Reporting on Test Results
Prerequisites
Before you get started, you should review the
The example script assumes you have set your Sauce Labs access credentials as environment variables
You will need to have Node.js v.0.11 or higher already installed
You will need to install both WebDriverIO and Jasmine
Once you've installed WebDriverIO, you can use the command line configuration utility to set up your test configuration
$ ./node_modules/.bin/wdio config
Quick Start
Configuring Selenium tests to run on Sauce Labs is simple. The basic change is to switch from using a local Selenium driver, to using a remote
driver pointed at ondemand.saucelabs.com. If you're using the WebdriverIO testing utility for Node.js, all you have to do is provide your
Sauce Labs user credentials, and it will automatically connect you. Note that this example assumes you have set your Sauce Labs authentication
credentials as environment variables, a recommended best practice for testing on Sauce. This code sample shows how to set up a very simple
standalone JavaScript test script that will authenticate you to Sauce Labs, and then test against Chrome to find the title of Google's home page.
client
.init()
.url('http://google.com')
.getTitle().then(console.log)
.end();
Page 13
Copyright Sauce Labs 2015
$ ./node_modules/.bin/wdio wdio.conf.js
Code Sample
This code example was generated through the WebDriverIO configuration utility and defines the desired capabilities for the test, while the test.s
pec.js code specifies the test behavior.
//
// If you are using Sauce Labs, WebdriverIO takes care to update the job
information
// once the test is done. This option is set to `true` by default.
//
updateJob: true,
//
// ==================
// Specify Test Files
// ==================
// Define which test specs should run. The pattern is relative to the directory
// from which `wdio` was called. Notice that, if you are calling `wdio` from an
// NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
// directory is where your package.json resides, so `wdio` will be called from
there.
//
specs: [
'./*.spec.js'
],
//
// ============
// Capabilities
// ============
// Define your capabilities here. WebdriverIO can run multiple capabilties at the
same
// time. Depending on the number of capabilities, WebdriverIO launches several
Page 14
Copyright Sauce Labs 2015
test
// sessions. Within your capabilities you can overwrite the spec and exclude
option in
// order to group specific specs to a specific capability.
//
// If you have trouble getting all important capabilities together, check out the
// Sauce Labs platform configurator - a great tool to configure your capabilities:
// https://docs.saucelabs.com/reference/platforms-configurator
//
capabilities: [{
browserName: 'firefox',
version: 37,
name: 'Firefox Selenium tests',
build: process.env.BUILD_NUMBER
},{
browserName: 'chrome',
version: 43,
name: 'Chrome Selenium tests',
build: process.env.BUILD_NUMBER
},{
browserName: 'safari',
version: 6,
name: 'Safari Selenium tests',
build: process.env.BUILD_NUMBER
}],
//
// ===================
// Test Configurations
// ===================
// Define all options that are relevant for the WebdriverIO instance here
//
// Level of logging verbosity.
logLevel: 'silent',
//
// Enables colors for log output.
coloredLogs: true,
//
// Saves a screenshot to a given path if a command fails.
screenshotPath: './errorShots/',
//
// Set a base URL in order to shorten url command calls. If your url parameter
starts
// with "/", the base url gets prepended.
baseUrl: 'http://nodejs.org',
//
// Default timeout for all waitForXXX commands.
waitforTimeout: 10000,
//
// Framework you want to run your specs with.
// The following are supported: mocha, jasmine and cucumber
// see also: http://webdriver.io/guide/testrunner/frameworks.html
//
// Make sure you have the node package for the specific framework installed before
running
// any tests. If not please install the following package:
// Mocha: `$ npm install mocha`
Page 15
Copyright Sauce Labs 2015
//
// Test reporter for stdout.
// The following are supported: dot (default), spec and xunit
// see also: http://webdriver.io/guide/testrunner/reporters.html
reporter: 'spec',
//
// Options to be passed to Mocha.
// See the full list at http://mochajs.org/
jasmineNodeOpts: {
Page 16
Copyright Sauce Labs 2015
defaultTimeoutInterval: 10000
}
};
If you want to use Sauce Connect, you need to set host to localhost and the port to 4445, as shown in this example script.
client
.init()
.url('http://localhost')
.getTitle().then(console.log)
.end();
Page 17
Copyright Sauce Labs 2015
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. For more on this see the Selenium WebDriver - Running Your Tests in Parallel blog.
Before you start running tests in parallel, you should review the , especially the topics on avoiding external test dependencies and avoiding
dependencies between tests.
With WebDriverIO you can define multiple Capabilities to run tests in parallel, as shown in the wdio.conf.js example script.
Page 18
Copyright Sauce Labs 2015
You need to have these components installed to set up testing on Sauce with PHP:
You must have PHP set up on your system before you start testing.
Mac OS X comes with PHP installed, as long as you're running version 5.3 or higher, you're ready to go! If you're a Windows user, you
can find instructions for setting up PHP on Windows at PHP.net.
Windows users must also enable the PHP curl library and OpenSSL support to get the best performance from your PHP setup.
For more information, see Installing Extensions for Windows on the php.net website as well as these setup topics:
Enabling the PHP curl Library for Windows
Setting Up curl/OpenSSL Support for PHP on Windows
We also recommend using Sausage as your PHP testing framework.
Sausage contains classes and libraries that are designed to work with the Sauce Labs API, and it provides a convenient user interface
and other features for managing your test results. It also includes a demo test, WebDriverDemo.php, that you can run to see how
Sauce works. For more information about how to set up and use Sausage, see Setting Up Sausage for Windows and Setting Up
Sausage for OS X and Linux.
Quick Start
You can set up any PHP test you've already written to run on Sauce, regardless of the testing framework it uses. All you need to do is change the
test from running locally, to running on the Sauce cloud by defining the sauce URL, your authentication credentials, and a set of desired
capabilities for the test.
This example test suite directly subclasses PHPUnit_Extensions_Selenium2TestCase, and thereby uses a locally-running Firefox browser.
Page 19
Copyright Sauce Labs 2015
And this example shows how you could edit the existing test to run on Sauce. Note that it assumes your authentication credentials are set up as
PHP constants, as recommended in our topic Best Practice: Use Environment Variables for Authentication Credentials. You can use the Platform
Configurator to specify the desired capabilities for any browser/platform combination you want.
Page 20
Copyright Sauce Labs 2015
Code Example
In this code example for PHP, the test runs a check to make sure that clicking a link brings you to the expected page. While simple, this example
illustrates everything you need to run an automated test on Sauce Labs. First, it checks for your Sauce authentication credentials, which are set
as environmental variables, and then sets the platform, browser, version, and other capabilities to use in the test.
Page 21
Copyright Sauce Labs 2015
require_once 'vendor/autoload.php';
define('SAUCE_HOST',
SAUCE_USERNAME.':'.SAUCE_ACCESS_KEY.'@ondemand.saucelabs.com');
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. For more on this see the Selenium WebDriver - Running Your Tests in Parallel blog.
Before you start running tests in parallel, you should review the Best Practices for Running Tests with Sauce Labs, especially the topics on avoidi
ng external test dependencies and avoiding dependencies between tests.
Page 22
Copyright Sauce Labs 2015
Check out the topics under Running Tests in Parallel with PHP for more information.
By default, Sauce Labs doesn't know how to display the name of your test. Sausage comes up with a good name (TestClass::testFunction
) and reports it with your test so it's easy to find on your dashboard. Similarly, Sauce has no way to know if a particular test passed or
failed. Sausage catches any failed assertions and reports the status of the test to Sauce after it's complete. Upon test failure Sausage
will generate an authorized link to the failed job report on the Sauce Labs website, to facilitate reporting to people who need to know the details of
the test. The job remains private (unless you change the status yourself), but others can follow the link without needing to log in with your
credentials. Check out Sharing the Results of Sauce Labs Tests for more information.
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, and associate tests with build numbers in your continuous integration
pipeline.
Page 23
Copyright Sauce Labs 2015
Prerequisites
Quick Start
Code Sample
Running Local Tests
Running Tests in Parallel
Reporting on Test Results
Prerequisites
Before getting started, you should read the Best Practices for Running Tests with Sauce Labs.
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.
You should also install the Sauce Python client, which provides features for reporting job information to the Sauce Labs dashboard.
Quick Start
It's very easy to get your existing Python test scripts up and running on Sauce.
If you wanted to run Selenium locally, you might initiate a driver for the browser that you want to test on like so:
If you wanted to run on Sauce, you would instead use webdriver.Remote(), and then pass it two paramaters: 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.
Page 24
Copyright Sauce Labs 2015
command_executor='http://YOUR_SAUCE_USERNAME:YOUR_SAUCE_ACCESSKEY@ondemand.saucelabs.c
om:80/wd/hub',
desired_capabilities=desired_cap)
You can use the Platform Configurator to specify the desired capabilities for any browser/platform combination you want.
Code Sample
This simple Python test script tests the Google front page. Despite its simplicity, it contains everything you need to know in order to run an
automated test on Sauce Labs.
Page 25
Copyright Sauce Labs 2015
# This is the only code you need to edit in your existing scripts.
# The command_executor tells the test to run on Sauce, while the desired_capabilties
# parameter tells us which browsers and OS to spin up.
desired_cap = {
'platform': "Mac OS X 10.9",
'browserName': "chrome",
'version': "31",
}
driver = webdriver.Remote(
command_executor='http://philg:45753ef0-4aac-44a3-82e7-b3ac81af8bca@ondemand.saucelabs
.com:80/wd/hub',
desired_capabilities=desired_cap)
# This is your test logic. You can add multiple tests here.
driver.implicitly_wait(10)
driver.get("http://www.google.com")
if not "Google" in driver.title:
raise Exception("Unable to load google page!")
elem = driver.find_element_by_name("q")
elem.send_keys("Sauce Labs")
elem.submit()
print driver.title
# 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.
driver.quit()
This code sample is more complex, and relies on some libraries that you may need to install to make it work.
Page 26
Copyright Sauce Labs 2015
"version": "31"},
{"platform": "Windows 8.1",
"browserName": "internet explorer",
"version": "11"}]
def on_platforms(platforms):
def decorator(base_class):
module = sys.modules[base_class.__module__].__dict__
for i, platform in enumerate(platforms):
d = dict(base_class.__dict__)
d['desired_capabilities'] = platform
name = "%s_%s" % (base_class.__name__, i + 1)
module[name] = new.classobj(name, (base_class,), d)
return decorator
@on_platforms(browsers)
class SauceSampleTest(unittest.TestCase):
def setUp(self):
self.desired_capabilities['name'] = self.id()
sauce_url = "http://%s:%s@ondemand.saucelabs.com:80/wd/hub"
self.driver = webdriver.Remote(
desired_capabilities=self.desired_capabilities,
command_executor=sauce_url % (USERNAME, ACCESS_KEY)
)
self.driver.implicitly_wait(30)
def test_sauce(self):
self.driver.get('http://saucelabs.com/test/guinea-pig')
assert "I am a page title - Sauce Labs" in self.driver.title
comments = self.driver.find_element_by_id('comments')
comments.send_keys('Hello! I am some example comments.'
' I should be in the page after submitting the form')
self.driver.find_element_by_id('submit').click()
commented = self.driver.find_element_by_id('your_comments')
assert ('Your comments: Hello! I am some example comments.'
' I should be in the page after submitting the form'
in commented.text)
body = self.driver.find_element_by_xpath('//body')
assert 'I am some other page content' not in body.text
self.driver.find_elements_by_link_text('i am a link')[0].click()
body = self.driver.find_element_by_xpath('//body')
assert 'I am some other page content' in body.text
def tearDown(self):
print("Link to your job: https://saucelabs.com/jobs/%s" %
self.driver.session_id)
try:
if sys.exc_info() == (None, None, None):
sauce.jobs.update_job(self.driver.session_id, passed=True)
else:
Page 27
Copyright Sauce Labs 2015
sauce.jobs.update_job(self.driver.session_id, passed=False)
finally:
self.driver.quit()
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. For more on this see the Selenium WebDriver - Running Your Tests in Parallel blog.
Before you start running tests in parallel, you should review the Best Practices for Running Tests with Sauce Labs, especially the topics on avoidi
ng external test dependencies and avoiding dependencies between tests.
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.
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.
Page 28
Copyright Sauce Labs 2015
Prerequisites
Before getting started, you should read the Best Practices for Running Tests with Sauce Labs.
Quick Start
It's very easy to get your existing Ruby tests up and running on Sauce.
If you wanted to run a test on Selenium locally, you would initiate a driver for the browser you want to test against like this.
To run an existing test on Sauce, all you need to change is your driver definition, and make sure that the sauce_endpoint variable includes
your Sauce USERNAME and ACCESSKEY.
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_capabilites and caps come into play.
caps = { :platform => "Mac OS X 10.9", :browserName => "Chrome", :version => "31" }
You can manually enter the values you want for :platform, :browsername, and :version, or you can use the handy Sauce Labs Platform
Configurator to generate the caps values for any combination of platform, browser, and browser version.
Code Sample
This code examples shows a very simple test to see if the title of Google's home page has changed, but it includes everything you need to set up
and run an automated test on Sauce.
Page 29
Copyright Sauce Labs 2015
Example Ruby Code for Testing with Sauce Labs Expand source
require "selenium/webdriver"
sauce_endpoint =
"http://YOUR_SAUCE_USERNAME:YOUR_SAUCE_ACCESSKEY@ondemand.saucelabs.com:80/wd/hub"
caps = {
:platform => "Mac OS X 10.9",
:browserName => "Chrome",
:version => "31"
}
puts driver.title
driver.quit
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. For more on this see the Selenium WebDriver - Running Your Tests in Parallel blog.
Before you start running tests in parallel, you should review the Best Practices for Running Tests with Sauce Labs, especially the topics on avoidi
ng external test dependencies and avoiding dependencies between tests.
Check out the topics under Running Tests in Parallel with Ruby for code examples and instructions on using popular testing frameworks for
running tests in parallel with Ruby.
Page 30
Copyright Sauce Labs 2015
"fails." Sauce Labs lets you notify us of test status using our REST API. All you need is the ID Sauce Labs gave the job, and the status your test
ended with. Then, you can use the Update Job method on the REST API to set the job's status.
The Job ID is the simplest part of the process. The ID assigned to each job by Sauce Labs is the same as the Session ID for the corresponding
Selenium session, which you can pull off the driver like so:
job_id = driver.session_id
Using the REST API is best done with the sauce_whisk gem, which assumes you've set your Sauce username and access key as the SAUCE_US
ERNAME and SAUCE_ACCESS_KEY environment variables.
This example shows how you would modify the example RSpec spec_helper.rb file to check the status of the test, and pass that to the REST
API.
Modifying spec_helper.rb to Report Test Results to the Dashboard Using Expand source
the sauce-whisk Gem
require "sauce_whisk"
RSpec.configure do |config|
config.around(:example, :run_on_sauce => true) do |example|
@driver = SauceDriver.new_driver
@job_id = @driver.session_id
begin
example.run
ensure
SauceWhisk::Jobs.change_status job_id, !example.exception.nil?
@driver.quit
end
end
end
That's it! Your tests will now be reporting their status to the Sauce Labs REST API.
Page 31
Copyright Sauce Labs 2015
WEB-2302 Not able to launch the Android Emulators with Google API in a Manual Session
WEB-2300 Large log.json File Causes Test Details Page to Load Slow
WEB-2290 Build Doesn't Match Results Between Parent & Sub Account
WEB-2282 Subaccounts with Admin Privileges can't set the Parent account as a parent when creating new users
WEB-2170 Manual Launcher: Amazon Kindle Fire Emumlator Android 2.3 combo is not working
WEB-2146 500 Internal Error when creating a sub-account with existing email address
WEB-1880 Scrolling over commands on test details page doesn't work in a specific case
WEB-1863 This build says '1 failed' but no test in the list is marked as failed
WEB-1774 Interactions with manual sessions fail if using computers with touch screen
WEB-1622 Sauce Connect outputs HTML when encountering JSON parse error
WEB-1338 Bad test data in YUI js unit tests cause job page not to load
WEB-1035 Manual Testing does not work using Windows 8 or Windows 10 Chrome or IE, very slow on FF
SC-213 Closing a Sauce Connect Windows tunnel does not close the tunnel in the UI
MOBILE-600 Emulators fail to start when the url to open has special characters
MOBILE-534 Live screencast doesn't load right away on test detials page / needs a few refreshes
MOBILE-488 Cannot launch tests with Android 2.3 (Manual & Automated)
MOBILE-364 VM fails to start for Samsung Galaxy S3 Emulator with Android 4.1
MOBILE-305 Android 5.0 Mobile sessions can't resolve DNS entries, initially
Page 32
Copyright Sauce Labs 2015
Page 33
Copyright Sauce Labs 2015
When you open the Account Profile drawer, you will see links for 5 The Account Profile drawer
managing your account information such as username and opens to provide you with links
password, managing teams and sub-accounts, and user settings for managing your account and
such as your Sauce Labs access key. team, as described in the Acco
unt Profile User Interface.
UI Element Description
Page 34
Copyright Sauce Labs 2015
Page 35
Copyright Sauce Labs 2015
It's important to point out that this time is necessary only on our servers. If you are running multiple tests at once, they will be assigned to new
machines so there shouldn't be any impact on the overall test suite execution time.
Sauce Connect creates a reliable, encrypted connection between your firewalled server and ours, and eliminates the need to whitelist IP
addresses (since all requests come from the machine in which Sauce Connect is running).
Note: If you don't yet have any HTTP Auth setup and all you want to do is have Sauce test your internal app, we strongly recommend using Sauc
e Connect instead.
Page 36
Copyright Sauce Labs 2015
One of our main criteria for a mature set of tests is "test independence." If your tests are completely independent from each other, the complete
test suite will be ready for scaling. And believe us, scaling is never too far off. Once you reach a certain amount of tests, the time needed to run
them serially will exceed the practical limit and:
1. Your team will stop running the tests as regularly as needed because it takes too long
2. The tests will start eating more and more of the development time
This can also depend on the context. In case it's really needed, we suggest preventing the test framework on your side from calling the start() and
stop() commands between tests.
Page 37
Copyright Sauce Labs 2015
Mobile Application Testing on Emulators and Real Devices Made Easy with Appium
Appium is an open-source tool for automating native, mobile web, and hybrid applications on iOS and Android platforms. Like Selenium, it works
with the language of your choice. Sauce also offers you the choice of testing on emulators or real devices, because while functional tests on
emulators might work out most of your bugs, you can't know for sure that you've squashed all of them out until you run the real thing.
Want to test your application "in the wild," but you aren't ready to make it publicly available yet? You can use Sauce Storage to load the assets
you want to test into our cloud, and then point your tests to their location. After seven days the assets are cleared out, and only you and other
users associated with your account can access them while they're available. There's no extra charge, and you get to see how your
applications behave over a network connection without having to commit to a hosting solution just for the purpose of testing.
Page 38
Copyright Sauce Labs 2015
Full Support - all browsers at this level will have identical behavior when accessing the Sauce Labs web interface
Functional Support - browsers at this level will be fully functional with the web interface, but may have differences in the way content is
displayed
Full Support Latest, Latest - 1 Latest, Latest - 1 Latest, Latest -1 (6.2+) Older than 2 years (11+ | Latest Latest
Win 8)
Functional Older than 6 months Older than 6 months Older than 2 years 9+ iOS 7.1+ Android 5.0+
Only (40+) (40+) (5.1+)
Page 39
Copyright Sauce Labs 2015
Tips and Best Practices for Running Tests with Sauce Labs
Best Practices for Running Tests with Sauce Labs
Best Practice: Avoid External Test Dependencies
Best Practice: Avoid Dependencies between Tests to Run Tests in Parallel
Best Practice: Don't Use Brittle Locators in Your Tests
Best Practice: Have a Retry Strategy for Handling Flakes
Best Practice: Keep Functional Tests Separate from Performance Tests
Best Practice: Use Build IDs, Tags, and Names to Identify Your Tests
Best Practice: Use Environment Variables for Authentication Credentials
Best Practice: Use Explicit Waits
Best Practice: Use the Latest Version of Selenium Client Bindings
Best Practices: Use Small, Atomic, Autonomous Tests
Tips for Lean, Speedy Tests with Sauce Labs
Handling Authentication
Basic HTTP Authentication
Injecting Cookies to Bypass Authentication Dialogs
Running an AutoIt Script as a Pre-run Executable to Handle Windows Security Authentication Dialogs
Pre-Run Executables
Setting Up Pre-Run Executables
Test Configuration and Annotation
Configuring Tests with the WebDriver API DesiredCapabilities
Configuring Tests with the Sauce Labs REST API
Configuring Tests with Selenium's JavaScript Executor
Test Configuration Options
Examples of Desired Capabilities for iWebDriver and Appium iOS Tests
Manual Testing with Sauce Labs
Running a Manual Testing Session
Starting Manual Tests from Automated Tests
Troubleshooting Manual Tests
Automated Testing with Sauce Labs
Troubleshooting Automated Tests
Common Error Messages
Mobile Testing with Sauce Labs
Mobile Testing with Appium
Support and Requirements for Mobile Testing
Supported Android Emulators
Supported Mobile Operating Systems
Requirements for Testing Mobile Native and Hybrid Applications
Manual Testing for Mobile Apps
Getting to the JavaScript Console for Manual iOS Browser Tests
Running Emulator and Simulator Mobile Tests
Types of Mobile Tests
FAQs for Mobile Testing
Example Appium Mobile Testing Scripts
Android Example Scripts Written for Mobile Testing on Sauce Labs
Example Java Script for Testing Android Mobile Applications on Sauce Labs
Example Node.js Script for Testing Android Mobile Applications on Sauce Labs
Example Python Script for Testing Android Mobile Applications on Sauce
Example Ruby Script for Testing Android Mobile Applications on Sauce Labs
iOS Example Scripts for Mobile Testing on Sauce
Example Java Script for Testing iOS Mobile Applications on Sauce Labs
Example Node.js Script for Testing iOS Mobile Applications on Sauce
Example PHP Script for Testing iOS Mobile Applications on Sauce Labs
Example Python Script for Testing iOS Mobile Applications on Sauce Labs
Example Ruby Script for Testing iOS Mobile Applications on Sauce Labs
Running Tests in Parallel with Sauce Labs
Running Tests in Parallel with C#
Running C# Tests in Parallel with Gallio and MBUnit
Running C# Tests in Parallel with PNUnit
Running Tests in Parallel with Java
Running Java Tests in Parallel with JUnit
Running Java Tests in Parallel with TestNG
Running Tests in Parallel with PHP
Running PHP Tests in Parallel with PHPUnit and Paratest
Running Tests in Parallel with Python
Page 40
Copyright Sauce Labs 2015
Page 41
Copyright Sauce Labs 2015
Tips and Best Practices for Running Tests with Sauce Labs
These topics cover tips and best practices for automated Selenium and Appium testing, and for running tests in the Sauce Labs browser cloud.
Page 42
Copyright Sauce Labs 2015
Page 43
Copyright Sauce Labs 2015
Page 44
Copyright Sauce Labs 2015
@Test
public void testUserOnlyFunctionality()
{
driver.findElement(By.id("userOnlyButton")).click();
assertEquals("Result of clicking userOnlyButton",
driver.findElement(By.id("some_result")));
}
function testUserOnlyFunctionality()
{
$this->byId('userOnlyButton')->click();
$this->assertTextPresent("Result of clicking userOnlyButton");
}
In both of these examples, testLogin() triggers the browser to log in and asserts that the login was successful. The second test clicks a
button on the logged-in page and asserts that a certain result occurred.
This test suite works fine as long as the tests run in order. But second test makes an assumption that you are already logged in, which creates a
dependency on the first test. If these tests run at the same time, or if the second one runs before the first one, the browser's cookies will not yet
allow Selenium to access the logged-in page, and the second test fails. You can get rid of this dependency by making sure that each test can run
independently independently of the others, as shown in these examples.
Page 45
Copyright Sauce Labs 2015
@Test
public void testLogin()
{
this.doLogin();
}
@Test
public void testUserOnlyFunctionality()
{
this.doLogin();
driver.findElement(By.id("userOnlyButton")).click();
assertEquals("Result of clicking userOnlyButton",
driver.findElement(By.id("some_result")));
}
function testLogin()
{
$this->doLogin();
}
function testUserOnlyFunctionality()
{
$this->doLogin();
$this->byId('userOnlyButton')->click();
$this->assertTextPresent("Result of clicking userOnlyButton");
}
The main point is that it is dangerous to assume any state when developing tests for your app. Instead, you should find ways to quickly generate
desired states for individual tests. In the example, this is accomplished with the doLogin() function, which generates a logged-in state instead of
assuming it. You might even want to develop an API for the development and test versions of your app that provides URL shortcuts that generate
common states. For example, a URL that's only available in test that creates a random user account and logs it in automatically.
Page 46
Copyright Sauce Labs 2015
Instead, use sensible semantics for CSS IDs and form element names, and try to restrict yourself to using these semantic identifiers. For
example, in Java you could designate elements with $this->byId() or $this->byName() or, in the example of PHP, you could use $this->
byId() or $this->byName() . This makes it much less likely that you'll inadvertently break your page by shuffling around some lines of code.
Page 47
Copyright Sauce Labs 2015
The best way to handle this problem is log your failing tests into a database and then analyze them. Even tests that fail intermittently with no
apparent cause may turn out to have a pattern when you are able to analyze them in detail and as a larger data set. If this is beyond the scope of
your testing setup, the next best strategy is to log your failing cases into a log file that records the browser, version, and operating system for
those tests, and then retry those tests. If they continue to fail after a second or third retry, chances are that the issue is with the functionality you're
testing, rather than the test itself. This isn't a total solution for dealing with flakes, but it should help you get closer to the source of the problem.
Page 48
Copyright Sauce Labs 2015
Functional tests should, as the name indicates, test some functionality or feature of your application. The output of these tests should be
either a simple "pass" or "fail" - either your functionality worked as expected, or it didn't.
Performance tests, in contrast, should gauge and output performance metrics. For example, can your application server handle a
particular load, and does it behave as expected when you push it to its limit? These types of tests are better undertaken with a testing
infrastructure that has been specifically developed for performance testing, so all baseline performance metrics are well established and
understood before you start the test.
By maintaining the distinction between functional and performance tests, and the different outputs that you expect from them, you should be able
to more precisely design your tests to uncover the specific kinds of issues that you need to address to make your app more robust under any
conditions.
Page 49
Copyright Sauce Labs 2015
Best Practice: Use Build IDs, Tags, and Names to Identify Your Tests
When you set the desired capabilities for your test, you can also add identifying information such as a name, tags, and build numbers that you can
then use to filter results in your test results or Web Archive page, or to identify builds within your continuous integration pipeline.
Page 50
Copyright Sauce Labs 2015
4. Press Escape.
5. Hold Shift and press Z twice (z z) to save and quit.
define('SAUCE_HOST', SAUCE_USERNAME.':'.SAUCE_ACCESS_KEY.'@ondemand.saucelabs.com');
driver = webdriver.Remote(
command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@ondemand.saucelabs.com:80/wd/
hub',
desired_capabilities=desired_cap)
Page 51
Copyright Sauce Labs 2015
username = ENV["SAUCE_USERNAME"]
access_key = ENV["SAUCE_ACCESS_KEY"]
remote_server_url =
"http://#{username}:#{access_key}@ondemand.saucelabs.com:80/wd/hub"
Page 52
Copyright Sauce Labs 2015
The general advice from the Selenium community on how to handle this is to use explicit waits. While you could also use implicit waits, an implicit
wait only waits for the appearance of certain elements on the page, while an explicit wait can be set to wait for broader conditions. Selenium guru
Dave Haeffner provides an excellent example of why you should use explicit waits on his Elemental Selenium blog.
These code samples, from the SeleniumHQ documentation on explicit and implicit waits, shows how you would use an explicit wait. In their
words, this sample shows how you would use an explicit wait that "waits up to 10 seconds before throwing a TimeoutException, or, if it finds
the element, will return it in 0 - 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns
successfully. A successful return for ExpectedCondition type is Boolean return true, or a not null return value for all other ExpectedCondi
tion types."
ff = webdriver.Firefox()
ff.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.ID,
"myDynamicElement")))
finally:
ff.quit()
Page 53
Copyright Sauce Labs 2015
require 'selenium-webdriver'
Page 54
Copyright Sauce Labs 2015
Page 55
Copyright Sauce Labs 2015
Small
Small refers to the idea that your tests should be short and succinct. If you have a test suite of 100 tests running concurrently on 100 VMs, then
the time it will take to run the entire suite will be determined by the longest/slowest test case. Keeping your tests small ensures that your suite will
run efficiently and provide you with results faster.
Atomic
An atomic test is one that focuses on testing a single feature, and which makes clear exactly what it is that you're testing. If the test fails, then you
should also have a very clear idea of what needs to be fixed.
Autonomous
An autonomous test is one that runs completely independently of other tests, and is not dependent on the results of one test to run successfully.
In addition, an autonomous test should use its own data to test against, and not create potential conflicts with other tests over the same data.
Page 56
Copyright Sauce Labs 2015
If you're testing against a local application server, you will see some additional latency due to the distance from our browsers to your
server.
The same applies if you're using Sauce Connect to test against a firewalled server. When you're running Connect, it sends all requests
from Sauce's browsers back through the machine running Sauce-Connect.jar, such that they appear to originate from that machine. This
means that all data sent between the Sauce cloud and the site you're testing must travel first to your local machine, then back out to the
application under test or to the Sauce cloud.
While Connect also includes features that help to reclaim this time - such as caching static site resources in our cloud - this added
security comes with some extra running time.
If you're using Capybara, be aware that this integration testing tool is especially chatty when formulating tests (and the same may go for
other wrappers that run on top of the Selenium library). For example, entering a value in an input field can spawn five Selenium
commands: verifying that the element is displayed, getting its name, determining its type, clearing it, and then entering the text. While
these steps help make tests robust and informative, if you're writing scripts by hand, they are usually not necessary.
Mobile browsers (iOS and Android) require a little extra time to fire up, as they launch first the device emulator, then a browser within it.
Reduce the unnecessary traffic that goes through the Sauce Connect tunnel, this in turn will help the test run
faster. Here are some suggestions to accomplish this on your end:
1. In your test, determine the URLs that are publicly available over the internet and list their domains with the -D, --direct-domains flag
when you start the Sauce Connect tunnel. The -D, --direct-domains flag takes a comma-separated list of domains which will be
relayed directly through the internet, instead of through the tunnel.
2. Determine those resources in your application that are not necessary for your test verifications (for example, images or advertisements).
List the domains for these resources using the -F, --fast-fail-regexps flag when you start the Sauce Connect tunnel. The -F, -
-fast-fail-regexps flag takes a comma-separated list of domains and any requests matching one of these will be dropped instantly,
not going through the tunnel. This will allow your application to load faster.
You can find information about all the flags that you can use with Sauce Connect in the topic Sauce Connect Command Line Reference.
The main thing you can do to decrease latency is to break your test down into small, atomic, autonomous tests. Our best practices topic goes into
more detail, but this will approach has several benefits for decreasing overall testing time.
That said, there are a few things that should help bring this down. We mainly recommend breaking the test down into smaller chunks, because:
1. You will be able to run independent tests in parallel, decreasing your build time.
2. It will make your tests more robust, since independent sections are tested without a pre-existing application state from earlier actions.
3. If you're using Sauce Connect, you have use of a proxy that intelligently caches static resources, so that later tests don't have to re-load
those from scratch.
CSS locators are generally faster than XPATH locators, especially if you're running tests in Internet Explorer. (Also, locating by an
Page 57
Copyright Sauce Labs 2015
Our Best Practices for Running Tests with Sauce Labs provide several tips for optimizing your test scripts.
Besides these script-dependent factors, there are a few additional Sauce processes that happen on a per-job basis, aside from the test, that add
some extra time. These include:
Automatic screenshots and video recording: We capture an automatic screenshot after each page-changing command, and record video
of each test by default. These are post-processed and uploaded after the test is over. The time this takes is added to the test, as it means
we have to keep that machine fully dedicated until this is finished. These options are turned on by default, and can be disabled in your
script as described in the topic Test Configuration Options.
Browser start time. The time it takes browsers to start varies with browsers and versions. This is inherent to the complexity of browser
testing and how Selenium handles each browser boot, so this can't be eliminated. This happens before the test starts and is added to the
test time as well under the same principles.
When using Connect, some additional length is expected (due to the time required to relay each request and response between
our browsers and your machine running the .jar)
If your tests are very short, the processing on each end also contributes time in a greater proportion relative to the test - since
these times will not reduce below a few seconds.
That said, if your tests exceed the 3x metric, or if they suddenly start running much more slowly than previously, feel free to reach out to us at hel
p@saucelabs.com and we'll do our best to assist you.
Page 58
Copyright Sauce Labs 2015
Handling Authentication
Dealing with authentication or security dialogs when testing a site or application can be tricky business. These topics present some options you
can use to deal with various kinds of authentication challenges.
Page 59
Copyright Sauce Labs 2015
Chrome Supported
Firefox Supported, but Firefox will display a prompt asking you to confirm
Safari Unsupported. See the support KB article How Can I use HTTP basic auth in Safari for an example of how you can use a pre-run
executable to handle this situation.
Because browser support for basic HTTP authentication is limited, we recommend either Injecting Cookies to Bypass Authentication Dialogs or R
unning an AutoIt Script as a Pre-run Executable to Handle Windows Security Authentication Dialogs as better solutions for handling
authentication.
Page 60
Copyright Sauce Labs 2015
You must be on the same domain that the cookie is valid for in order for this to work.
If the home page of the site you want to test takes a long time ago, you can try accessing a smaller page, like the 404 page, for the
purpose of injecting the cookie before you access the home page.
This code example demonstrates how you would set the cookies, but you can find additional examples for Java, Python, Ruby, and Perl on the
official Selenium Commands and Operations page.
require 'selenium-webdriver'
url =
"http://#{ENV['SAUCE_USERNAME']}:#{ENV['SAUCE_ACCESS_KEY']}@ondemand.saucelabs.com:80/
wd/hub".strip
browser.manage.add_cookie({
:name => 'CookieName',
:value => 'CookieValue',
:path => '/',
:secure => false
})
Page 61
Copyright Sauce Labs 2015
Running an AutoIt Script as a Pre-run Executable to Handle Windows Security Authentication Dialogs
When using Sauce Connect to run local tests on a Windows machine, you may encounter an Integrated Windows Authentication (IWA) dialog,
also known as NTLM or Domain authentication. This is because the machine that Sauce Connect is running on is used to look up the host where
the site or application under test is located. If the host has IWA enabled, the authentication request will be passed back through Sauce Connect to
the Sauce Labs browser. Because there is no registry key available on our Windows virtual machines to disable this authentication, the solution is
to create an AutoIT script to respond to the dialog, and run it as a pre-run executable in advance of running the test.
You can use the AutoIT Script editor to write and save your script.
The script for handling the IWA dialog should look like this:
WinWaitActive(“Windows Security”)
Send(“Username”)
Send(“{TAB}”)
Send(“mysupersecretpassword”)
Send(“{ENTER}”)
For Username and mysupersecretpassword, enter the authentication credentials required by the Windows host.
When you save the script, it will be an .au3 file, and you will need to compile it as an .exe file. Once compiled, you can use it as a
pre-run executable with this API call:
Page 62
Copyright Sauce Labs 2015
Pre-Run Executables
In the real world, there's no such thing as a "stock" version of any particular browser, because users can easily modify them with add-ons, change
settings, and set profiles with specific functionality. There are also situations in which browser or virtual machine configurations can cause issues
with your tests. For these reasons, you may want to make changes to the browser or VM configuration before your test runs. For example, you
might want to test against a security-conscious user profile that includes using private windows, blocking all pop-ups, and disabling JavaScript, or
you may want to change settings that could raise dialogs and cause your tests to fail.
There are different ways to deal with these situations, depending on the type of browser you're testing against. Firefox includes a Profiles feature t
hat lets you manage everything from passwords to security settings to site-specific settings, like which sites are allowed to display pop-ups. The S
elenium driver for Firefox includes a webdriver.firefox.profile system property that lets you select which profile you want to use in your
testing. With Chrome, there is a long list of switches that you can set to change browser behavior, which you can pass as arguments to the
Chrome WebDriver. Unfortunately, neither Safari or Internet Explorer have a built-in way to edit user settings, which is where pre-run executables
come into play.
A pre-run executable is simply a script that you can run prior to a test to change settings for Safari, Internet Explorer, or any other browser, or to
configure the virtual machine that your tests will run on. You can see an example of a pre-run executable for virtual machine configuration in the
Sauce Labs Support KB article Edit the Domain Name System (DNS) within the Sauce Labs Virtual Machine, which edits the local hosts file on
the Sauce Labs VM so that when the driver tries to access http://www.saucelabs.com, it will be re-directed to www.google.com. You can see an
example of a pre-run executable for Safari in the Support KB article How Can I Use HTTP Basic Authentication in Safari? In this case, Safari will
normally load a Warning page when you try to access a site that uses HTTP basic authentication, which will cause your test to fail. The solution is
to use a pre-run executable to change the setting that warns about potentially fraudulent websites. An example of a pre-run executable for
Internet Explorer would be changing the registry key MaxScriptStatements to a very high number to try and prevent the dialog Stop
unresponsive script? from appearing.
You can configure your Sauce testing jobs to use pre-run executables using the DesiredCapabilities of the WebDriver API, as described in
both Test Configuration Options and Setting Up Pre-Run Executables.
Page 63
Copyright Sauce Labs 2015
1. Write your script to reflect the changes you want to make to the browser or virtual machine configuration.
This example script disables the Warning that Safari pops up when using basic HTTP authentication to access a website.
disable_fraud.sh
#!/bin/bash
defaults write com.apple.Safari WarnAboutFraudulentWebsites false
desired_capabilities['prerun'] = {
'executable':'http://myscriptstorage.com/disable_fraud.sh',
'background': 'false'
}
Page 64
Copyright Sauce Labs 2015
Page 65
Copyright Sauce Labs 2015
Related Links
Page 66
Copyright Sauce Labs 2015
Accepted Keys
Key Type
name string
public string
tags array
build integer
passed boolean
If you were to use this from your tests, you would probably want to build a simple set of functions that perform the put request for you. We've
created a Java library for this, and there are also some examples for Python and Ruby.
Page 67
Copyright Sauce Labs 2015
Related Links
Page 68
Copyright Sauce Labs 2015
Python Example
Java Example
Options
Python Example
driver.execute_script("sauce:job-name=My test")
Java Example
((JavascriptExecutor)driver).executeScript("sauce:job-name=My test");
Options
Pass/Fail "sauce:job-result=passed" Sets the pass/fail status of the job. Valid options are passed, failed, true, and f
Status alse. True means passed and false means failed.
Start/Stop "sauce: stop network" Stops/re-starts the VM’s network connection. A space must be included between sa
the VM uce: and stop or start.
Connection "sauce: start network"
Mac OS X
only
Break "sauce: break" Puts a Sauce breakpoint in the test. Test execution will pause at this point, waiting
Point for manual control by clicking in the test’s live video. A space must be included
between sauce: and break. See Manual Testing for Mobile Apps for more
information on how to use this annotation.
Context "sauce:context=This line Logs the given line in the job’s Selenium commands list. No spaces can be between
appears in the command list as sauce: and context.
'info'"
Job Info "sauce: Sets one or more job information fields to the values sent in the JSON-formatted
job-info={'build':'mybuild', dictionary.
'name':'my test name',
'public':'team'}"
Page 69
Copyright Sauce Labs 2015
Selenium-Specific Options
Required Selenium Test Configuration Settings
Other Selenium Options
Selenium Version
Appium-Specific Options
Required Appium Test Configuration Settings
Other Appium Options
General Options
Auto Accept Alerts
Test Annotation
Timeouts
Sauce Testing Options
Optional Sauce Testing Features
Selenium-Specific Options
The name of the browser test against. Options are: browserName string "browserName": "firefox"
Browser Name android
chrome
firefox
htmlunit
internet explorer
iPhone
iPad
opera
safari
The version of the browser you want to use in your test. version string "version", "45.0"
Browser Version
Which platform the browser should be running on. Options are: platform string "platform", "OS X 10.9"
Platform windows
xp
vista
mac
linux
unix
android
Allows you to choose the version of Selenium you want to use seleniumVersion string "seleniumVersion":"2.46.0"
for your test.
Selenium
Version
Appium-Specific Options
Page 70
Copyright Sauce Labs 2015
The mobile web browser that will be automated in browserName string "browserName", "Safari" If you're testing a mobile
the simulator, emulator or device. native application or a mobile
Browser hybrid application, the value
Name for this capability should be
an empty string. Check out T
ypes of Mobile Tests for
more information.
The name of the simulator, emulator, or device deviceName string "deviceName","Google Nexus 7 HD For an Android emulator test
you want to use in the test. Emulator" you can request a generic
Device Android emulator by using
Name the option "deviceName":"
Android Emulator". If
you want to use an Android
emulator that looks and feels
like a specific Android phone
or tablet, for example a
Google Nexus 7 HD
Emulator or a Samsung
Galaxy S4, then instead of "
deviceName":"Android
Emulator", you need to
specify the exact Android
emulator skin to use, for
example "deviceName":"S
amsung Galaxy S4
Emulator".
The mobile operating system version that you platformVersion string "platformVersion","9.1"
want to use in your test.
Platform
Version
The mobile operating system platform you want to platformName string "platformName", "iOS"
use in your test.
Platform
Name
The path to a .ipa, .apk or .zip file containing app string "app","sauce-storage:my_app.zip" This capability is only for
the app to test. This could be the location of your testing mobile native or
Application app in the Temporary Sauce Storage, for example, mobile hybrid applications. T
Path sauce-storage:myapp.zip, or the URL to a his capability is not required
remote location where your app is located, for for Android if you specify the
example http://myappurl.zip/. appPackage and appActiv
For mobile and
ity capabilities.
Hybrid application
testing only. See
Types of Mobile
Tests for more
information
Page 71
Copyright Sauce Labs 2015
Automation Engine
Auto Accept Alerts
Application Package
Android Activity
The name for the Android appActivity string "appActivity",".MainActivity" This capability
activity you want to launch needs to be
Android from your package. preceded by a .
Activity (dot). For
For Android example, .Main
Only Activity instea
d of MainActiv
ity.
Appium
automatically
determines the
activity to launch,
you only need to
use this desired
capability if you
want to specify
an activity
different than the
default one.
General Options
Page 72
Copyright Sauce Labs 2015
These options can be set for both Selenium and Appium Tests.
Setting this option will automatically accept any unexpected browser alerts that come autoAcceptAlerts boolean "autoAcceptAlerts":
up during your test, such as when Safari pops up the alert "Safari would like to use your true
Auto current location (Don't Allow | Allow)."
Accept
Alerts
Test Annotation
You can add these annotations to your tests to make them easier to track and identify.
Test Names
Build Numbers
Tagging
Pass/Fail Status
Custom Data
Used to record test names for jobs and make it easier to find name string "name": "my example name"
individual tests
Test
Names
Used to associate jobs with a build number or app version, which is build string "build": "build-1234"
then displayed on both the Dashboard and Archives view
Build
Numbers
User-defined tags for grouping and filtering jobs in the Dashboard tags list "tags": ["tag1","tag2","tag3"]
and Archives view
Tagging
Selenium and Appium handle sending commands to control a passed boolean "passed": "true"
browser or app, but don't report to the server whether a test passed
Pass/Fail or failed. To record pass/fail status on Sauce, set the passed flag
Status on the job. Since you can't know in advance whether a test passed
or failed, this flag can't be set in the initial configuration.
User-defined custom data that will accept any valid JSON object, customData object "customData": {"release": "1.0",
limited to 64KB in size. "commit":
Custom "0k392a9dkjr",
Data "staging": true,
"execution_number":
5,
"server":
"test.customer.com"}
Timeouts
Maximum Test Duration
Command Timeout
Idle Test Timeout
As a safety measure to prevent broken tests from running indefinitely, Sauce limits maxDuration integer "maxDuration":1800
the duration of tests to 30 minutes by default. You can adjust this limit on per-job
Maximum basis. The value of this setting is given in seconds. The maximum test duration
Test value allowed is 10800 seconds.
Duration
Page 73
Copyright Sauce Labs 2015
As a safety measure to prevent Selenium crashes from making your tests run commandTimeout integer "commandTimeout":300
indefinitely, Sauce limits how long Selenium can take to run a command in our
Command browsers. This is set to 300 seconds by default. The value of this setting is given
Timeout in seconds. The maximum command timeout value allowed is 600 seconds.
As a safety measure to prevent tests from running too long after something has idleTimeout integer "idleTimeout":90
gone wrong, Sauce limits how long a browser can wait for a test to send a new
Idle Test command. This is set to 90 seconds by default and limited to a maximum value of
Timeout 1000 seconds. You can adjust this limit on a per-job basis. The value of this
setting is given in seconds.
If this capability is null, an empty string, or omitted altogether, the latest version string or "version": "35"
version of the browser will be used automatically. integer
Version
(Browser)
You can provide a URL to an executable file, which will be downloaded prerun "prerun": { "executable": "http: If a single string is
and executed to configure the VM before the test starts. For faster //url.to/your/executable.exe", sent as the prerun
Pre-run performance, you may want to upload the executable to temporary Sauce (primary key) "args": [ "--silent", "-a", "-q" capability rather than
storage. This capability takes a JSON object with four main keys. Check ], "background": true, a JSON object, this
Executables out the topics under Pre-Run Executables for more information. "timeout": 120 } string is considered
to be the URL to the
executable, and the
Running AutoIt Scripts executable launches
If you want to run an AutoIt script during your test, compile with background se
it as an exe, send it using this capability, and set backgro t to false.
und to true to allow AutoIt to continue running throughout
the full duration of your test.
The URL to the executable you want to run before your browser session executable
starts.
(secondary key)
A list of the command line parameters that you want the executable to args
receive.
(secondary key)
A boolean that defines whether Sauce should wait for this executable to background
finish before your browser session starts. If background isn't set or is set
to false, Sauce will wait for up to 90 seconds for the executable to (secondary key)
finish. At that point, the browser will start and your test will proceed.
The number of seconds Sauce will wait for your executable to finish timeout
before your browser session starts. If timeout isn't set, Sauce will wait for
up to 90 seconds for the executable to finish. timeout is capped at 360 (secondary key)
seconds and won't apply if background is set to true.
If an identified tunnel is started using Sauce Connect, your jobs can tunnelIdentifier string "tunnelIdentifier": "MyTunnel01"
choose to proxy through it using this set of keys with the right identifier.
Identified
Tunnels
Page 74
Copyright Sauce Labs 2015
This setting specifies which screen resolution should be used during the screenResolution string "screenResolution": "1280x1024" Valid values for
test session. This feature is available in Windows XP, Windows 7 (except Windows XP and
Specifying Windows 7 with IE 9), Windows 8, Windows 8.1, and OS X 10.8. We do Windows 7
not yet offer specific resolutions for Windows 10, OS X 10.9, OS X 10.10,
the Screen OS X 10.11, Linux, or mobile platforms. 800x600
Resolution 1024x768
1052x864
1152x864
1280x800
1280x960
1280x1024
1400x1050
1440x900
1600x1200
1680x1050
1920x1200
2560x1600
1024x768
1152x864
1152x900
1280x800
1280x1024
1376x1032
1400x1050
1600x1200
1680x1050
1920x1200
800x600
1024x768
1280x1024
Desktop Test VMs can be configured with custom time zones. This timeZone string "timeZone": "Pacific"
feature should work on all operating systems, however time zones on "timeZone": "Honolulu"
Custom Windows VMs are approximate. They will default to the time zone that the "timeZone": "Alaska"
provided location falls into. You can find a complete list of timezones on "timeZone": "New_York"
Time Zones Wikipedia. Underscores should be replaced with spaces. Sauce takes
only location names (not their paths), as shown in the example below.
Sauce Labs supports the ChromeDriver version 1 series (i.e. 26.0.1383 chromedriverVersion string "chromedriverVersion": "2.15" Supported Chrome
.0) and the version 2 series (i.e. 2.15). The default version of Drivers
Chrome ChromeDriver when no value is specified depends on the version of
Chrome. 21.0.1180.0
Driver 23.0.1240.0
Version Chrome 28 and below: Chromedriver 26.0.1383.0 26.0.1383.0
0.6
Chrome 29 - 30: Chromedriver 2.4
Chrome 31 - 32: Chromedriver 2.8 0.7
Chrome 33 - 36: Chromedriver 2.10 0.8
Chrome 37 - 39: Chromedriver 2.11 0.9
Chrome 40 - 44: Chromedriver 2.15 2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
2.10
2.11
2.12
2.13
2.14
2.15
Page 75
Copyright Sauce Labs 2015
Sauce Labs supports launching 64-bit IE on our 64-bit VMs: Windows 7, iedriverVersion string "iedriverVersion": "2.46.0" Supported IE
Windows 8, and Windows 8.1. This provides a workaround for two known Drivers
Internet Selenium issues:
2.21.1
Explorer Using a 32 bit driver on a 64 bit operating system causes Selenium's 2.21.2
Driver screenshot feature to only capture the part of the page currently visible in
the browser viewport Selenium Issue 5876.
2.24.0
2.25.3
Version 2.26.0
Using a 64 bit driver on a 64 bit operating system causes text entry to be 2.28.0
extremely slow Selenium Issue 5516. 2.29.0
2.30.1
2.31.0
2.32.2
2.33.0
2.34.0
2.35.0
2.35.1
2.35.2
2.35.3
2.36.0
2.37.0
2.38.0
2.39.0
2.40.0
2.41.0
2.42.0
2.43.0
2.44.0
2.45.0
2.46.0
x64_2.29.0
x64_2.39.0
x64_2.40.0
x64_2.41.0
x64_2.42.0
x64_2.43.0
x64_2.44.0
x64_2.45.0
x64_2.46.0
By default, Sauce routes traffic from some WebDriver browsers (Internet avoidProxy boolean "avoidProxy": true
Explorer and Safari) through the Selenium HTTP proxy server so that
Avoiding HTTPS connections with self-signed certificates work everywhere. The
Selenium proxy server can cause problems for some users. If that's the
the case for you, you can configure Sauce to avoid using the proxy server
and have browsers communicate directly with your servers.
Selenium
Proxy
Don't Need the Selenium Proxy with Firefox or Google
Chrome
Firefox and Google Chrome under WebDriver aren't
affected by this flag as they handle invalid certificates
automatically and there isn't a need to proxy through
Selenium.
Page 76
Copyright Sauce Labs 2015
Sauce Labs supports several test result visibility levels, which control who
can view the test details. The visibility level for a test can be set manually
Job from the test results page, but also programatically when starting a test or
with our REST API. For more information about sharing test result, see
Visibility the topics under Sharing the Results of Sauce Labs Tests.
Visibility Description
Key
public If you want to share your job's result page and video,
restricted but keep the logs only for you, you can certainly do so
with public restricted visiblity mode. This visibility mode
will hide the fancy job log as well as prohibit access to
the raw Selenium log, so that anonymous users with
the link will be able to watch the video and screen
shots but won't be able to see what's being typed and
done to get there.
private If you don't want to share your test's result page and
video with anyone, you should use private job visibility
mode. This way, only you (the owner) will be able to
view assets and test result page.
By default, Sauce Labs captures screenshot and video of your tests. You can disable these and other optional test features.
Disable video recording
Disable step-by-step screenshots
Disable log recording
Enable HTML source capture
Enable WebDriver's automatic screen shots
This setting will let you discard videos recordScreenshots boolean "recordScreenshots": false
for passing tests identified using the pa
Disable ssed setting. This disables video
step-by-step post-processing and uploading that
screenshots may otherwise consume some extra
time after your test is complete.
Page 77
Copyright Sauce Labs 2015
Page 78
Copyright Sauce Labs 2015
Using iWebdriver
Mobile Web Application
iPhone
iPad
Using Appium
Mobile Web Application
iPhone
iPad
Native Mobile Applications
iPhone
iPad
Learn more about Appium and its desired capabilities: http://appium.io/slate/en/v1.2.0/?python#toc_56
Manual Test + Native Mobile Applications:
Using iWebdriver
You can use iWebdriver to drive the iOS simulator when testing Mobile Web Applications with Sauce Labs. If you want to test Native Mobile
Application then you will need to use the Appium driver.
iPhone
self.desired_capabilities = webdriver.DesiredCapabilities.IPHONE
self.desired_capabilities['platform'] = "OS X 10.10"
self.desired_capabilities['version'] = "6.0"
self.desired_capabilities['browserName'] = 'iPhone'
iPad
self.desired_capabilities = webdriver.DesiredCapabilities.IPAD
self.desired_capabilities['platform'] = "OS X 10.10"
self.desired_capabilities['version'] = "6.0"
self.desired_capabilities['browserName'] = 'iPad'
Using Appium
Appium is not supported for iOS version 6.0 and earlier. For these earlier versions of iOS you must use iWebdriver. For iOS version 6.1 and later
you can use Appium. Appium will be the tool in the background that is starting and driving the simulator for your Sauce Labs test.
If in your test you omit the appiumVersion desired capability, your test will be running with our default Appium version (for example, Appium
0.18.2.). Sauce recommends that you specify one of the newer Appium versions (for example, Appium version 1.3.6 or 1.3.7) which provides a
more extended API and fixes to known bugs.
iPhone
Page 79
Copyright Sauce Labs 2015
self.desired_capabilities = {}
self.desired_capabilities['platformName'] = 'iOS'
self.desired_capabilities['platformVersion'] = '8.1'
self.desired_capabilities['browserName'] = 'safari'
self.desired_capabilities['deviceName'] = 'iPhone Simulator'
self.desired_capabilities['appiumVersion'] = '1.3.6'
iPad
self.desired_capabilities = {}
self.desired_capabilities['platformName'] = 'iOS'
self.desired_capabilities['platformVersion'] = '8.1'
self.desired_capabilities['browserName'] = 'safari'
self.desired_capabilities['deviceName'] = 'iPad Simulator'
self.desired_capabilities['appiumVersion'] = '1.3.6'
iPhone
self.desired_capabilities = {}
self.desired_capabilities['platformName'] = 'iOS'
self.desired_capabilities['platformVersion'] = ‘8.1'
self.desired_capabilities['browserName'] = ''
self.desired_capabilities['deviceName'] = 'iPhone Simulator'
self.desired_capabilities['app'] = 'sauce-storage:myapp.zip'
self.desired_capabilities['appiumVersion'] = '1.3.6'
iPad
self.desired_capabilities = {}
self.desired_capabilities['platformName'] = 'iOS'
self.desired_capabilities['platformVersion'] = ‘8.1'
self.desired_capabilities['browserName'] = ''
self.desired_capabilities['deviceName'] = 'iPhone Simulator'
self.desired_capabilities['app'] = 'sauce-storage:myapp.zip'
self.desired_capabilities['appiumVersion'] = '1.3.6'
Note that when testing a Native Mobile Application the value for the 'browserName' desired capability is simply an empty string (e.g ''). Also have
in mind that you must add the desired capability 'appiumVersion'with a value of Appium version 1.0 or greater. If you need to use a remote
app instead of an app that you previously loaded into sauce-storage then you can specify it like this:
self.desired_capabilities['app'] = 'http://myappurl.zip'
Currently, the only way that users can interact with Native Mobile Applications is through an automated tests. After the app is loaded through an
automated test, you could take manual control of your Native Mobile Application by inserting a breakpoint. But overall the loading of the app has
to happen through an automated test.
Page 80
Copyright Sauce Labs 2015
Page 81
Copyright Sauce Labs 2015
to select browser/version/operating system/screen resolution combinations you've used in previous manual tests.
5. For Web browsers, select the browser version, operating system, and screen resolution that you want to test against.
6. Test assets such as screenshots are automatically saved. If you don't want to save them, clear the Save Screenshots, Logs, & Video o
ption.
7. Click Start Session.
You'll see a loading screen, and then the URL you entered will launch in a manual test window. At the top of the screen you will see a tab
with the test URL, and a menu bar that contains information about the parameters of your test and the time remaining before your test
session ends. You will also see icons to Stop the test, Share the session with other users, use the Clipboard, take Snapshots, and
enter Full-screen mode.
8. Use your keyboard and mouse to test the functionality of your website or application.
to record it.
This will save it to the Test Details page.
10. When you're finished with your test session, click Stop
.
You can now download video of your test, and other test assets, on the Test Details page under the Metadata tab.
. This will display a URL for the test that you can then send to other users.
, enter the text you want to store on the remote clipboard, and click Send. You'll see the text appear under the Remote Clipboard head
er. To copy text from the remote clipboard back to your local clipboard, click the Copy icon
Page 82
Copyright Sauce Labs 2015
Page 83
Copyright Sauce Labs 2015
This error is displayed when the ports used by manual testing relies are being blocked by a firewall on your end. This may also be caused by
running applications such as Avast! antivirus software.
These are the servers and ports used by manual testing. Please check with your IT organization that they are accessible.
If you are launching manual testing from Internet Explorer on your local machine:
tv1.saucelabs.com:843
tv1.saucelabs.com:5901
saucelabs.com:843
If you are launching manual testing from any other locally-installed browser:
charon.saucelabs.com:80
We recommend making all of these accessible if you plan on using several browsers locally.
If your test shows a black screen after starting the virtual machine, you may need to reinstall Adobe Flash Player on your machine. This should
only occur if you are using Internet Explorer to launch Sauce Manual Testing, which requires this software for our in-browser VNC player to
function.
We've streamlined our service to provide the best possible load times. If you are seeing slow manual testing sessions, check our status page, or
get instant updates by following @sauceops on Twitter.
It's possible for the manual testing VNC client to have a modifier key "stuck" down, causing any clicked links to open in new tabs. This happens if
the client loses focus while a key is held down -- for example, when using Alt-Tab to switch application windows. In this case, VNC never receives
the keyUp event.
To prevent this from happening: every time you focus back on the manual testing window, first click in the middle of the page, then press and
release all the modifier keys (like Alt, Control, Command, and Shift).
Error message: "Uh oh! Some error occurred while connecting to the browser"
The job seems to start, but you see only a white text box in the middle of a black screen.
Page 84
Copyright Sauce Labs 2015
Both of these indicate that your browser is having trouble displaying the VNC stream from the remote machine. Take the following steps to
troubleshoot:
Check the video on Sauce: If the recorded video after the job shows a steady video stream, this indicates that the issue is in your
computer or connection to Sauce. However, if the Sauce video shows the same issue, that indicates an issue in our service. In that case,
send us the URL for the job page and a screenshot of the issue.
Check that your browser is up to date: If you're on an older version, this may cause incompatibilities. Update your browser and try again.
Check your firewall: make sure that your machine allows full access for the interactive stream over the required ports (https://saucelabs.c
om/docs/manual#troubleshooting).
Check that the Internet connection is stable: We recommend running Sauce tests from a machine with a wired Ethernet connection, to
ensure a steady connection. If the connection flickers, this error could be thrown.
Want more?
If you'd like to dig deeper, feel free to check out our help forums or email us directly at help@saucelabs.com.
Page 85
Copyright Sauce Labs 2015
Prerequisites
Before you get started with testing on Sauce, you should check out the Automated Testing with Sauce Labs and the Automated Testing
with Sauce Labs
If you're interested in testing mobile applications, you should read the Automated Testing with Sauce Labs
If you want to test applications that are behind a firewall or on localhost, you should read up on Sauce Connect, which enables you to
create a secure tunnel between the location where your application resides and the Sauce Labs testing infrastructure
If you aren't already, you should familiarize yourself with using Selenium for Web application testing, and Appium for mobile application
testing
You can use the Platform Configurator to set the desired capabilities for both Selenium and Appium tests in your preferred
language.
You can also use the REST API or the WebDriver API to further configure your jobs with timeouts, annotations (a recommended
best practice for managing your tests results, and for managing builds in your continuous integration pipeline), and other job
functionality.
Both the Automated Testing with Sauce Labs and Tutorial topics include code samples that illustrate how to write automated
tests for Web applications in various languages, while the topics under Automated Testing with Sauce Labs illustrate how to write
scripts for testing iOS and Android mobile applications.
1. Run your tests and watch the results appear on your Sauce Labs dashboard, complete with video, screenshots, and logs.
Once you've mastered the basics, you'll be ready to move on to more advanced functionality, like running your tests in parallel to speed up your
testing process, and integrating your tests on Sauce into your continuous integration pipeline.
Page 86
Copyright Sauce Labs 2015
A general problem some users face is when outgoing connections from private networks on port 4444 are blocked, causing the tests to not reach
Sauce. As a fast solution to that problem, Sauce also listens at ondemand.saucelabs.com:80. Just use ondemand.saucelabs.com as the
Selenium host and 80 as the Selenium port.
The video is missing, even though the test finished. What happened?
Missing videos are generally caused by the need to first post-process and upload the recorded video for it to be accessible to our users through
the web interface. The time these tasks take will depend on the duration of the test (longer tests will produce longer videos). A reasonable
estimation is that video processing and uploading consumes around 30% of total test time. This means that if your test takes 1 minute total
(between browser start and shutdown), the video will take 20 seconds to upload to your account page. Additionally, if a test takes 10 minutes, it
may take us up to 3 minutes to have the video ready.
Please let us know if you find videos are taking longer than that to process.
Open Commands time out, even though I see the app loaded in the video. Why is this?
This is generally caused by a connection gap or a problem with the application's server handling requests incorrectly. As a first step, you should
proceed with a deep analysis of the network traffic. If you make it automated and run several tests at the same time, you will have higher chances
of replicating the error.
Another good recommendation is to try out the captureNetworkTraffic command, which requires the Selenium instance to be started with the
option captureNetworkTraffic=true and your test to use Firefox. This will let you pull the request info back out as JSON/XML/plain text. Then you
can parse that content and find any problems.
We're constantly working to making our resource allocation as slick as possible, but at certain times, when our service is under very high load, this
could take longer than expected. Please check our status page to see if there's an ongoing issue and let us know if you find this happening too
often.
Tests that failed on my end appear to have passed in Sauce. How did that happen?
Because of the client/server architecture that Selenium employs, there's no information about assertion results on the server side (which, in this
case, is Sauce). Here's an example. If your test has a step for validating that the title of your AUT is "My Shiny WebApp's Title", all that Sauce
sees is a request to get the title from the current page. Therefor, it will only return the result, without even knowing what was expected.
Your test:
assertEquals(sel.getTitle(), "My Shiny WebApp's Title");
Sauce Labs:
Command requested: getTitle()
Result: Your Page's Title
Notice that we use the same criteria for other kinds of failures, such as a Selenium exception for trying to click on a non-existent element. The
reality is that tests on your end could be coded in such a way that failures won't always end up as a failed job.
The good news is that you can let Sauce know what actually happened with your tests. Check out our Pass/Fail API to do it from within
your Selenium tests.
We're constantly checking our service so we're likely already aware of an outage. Please check our status page and let us know if you don't see
Page 87
Copyright Sauce Labs 2015
Page 88
Copyright Sauce Labs 2015
This indicates that your Sauce Labs username and access key aren't provided by your tests as expected. To address this, please follow the right
tutorial for your programming language.
User Terminated
This message is used for tests manually interrupted using the Cancel or Breakpoint buttons in our website. Since both of these take control of
the virtual machine immediately, test assets like screenshots, video, or logs that require additional execution time will not be collected and made
available afterwards.
Timeout errors
Sauce Labs implements several types of timeouts for automated tests as safety nets to prevent unwanted consumption of minutes by runaway or
broken tests.
You can set these to different values using the DesiredCapabilities in the setup of your test, as described in the Timeouts section of the
Test Configuration and Annotation topic..
To better understand why these timeouts exist, let's look at the lifecycle of a Selenium command through the Sauce Labs service:
Here you can see the different types of interactions that happen in real time between the test script running in your own infrastructure, Sauce
Labs' service and the Selenium or Appium server running inside our virtual machines.
Here are some common timeout errors you may find, what causes them and how to address them:
Test did not see a new command for 90 seconds. Timing out
This error is shown when Sauce Labs doesn't receive a new command from your Selenium script in more than 90 seconds (the timeout's default
length.)
Using the previously shown graph as a reference, this would happen if step number 5 never happened. Without such a timeout, any tests that
lack a proper session ending request (generally rendered as a call to driver.quit() or browser.stop()) will keep running forever,
consuming all test minutes available in your account.
The most common cause for this is customers' test scripts crashing, getting forcefully interrupted or losing connectivity.
A less common but still possible cause is tests legitimately needing more than 90 seconds to send a new command to the browser. This happens
most often when network or disk IO occurs in between selenium API calls in your tests (DB queries, local file reads or changes.)
Page 89
Copyright Sauce Labs 2015
If that's the case, our idleTimeout desired capability can be used to modify Sauce's wait time for further commands. Check our idleTimeout
docs for more details on this.
This error is shown when Sauce Labs doesn't receive a response from Selenium to your Script's last command in more than 5 minutes (the
timeout's default length.)
Using the previously shown graph as a reference, this would happen if step number 3 never happened. Without such a timeout, any tests in
which the Selenium, Appium server or browser crashes would keep running forever, consuming all test minutes available in your account.
The most common causes for this are unresponsive javascript in your application or a bug in Selenium/Appium.
A less common but still possible cause is Selenium or Appium legitimately needing more than 5 minutes to run your command. If that's the case,
our commandTimeout desired capability can be used to have Sauce wait longer for your commands to complete in Selenium. Check our comma
ndTimeout docs for more details on this.
This error is shown when Sauce Labs finds an automated test still running after 30 minutes (the timeout's default length.)
The most common cause for this is an infinite loop in your tests that keep sending commands without an end clause.
It's not rare to find cases where tests legitimately need more than 30 minutes to complete. If that's the case, our maxDuration desired capability
can be used to have Sauce wait longer for your test to finish. Check ourmaxDuration docs for more details on this.
Similar to our commandTimeout, this means that Selenium took a long time to run the command -- usually the act of loading a page -- and your
test runner shut down the test before it might have timed out on Sauce's end. We recommend checking into why the page would take a long time
to load (perhaps because of perpetually-loading items from another domain), and if need be, extending the related timeout setting in your test
runner.
UnreachableBrowserException: Error communicating with the remote browser. It may have died
This error is thrown in Java when your test has timed out -- for example, due to the automatic 90-second idle timeout, which most often is caused
by a dropped Internet connection. Then, the test script attempts to send another command to Sauce, but the job has already finished, so the VM
is no longer available. Check your Internet connection, and try running your tests from a machine with a wired Ethernet connection.
The connection with your vm was lost and your job can't complete. You won't be charged for these
minutes
This message occurs when our infrastructure loses communication with our vm and can't regain that connection after a reasonable time. If you
only get this message rarely and randomly, it is probably a fluke on our end caused by an infrastructure blip.
However, if you are experiencing this error repeatedly for a specific test or set of tests there may be an issue on your end that is causing the
failure. For example, if the error regularly appears after a specific selenium command there could be something wrong with the test that is causing
selenium to crash. We have also seen issues with prerun executables: your script could be crashing the vm in any number of exciting ways, but
the most common we've seen is consuming too much memory. We even had a situation once where a customer's script killed processes in a
windows session, including the process we use to run jobs!
The VM's disk has filled up. Selenium likely crashed as a result.
Our VMs have virtual disks which, just like hardware disks, can fill up. We make sure that our virtual machines have at least 3G free when we
start a job, but sometimes complex/long-running tests fill up the guest machine's allocated space. This causes selenium to crash, which ends your
test.
The best thing you can do to avoid this failure is to break out your long tests into shorter tests and/or make sure that your tests are not filling up a
lot of disk space on the VM.
Page 90
Copyright Sauce Labs 2015
Check to make sure that the browser, version, and platform settings you're using are in our supported list of platforms.
This error usually means that you've manually set a Selenium version that is too old to handle a more recent browser version. It should be
resolved by choosing a newer version of Selenium, or omitting this setting altogether.
The twin sibling of "Unsupported version", this message means that something a little more unusual is off in your test setup. Usually, this means
that you're specifying a Selenium version that isn't compatible with the browser/version/OS you've selected. (For example, you should not be
setting this for any mobile tests.)
Try simply omitting that setting, and if you still see the issue, feel free to contact our support team with a description of the issue and a copy of
your setup code.
This means that your test runner decided to end the job before it had fully initialized on Sauce's end. There are a few potential causes:
You're running too many tests at a time: Check the left sidebar on your Account page (https://saucelabs.com/account). It shows a
"Parallel tests" number, which is the maximum number of tests you can run at a time, based on your subscription level. If your account
can run 2 parallel tests, and you're launching 10, 8 will be "queued" until one of your tests finishes and a slot frees up. However, if this
takes a long time, your test runner may choose to end the queued jobs after a few minutes instead of waiting. Just make sure you're
launching a reasonable number of simultaneous tests for your account.
High job wait times: Check our status page (http://status.saucelabs.com/) and/or follow @sauceops on Twitter for up-to-the-minute news
about any issues within the service. If something causes demand for certain VMs to stack up, your jobs may be queued and (as above)
terminated by your test runner.
Tests that end this way are never taken out of your minutes.
This message means that an error has been detected in the VM or in Selenium, which caused the test to behave abnormally, and Sauce detected
this and shut down the job. These are very rare and usually do not recur. If you do see more than one on the same test, let us know.
UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of
the remote server or browser start-up failure
This error is thrown on the client side, when Selenium isn't able to reach our testing servers to start a session. Try running this on the command
line:
telnet ondemand.saucelabs.com 80
If you do receive this successful message, and still can't start a session, send that output to our support team and we'll troubleshoot further.
Otherwise, there's definitely something blocking the connection on your end. If so, you'll need to talk with your IT/network team to ensure that the
required ports can be made available.
Page 91
Copyright Sauce Labs 2015
Page 92
Copyright Sauce Labs 2015
You can write tests against multiple mobile platforms using the same API
You can write and run your tests using any language or test framework
It's an open-source tool that you can easily contribute to
You save the time it takes to set up the Appium server locally
You don't have to install/configure the mobile emulators/simulators in your local environment
You don't have to make any modifications to the source code of your application
You can start scaling your tests instantly
For an in-depth explanation of what Appium is, how it works, and the various technologies behind it, check out the official Appium Documentation.
The driver address in you test script is what points the test to the Sauce Labs cloud, for example http://SAUCE_USERNAME:SAUCE_ACCESS_K
EY@ondemand.saucelabs.com:80/wd/hub. Once you execute the test using the test framework of your choice, Sauce Labs initializes its own
Appium server using the specifications taken from your desired capabilities. What happens after that depends on the type of mobile platform
you're testing against.
iOS Tests
After the mobile application is initialized, the Appium server takes the driver commands in your test script, which are in a WebDriver JSON Wire
Protocol format, and converts them into UIAutomation JavaScript commands that can be understood by Apple Instruments. These commands,
once converted, are sent to your iOS mobile application via Apple Instruments, which executes the commands against your mobile application in
the simulator/device.
The responses from your mobile application are received by Apple Instruments, sent to UIAutomation, and relayed to the Appium server in the
Sauce Labs cloud. The Appium server then converts the UIAutomation JavaScript responses back into WebDriver JSON Wire Protocol format,
and sends the JSON responses to your test script.
Android Tests
After the mobile application is initialized, the Appium server receives your test script commands and launches your mobile application in the
emulator/device that you've specified. Appium then takes the driver commands in your test script, which are in a WebDriver JSON Wire Protocol f
ormat, and converts them into UIAutomator Java commands. UIAutomator is the library provided by Google as part of the Android SDK, and is
also the library that Appium uses to automate your Android mobile application tests.
In the case where you are connecting to the Selendroid automation backend, Appium simply proxies all requests to the Selendroid server running
on the emulator/device.
The response from your mobile application are received by UIAutomator and relayed to the Appium server in the Sauce Labs cloud. The Appium
server then converts the UIAutomator Java responses back into WebDriver JSON Wire Protocol format, and send the JSON responses back to
your test script.
Appium hides all of this complexity from your test script. Your test script thinks it's communicating with your mobile application, but in reality it is
communicating with Appium's implementation of the WebDriver API. The fact that Appium is running your mobile application in the appropriate
simulator, emulator or device, and wrapping up all of the communications with your mobile application, including the command conversions,
remains completely hidden, and your test script is none the wiser.
Appium Resources
For more information, feel free to visit the resources listed below:
Appium
Introduction to Appium Concepts
Page 93
Copyright Sauce Labs 2015
Appium Docs
Appium Discussion Group
Appium on Github
Selenium WebDriver JSON Wire Protocol
Selenium
Apple UI Automation Documentation
Android UI Testing Documentation
Page 94
Copyright Sauce Labs 2015
Page 95
Copyright Sauce Labs 2015
Emulator Specifics
Name RAM Heap Size Data Partition Screen Diagonal Resolution Pixel DPI (dots per GoogleAPI
Size Length Density inch) version*
DEFAULT: Generic 512 MB 2.3 to 4.2: 64MB 200MB 4.0" 480x800 HDPI 233 4.4/5.0
Phone 4.3 and above: 4.2 and 4.3:
32MB 300MB
Generic Tablet 512 MB 2.3-4.3: 64 MB 200MB 7.0" 800x1280 HDPI 216 4.4/5.0
4.4+: 32 MB 4.2 and 4.3:
300MB
Motorola Atrix HD 1024 64MB 200MB 4.5" 720x1280 XHDPI 326 N/A
MB
Motorola Photon Q 1024 32MB 200MB 4.3" 540x960 HDPI 256 N/A
MB
Motorola Razr Maxx HD 1024 64MB 200MB 4.7" 720x1280 XHDPI 312 N/A
MB
Motorola Droid 4 1024 32MB 200MB 4.0" 540x960 HDPI 275 N/A
MB
Motorola Droid Razr 1024 32MB 200MB 4.3" 540x960 HDPI 256 N/A
MB
Amazon Kindle Fire 512 MB 16MB 200MB 7.0" 600x1024 MDPI 170 N/A
Amazon Kindle Fire HD 1907 32MB 200MB 8.9" 720x1220 *** MDPI 160 4.4/5.0
MB
Samsung Galaxy S 512 MB 32MB 200MB 4.0" 480x800 HDPI 233 N/A
Samsung Galaxy S2 1024 32MB 200MB 4.3" 480x800 HDPI 217 N/A
MB
Samsung Galaxy S3 1900 64MB 200MB 4.8" 720x1280 XHDPI 306 4.4/5.0
MB
Samsung Galaxy S4 1900 64MB 200MB 5.0" 720x1280 *** XHDPI 293 4.4/5.0
MB
Samsung Galaxy Nexus 1024 64MB 200MB 4.6" 720x1280 XHDPI 320 4.4/5.0
MB
Samsung Galaxy Note 1024 64MB 200MB 5.3" 800x1280 XHDPI 285 N/A
MB
Samsung Galaxy Note 1907 32MB 200MB 10.1" 800x1280 MDPI 150 N/A
10.1 MB
Samsung Galaxy Note 2 1907 32MB 200MB 5.5" 720x1280 HDPI 267 N/A
MB
Samsung Galaxy Tab 2 1024 64MB 200MB 10.1" 800x1280 MDPI 150 N/A
10.1 MB
Samsung Galaxy Tab 3 1024 32MB 200MB 7.0" 600x1024 MDPI 170 N/A
7.0 MB
HTC One X 1024 64MB 200MB 4.7" 720x1280 XHDPI 312 N/A
MB
HTC Evo 3D 1024 32MB 200MB 4.3" 540x960 HDPI 256 N/A
MB
HTC Wildfire S 512 MB 16MB 200MB 3.2" 320x480 MDPI 180 N/A
Page 96
Copyright Sauce Labs 2015
Google Nexus 4 1907 64MB 200MB 4.7" 768x1280 XHDPI 318 4.4/5.0
MB
Google Nexus 7 C 1024 4.1 to 4.3: 64MB 200MB 7.0" 800x1280 TVDPI 216 4.4/5.0
MB 4.4: 32MB
Google Nexus 7 FHD 1907 4.3: 64MB 200MB 7.0" 800x1280 TVDPI 216 4.4/5.0
MB 4.4: 32MB
Sony Xperia X10 384 MB 32MB 200MB 4.0" 480x854 HDPI 245 N/A:
Page 97
Copyright Sauce Labs 2015
Android 2.3, 4.0 and later for Mobile Native Application and Mobile Hybrid Application testing
Page 98
Copyright Sauce Labs 2015
iOS Requirements
Android Requirements
The mobile application must be compiled for the emulator/device version of your choice
The mobile application must have internet permissions
The mobile application must be hosted in a place that Sauce Labs can access, for example:
A remote location, for example a GitHub Repository
Your Temporary Sauce Storage
Page 99
Copyright Sauce Labs 2015
Page 100
Copyright Sauce Labs 2015
1. Click the manual session outside the boundary of the iOS simulator.
The header should change to Finder.
2. Open the Desktop version of Safari.
The version of Safari running on the Mac which is hosting the simulator.
3. Open the iOS Simulator again.
4. In the iOS version of Safari, open your site.
5. Go back to the Desktop version of Safari and open the Develop menu.
6. Select the type of simulator you're testing against.
For example, iPad or iPhone.
7. Click yourpage.html.
You should now see the same developer tools as though you were in Safari itself.
Page 101
Copyright Sauce Labs 2015
Prerequisites
Before you get started with testing on Sauce, you should check out the Running Emulator and Simulator Mobile Tests and the Running
Emulator and Simulator Mobile Tests
If you're interested in testing mobile applications, you should read the Running Emulator and Simulator Mobile Tests
If you want to test applications that are behind a firewall or on localhost, you should read up on Sauce Connect, which enables you to
create a secure tunnel between the location where your application resides and the Sauce Labs testing infrastructure
If you aren't already, you should familiarize yourself with using Selenium for Web application testing, and Appium for mobile application
testing
Automated testing of both Web and mobile applications on Sauce Labs boils down to a few basic steps:
You can use the Platform Configurator to set the desired capabilities for both Selenium and Appium tests in your preferred
language.
You can also use the REST API or the WebDriver API to further configure your jobs with timeouts, annotations (a recommended
best practice for managing your tests results, and for managing builds in your continuous integration pipeline), and other job
functionality.
Both the Running Emulator and Simulator Mobile Tests and Tutorial topics include code samples that illustrate how to write
automated tests for Web applications in various languages, while the topics under Running Emulator and Simulator Mobile Tests
illustrate how to write scripts for testing iOS and Android mobile applications.
1. Run your tests and watch the results appear on your Sauce Labs dashboard, complete with video, screenshots, and logs.
Once you've mastered the basics, you'll be ready to move on to more advanced functionality, like running your tests in parallel to speed up your
testing process, and integrating your tests on Sauce into your continuous integration pipeline.
Page 102
Copyright Sauce Labs 2015
Mobile Native
This type of application is developed for an specific platform, for example, iOS or Android, using the native SDKs provided by the platform vendor,
and distributed to users via the appropriate app store.
Mobile Web
A mobile web application is formally referred to as a mobile website. It can be accessed through a browser, for example Mobile Safari, Chrome,
etc., in a mobile simulator/emulator or real device.
Mobile Hybrid
This type of application is part mobile native app and part mobile web app. Just like mobile native apps, you can find and download mobile hybrid
apps using Apple’s App Store or the Google Play Store. A mobile hybrid app, however, looks like a mobile website that would be accessed
through a browser, but in this case the browser is an embedded webview within the application that displays some HTML.
Page 103
Copyright Sauce Labs 2015
The best way to test on different Android emulators screen sizes is by using the different Android Emulator Skins . For instance, if you use our Pla
tform Configurator you'll see the available skins for the different Android versions (e.g Google Nexus 7 HD, LG Nexus 4, Samsung Galaxy Nexus,
Samsung Galaxy S3, etc). Some of these skins are tablets, for example the Google Nexus 7C is a tablet which has a very large resolution and
very high density.
How can I run manual tests for my mobile native app or mobile hybrid app?
Sauce Labs doesn't support manual tests for mobile native app or mobile hybrid app tests. Check out
Types of Mobile Tests for more information.
Android Emulators have software buttons and a hardware keyboard. In a regular Android emulator the device buttons are software buttons
displayed on the right size of the emulator. For the Android emulators with different skins (e.g Google Nexus 7 HD, LG Nexus 4, Samsung Galaxy
Nexus, Samsung Galaxy S3, etc) the device buttons are also software buttons that are overplayed on top of the skin. For instance, if you hover
the mouse around the edges of any of our Android emulators with an specified skin, a hover icon will appear and you should be able to find
whatever buttons actually exist on the device that the skinned emulator is trying to emulate (e.g power button along the top, volume buttons along
the edge, back/home buttons right below the screen, etc).
For older versions of Android Appium might not be supported. For instance, Appium is only supported in Android versions 4.4 or later for Mobile
Web Application tests, and Android versions 2.3, 4.0 and later for Mobile Native Application and Mobile Hybrid Application tests.
For those versions in which Appium is not supported you can request an emulator driven by Webdriver + Selendroid. All you need to do is use
our Platforms Configurator and select Selenium for the API instead of Appium.
In the Sauce Labs test you will notice that the top of the emulator says "AndroidDriver Webview App". In addition, you will notice that you will get a
"Selenium Log" tab which has the output of the Selendroid driver.
With an emulator driven by Webdriver + Selendroid you will be able to test Mobile Web Application only. You should be able to select any Android
emulator version from 4.0 to the latest version and any Android emulator skin (e.g "deviceName":"Samsung Galaxy Tab 3 Emulator").
For older versions of iOS Appium might not be supported. For instance, Appium is supported in iOS versions 6.1 and later. For earlier versions of
iOS the tool or driver used to drive your mobile applications automated test is called iWebdriver.
To obtain a simulator driven by iWebdriver use our Platforms Configurator and select Selenium for the API instead of Appium. With an emulator
driven by iWebdriver you will be able to test Mobile Web Applicationonly. In addition, in the Sauce Labs test you will notice a "Selenium Log" tab
which has the output of iWebdriver.
Currently the only browser that can be automated in our Android emulators is the stock browser (i.e Browser). The Android stock browser is an
Android flavor of 'chromium' which presumably implies that its behavior is closer to that of Google Chrome.
Page 104
Copyright Sauce Labs 2015
How can I test with mobile real devices instead of using the simulators or emulators?
The mobile real device cloud is a new feature that Sauce Labs is currently working on. For more information about this feature please directly
email one of our sales team representatives (saro@saucelabs.com).
Page 105
Copyright Sauce Labs 2015
Page 106
Copyright Sauce Labs 2015
Page 107
Copyright Sauce Labs 2015
Example Java Script for Testing Android Mobile Applications on Sauce Labs
Page 108
Copyright Sauce Labs 2015
package com.saucelabs.appium;
import java.io.File;
import java.net.URL;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
@Before
public void setUp() throws Exception {
File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, "../../../apps/ApiDemos/bin");
File app = new File(appDir, "ApiDemos-debug.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName","Android Emulator");
capabilities.setCapability("platformVersion", "4.4");
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("appPackage", "io.appium.android.apis");
capabilities.setCapability("appActivity", ".ApiDemos");
driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"),
capabilities);
}
@After
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void apiDemo(){
WebElement el = driver.findElement(By.name("Animation"));
assertEquals("Animation", el.getText());
el = driver.findElementByClassName("android.widget.TextView");
assertEquals("API Demos", el.getText());
el = driver.findElement(By.name("App"));
el.click();
List<WebElement> els =
driver.findElementsByClassName("android.widget.TextView");
assertEquals("Activity", els.get(2).getText());
}
}
Page 109
Copyright Sauce Labs 2015
Example Node.js Script for Testing Android Mobile Applications on Sauce Labs
require("./helpers/setup");
var wd = require("wd"),
_ = require('underscore'),
serverConfigs = require('./helpers/appium-servers');
before(function () {
var serverConfig = process.env.SAUCE ?
serverConfigs.sauce : serverConfigs.local;
driver = wd.promiseChainRemote(serverConfig);
require("./helpers/logging").configure(driver);
after(function () {
return driver
.quit()
.finally(function () {
if (process.env.SAUCE) {
return driver.sauceJobStatus(allPassed);
}
});
});
afterEach(function () {
allPassed = allPassed && this.currentTest.state === 'passed';
});
Page 110
Copyright Sauce Labs 2015
.back()
.elementByName('App')
.should.eventually.exist
.elementsByAndroidUIAutomator('new UiSelector().clickable(true)')
.should.eventually.have.length(12)
.elementsByAndroidUIAutomator('new UiSelector().enabled(true)')
.should.eventually.have.length.above(20)
.elementByXPath('//android.widget.TextView[@text=\'API Demos\']')
Page 111
Copyright Sauce Labs 2015
.should.exists;
});
});
Page 112
Copyright Sauce Labs 2015
import unittest
class SimpleAndroidTests(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '4.2'
desired_caps['deviceName'] = 'Android Emulator'
desired_caps['app'] = PATH(
'../../../sample-code/apps/ApiDemos/bin/ApiDemos-debug.apk'
)
def tearDown(self):
# end the session
self.driver.quit()
def test_find_elements(self):
el = self.driver.find_element_by_accessibility_id('Graphics')
el.click()
el = self.driver.find_element_by_accessibility_id('Arcs')
self.assertIsNotNone(el)
self.driver.back()
el = self.driver.find_element_by_accessibility_id("App")
self.assertIsNotNone(el)
els = self.driver.find_elements_by_android_uiautomator("new
UiSelector().clickable(true)")
self.assertGreaterEqual(12, len(els))
self.driver.find_element_by_android_uiautomator('text("API Demos")')
def test_simple_actions(self):
el = self.driver.find_element_by_accessibility_id('Graphics')
el.click()
el = self.driver.find_element_by_accessibility_id('Arcs')
el.click()
Page 113
Copyright Sauce Labs 2015
self.driver.find_element_by_android_uiautomator('new
UiSelector().text("Graphics/Arcs")')
Page 114
Copyright Sauce Labs 2015
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(SimpleAndroidTests)
unittest.TextTestRunner(verbosity=2).run(suite)
Page 115
Copyright Sauce Labs 2015
Example Ruby Script for Testing Android Mobile Applications on Sauce Labs
This example uses environment variables for your Sauce Labs authentication credentials, and the sauce-whisk gem.
require 'rubygems'
require 'spec'
require 'appium_lib'
require 'sauce_whisk'
describe 'Notepad' do
def desired_caps
{
caps: {
:'appium-version' => '1.3.4',
platformName: 'Android',
platformVersion: '4.3',
deviceName: 'Android Emulator',
app: 'http://appium.s3.amazonaws.com/NotesList.apk',
name: 'Ruby Appium Android example'
},
appium_lib: {
wait: 60
}
}
end
before do
Appium::Driver.new(desired_caps).start_driver
end
after do
driver_quit
end
Page 116
Copyright Sauce Labs 2015
find('Save').click
note_count = ids('android:id/text1').length
note_count.must_equal 1
texts.last.text.must_equal 'This is a new note, from Ruby'
end
end
# Because WebDriver doesn't have the concept of test failure, use the Sauce
# Labs REST API to record job success or failure
user = ENV['SAUCE_USERNAME']
key = ENV['SAUCE_ACCESS_KEY']
if user && !user.empty? && key && !key.empty?
Page 117
Copyright Sauce Labs 2015
Page 118
Copyright Sauce Labs 2015
Page 119
Copyright Sauce Labs 2015
Example Java Script for Testing iOS Mobile Applications on Sauce Labs
This example uses the JUnit testing framework and authenticates to Sauce Labs using credentials set as environment variables.
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
@Rule
public SauceOnDemandTestWatcher resultReportingTestWatcher = new
SauceOnDemandTestWatcher(this, authentication);
@Override
public String getSessionId() {
return sessionId;
}
@Before
public void setUp() throws MalformedURLException {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.1");
desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone
Simulator");
desiredCapabilities.setCapability(MobileCapabilityType.APP,
"http://appium.s3.amazonaws.com/TestApp6.0.app.zip");
desiredCapabilities.setCapability("appiumVersion", "1.3.4");
desiredCapabilities.setCapability("name", name.getMethodName());
Page 120
Copyright Sauce Labs 2015
@After
public void tearDown() {
System.out.println("Link to your job: https://saucelabs.com/jobs/" +
this.getSessionId());
driver.quit();
}
@Test
public void testUIComputation() {
// they should be the same size, and the first should be above the second
assertTrue(fieldOne.getLocation().getY() < fieldTwo.getLocation().getY());
assertEquals(fieldOne.getSize(), fieldTwo.getSize());
// is sum equal?
String sum = driver.findElementsByClassName("UIAStaticText").get(0).getText();
TestCase.assertEquals(Integer.parseInt(sum), 20);
Page 121
Copyright Sauce Labs 2015
Page 122
Copyright Sauce Labs 2015
require("./helpers/setup");
var wd = require("wd"),
_ = require('underscore'),
Q = require('q'),
serverConfigs = require('./helpers/appium-servers');
before(function () {
var serverConfig = process.env.SAUCE ?
serverConfigs.sauce : serverConfigs.local;
driver = wd.promiseChainRemote(serverConfig);
require("./helpers/logging").configure(driver);
after(function () {
return driver
.quit()
.finally(function () {
if (process.env.SAUCE) {
return driver.sauceJobStatus(allPassed);
}
});
});
afterEach(function () {
allPassed = allPassed && this.currentTest.state === 'passed';
});
function populate() {
var seq = _(['IntegerA', 'IntegerB']).map(function (name) {
return function (sum) {
return driver.waitForElementByName(name, 3000).then(function (el) {
var x = _.random(0,10);
sum += x;
return el.type('' + x).then(function () { return sum; })
.elementByName('Done').click().sleep(1000); // dismissing keyboard
}).then(function () { return sum; });
Page 123
Copyright Sauce Labs 2015
};
});
return seq.reduce(Q.when, new Q(0));
}
Page 124
Copyright Sauce Labs 2015
});
});
Page 125
Copyright Sauce Labs 2015
Example PHP Script for Testing iOS Mobile Applications on Sauce Labs
This script includes using Sausage, a set of libraries and classes developed for running PHP tests with PHPUnit, either locally or on Sauce Labs.
require_once "vendor/autoload.php";
define("APP_URL", "http://appium.s3.amazonaws.com/TestApp6.0.app.zip");
Page 126
Copyright Sauce Labs 2015
Page 127
Copyright Sauce Labs 2015
Example Python Script for Testing iOS Mobile Applications on Sauce Labs
This test assumes you have set your Sauce Labs authentication credentials as environment variables.
platforms = [{
'platformName': 'iOS',
'platformVersion': '7.1',
'deviceName': 'iPhone Simulator',
'app': 'http://appium.s3.amazonaws.com/TestApp6.0.app.zip',
'appiumVersion': '1.3.4'
}]
@on_platforms(platforms)
class SimpleIOSSauceTests(SauceTestCase):
def _populate(self):
# populate text fields with two random numbers
els = self.driver.find_elements_by_class_name('UIATextField')
self._sum = 0
for i in range(2):
rnd = randint(0, 10)
els[i].send_keys(rnd)
self._sum += rnd
def test_ui_computation(self):
# populate text fields with values
self._populate()
# is sum equal ?
sum = self.driver.find_elements_by_class_name("UIAStaticText")[0].text
self.assertEqual(int(sum), self._sum)
Page 128
Copyright Sauce Labs 2015
Example Ruby Script for Testing iOS Mobile Applications on Sauce Labs
require 'rubygems'
require 'appium_lib'
APP_PATH = '../../apps/TestApp/build/release-iphonesimulator/TestApp.app'
desired_caps = {
caps: {
platformName: 'iOS',
versionNumber: '8.1',
deviceName: 'iPhone 6',
app: APP_PATH,
},
appium_lib: {
sauce_username: nil, # don't run on Sauce
sauce_access_key: nil
}
}
Page 129
Copyright Sauce Labs 2015
module Calculator
Module IOS
# Add all the Appium library methods to Test to make
# calling them look nicer.
Appium.promote_singleton_appium_methods Calculator
# Get the first static text field, then get its text
actual_sum = first_text.text
raise unless actual_sum == (expected_sum.to_s)
# Or by find
find('Cancel').click
Page 130
Copyright Sauce Labs 2015
Page 131
Copyright Sauce Labs 2015
Page 132
Copyright Sauce Labs 2015
Page 133
Copyright Sauce Labs 2015
Prerequisites
Installing Gallio and MBUnit
Code Sample
GuineaPigTests.cs
Constants.cs
Run the Test
Prerequisites
You'll need to have these components installed to set up MBUnit testing on Sauce with C# .NET.
Visual Studio
Selenium DLLs for .NET installed and referenced by your project
Gallio and MBUnit Bundle
1. In the Visual Studio Tools menu, go to Library Package Manager > Manage Nuget Package for Solution. This will open the Manage
NuGet Packages screen.
2. Click Online, and then click Next.
3. In the Search Packages field enter Gallio, and then click Search.
4. In the search results, select Gallio & MbUnit, and then click Install.
5. After installing Gallio & MbUnit, select Gallio Bundle from the search results, and then click Install.
Code Sample
GuineaPigTests.cs
This example verifies the title, a link, and the presence of a user agent element on the page https://saucelabs.com/test/guinea-pig. It connects to
Sauce Labs, run commands to remote control the target browser, and reports the results. It also includes the code for running tests in parallel and
reporting the results to your Sauce Labs dashboard.
You can use the Platform Configurator to specify the desired capabilities for any browser/platform combination you want for your test.
namespace SauceLabs.SeleniumExamples
{
/// <summary>tests for the sauce labs guinea pig page</summary>
[TestFixture]
[Header("browser", "version", "platform")] // name of the parameters in the rows
[Row("internet explorer", "11", "Windows 7")] // run all tests in the fixture against
IE 11 for windows 7
[Row("chrome", "35", "linux")] // run all tests in the fixture against chrome 35 for
linux
Page 134
Copyright Sauce Labs 2015
[Row("safari","6","OS X 10.8")] // run all tests in the fixture against safari 6 and
mac OS X 10.8
public class GuineaPigTests
{
#region Setup and Teardown
return _Driver;
}
\#endregion
Page 135
Copyright Sauce Labs 2015
\#region Tests
[Test, Parallelizable] // denotes that this method is a test and can be run in
parallel
public void LinkWorks(string browser, string version, string platform)
{
// start the remote webdriver session with sauce labs
var _Driver = _Setup(browser, version, platform);
CleanUp(_Driver);
}
Assert.IsNotNull(useragent);
CleanUp(_Driver);
}
Page 136
Copyright Sauce Labs 2015
\#endregion
}
}
Constants.cs
Use this class to set your Sauce Labs account name and access key. You can find these in the User Profile menu of your Sauce Labs
dashboard.
desiredCapabilites.SetCapability("username", Constants.SAUCE_LABS_ACCOUNT_NAME);
// supply sauce labs username
desiredCapabilites.SetCapability("accessKey", Constants.SAUCE_LABS_ACCOUNT_KEY);
// supply sauce labs account key
Where you would substitute your account name and access key for Constants.SAUCE_LABS_ACCOUNT_NAME and Constants.SAU
CE_LABS_ACCOUNT_KEY. However, as a best practice we recommend using environment variables stored in a local file or system for
authentication, as this improves the security of your tests, and enables other members of your team to run tests on your account by
referencing the authentication credentials.
{
/// <summary>contains constants used by the tests such as the user name and
password for the sauce labs</summary>
internal static class Constants
{
/// <summary>name of the sauce labs account that will be used</summary>
internal const string SAUCE_LABS_ACCOUNT_NAME = "Your Account Name";
/// <summary>account key for the sauce labs account that will be
used</summary>
internal const string SAUCE_LABS_ACCOUNT_KEY = "Your Access Key";
// NOTE:
// To change the maximum number of parallel tests edit DegreeOfParallelism in
AssemblyInfo.cs
}
}
Page 137
Copyright Sauce Labs 2015
6.
This launches the Gallio test GUI where you can run your tests. The DLL for this project should be preloaded. If it isn’t, you can open it
from the File menu.
Page 138
Copyright Sauce Labs 2015
NUnit is a unit-test framework for all .Net languages, written entirely in C# and designed to take advantage of many .NET language features, for
example custom attributes and other reflection-related capabilities. PNUnit, which stands for "Parallel NUnit," is an extension of NUnit that allows
NUnit tests to run in parallel using a special .conf configuration file that specifies the tests to be executed and where they should run, whether
on the same machine or on another machine on the network. For more information and documentation about the framework, as well as how to
use it in your testing, you can visit the official NUnit website.
Prerequisites
You'll need to have these components installed to set up PNUnit testing on Sauce with C# .NET.
Visual Studio
Selenium DLLs for .NET installed and referenced by your project
NUnit + PNUnit Bundle
After you've set up your project in Visual Studio, you need to make sure that it references the required Selenium DLLs for .NET.
Install NUnit + PNUnit and Import the Libraries into Your Project
Code Example
SaucePNUnit_Test.cs
Page 139
Copyright Sauce Labs 2015
using System.Threading;
using System.Web;
using System.Text;
using System.Net;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace SauceLabs.NUnitExample
{
[TestFixture()]
public class SaucePNUnit_Test
{
private IWebDriver driver;
private string[] testParams;
[SetUp]
public void Init()
{
testParams = PNUnitServices.Get().GetTestParams();
String params1 = String.Join(",", testParams);
Console.WriteLine(params1);
String browser = testParams[0];
String version = testParams[1];
String platform = testParams[2];
DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability("browserName", browser);
caps.SetCapability(CapabilityType.Version, version);
caps.SetCapability(CapabilityType.Platform, platform);
caps.SetCapability("username", Constants.SAUCE_LABS_ACCOUNT_NAME);
caps.SetCapability("accessKey", Constants.SAUCE_LABS_ACCOUNT_KEY);
caps.SetCapability("name", TestContext.CurrentContext.Test.Name);
Console.WriteLine("Capabilities" + caps.ToString());
driver = new RemoteWebDriver(new
Uri("http://ondemand.saucelabs.com:80/wd/hub"), caps, TimeSpan.FromSeconds(420));
}
[Test]
public void googleTest()
{
driver.Navigate().GoToUrl("http://www.google.com");
StringAssert.Contains("Google", driver.Title);
IWebElement query = driver.FindElement(By.Name("q"));
query.SendKeys("Sauce Labs");
query.Submit();
}
[TearDown]
public void Cleanup()
{
// Gets the status of the current test
bool passed = TestContext.CurrentContext.Result.Status ==
TestStatus.Passed;
try
{
// Logs the result to Sauce Labs
((IJavaScriptExecutor)driver).ExecuteScript("sauce:job-result=" +
(passed ? "passed" : "failed"));
}
finally
{
// Terminates the remote webdriver session
Page 140
Copyright Sauce Labs 2015
driver.Quit();
}
}
}
Page 141
Copyright Sauce Labs 2015
This example test opensGoogle, verifies that "Google" is the title of the page, and then searches for Sauce Labs.
Constants.cs
}
}
Use this class to set your Sauce Labs account name and access key as environment variables, as shown in the example test. You can find these
in the User Profile menu of your Sauce Labs dashboard, under User Settings.
caps.SetCapability("username", Constants.SAUCE_LABS_ACCOUNT_NAME);
caps.SetCapability("accessKey", Constants.SAUCE_LABS_ACCOUNT_KEY);
However, Sauce Labs recommends using environment variables for authentication as a best practice. This adds a layer of security to
your tests, and allow other members of your team to share authentication credentials.
sauce_test.conf
Page 142
Copyright Sauce Labs 2015
Use this file to set up the configuration for your PNUnit testing.
1. Build the project by going to Build > Build Solution, or use the CTRL-SHIFT-B shortcut.
2. Change the sauce_test.conf file to specify your project .dll and tests, and the browsers you want to run the tests against.
3. Add the .dll file of your project, sauce_test.conf, and any other referenced .dll files like the Selenium .DLL files, into the bin of the
directory where you saved NUnit.
4. Open an Administrator command prompt.
5. Go to the NUnit > Bin directory.
6. Enter start pnunit-agent.exe agent.conf.
This will launch the PNUnit agent and open up a new PNUnit agent command prompt.
7. In the command prompt, enter pnunit-launcher.exe sauce_test.conf.
This will launch your tests to the Sauce Labs dashboard, where you will be able to see them run.
Page 143
Copyright Sauce Labs 2015
Page 144
Copyright Sauce Labs 2015
1. https://github.com/ndmanvar/SeleniumJavaJunit
2. https://github.com/ndmanvar/SeleniumJavaTestNG
Page 145
Copyright Sauce Labs 2015
/**
* Constructs a {@link SauceOnDemandAuthentication} instance using the supplied
user name/access key. To use the authentication
* supplied by environment variables or from an external file, use the no-arg
{@link SauceOnDemandAuthentication} constructor.
*/
public SauceOnDemandAuthentication authentication = new
SauceOnDemandAuthentication("${userName}", "${accessKey}");
/**
* JUnit Rule which will mark the Sauce Job as passed/failed when the test
succeeds or fails.
*/
@Rule
public SauceOnDemandTestWatcher resultReportingTestWatcher = new
SauceOnDemandTestWatcher(this, authentication);
/**
* Represents the browser to be used as part of the test run.
*/
private String browser;
/**
* Represents the operating system to be used as part of the test run.
*/
private String os;
/**
* Represents the version of the browser to be used as part of the test run.
*/
private String version;
/**
* Instance variable which contains the Sauce Job Id.
*/
private String sessionId;
/**
* The {@link WebDriver} instance which is used to perform browser interactions
with.
*/
private WebDriver driver;
Page 146
Copyright Sauce Labs 2015
/**
* Constructs a new instance of the test. The constructor requires three string
parameters, which represent the operating
* system, version and browser to be used when launching a Sauce VM. The order of
the parameters should be the same
* as that of the elements within the {@link #browsersStrings()} method.
* @param os
* @param version
* @param browser
*/
public SampleSauceTest(String os, String version, String browser) {
super();
this.os = os;
this.version = version;
this.browser = browser;
}
/**
* @return a LinkedList containing String arrays representing the browser
combinations the test should be run against. The values
* in the String array are used as part of the invocation of the test constructor
*/
@ConcurrentParameterized.Parameters
public static LinkedList browsersStrings() {
LinkedList browsers = new LinkedList();
browsers.add(new String[]{"Windows 8.1", "11", "internet explorer"});
browsers.add(new String[]{"OSX 10.8", "6", "safari"});
return browsers;
}
/**
* Constructs a new {@link RemoteWebDriver} instance which is configured to use
the capabilities defined by the {@link #browser},
* {@link #version} and {@link #os} instance variables, and which is configured to
run against ondemand.saucelabs.com, using
* the username and access key populated by the {@link #authentication} instance.
*
* @throws Exception if an error occurs during the creation of the {@link
RemoteWebDriver} instance.
*/
@Before
public void setUp() throws Exception {
Page 147
Copyright Sauce Labs 2015
/**
* Runs a simple test verifying the title of the amazon.com homepage.
* @throws Exception
*/
@Test
public void amazon() throws Exception {
driver.get("http://www.amazon.com/");
assertEquals("Amazon.com: Online Shopping for Electronics, Apparel, Computers,
Books, DVDs & more", driver.getTitle());
}
/**
* Closes the {@link WebDriver} session.
*
* @throws Exception
*/
@After
public void tearDown() throws Exception {
driver.quit();
}
/**
*
* @return the value of the Sauce Job id.
*/
@Override
public String getSessionId() {
Page 148
Copyright Sauce Labs 2015
return sessionId;
}
}
The Sauce Labs Parallelized JUnit runner uses the junit.parallel.threads System property to control how many threads it runs. You can
set this by updating the <threadcount> in your Maven pom.xml file, as shown in the example. Similarly, if you were using Ant as your project
comprehension tool, you would update the <threadCount> attribute in your Parallel task.
Page 149
Copyright Sauce Labs 2015
Page 150
Copyright Sauce Labs 2015
Page 151
Copyright Sauce Labs 2015
These examples, for Mac OS X/Linux and Windows, show the commands used to specify the path to the test file you want to run, and to
simultaneously run two instances of PHPUnit. In these examples, the path to the WebDriverDemo.php demo test is shown, while the -p 2 arg
uments set the number of instances to run.
Page 152
Copyright Sauce Labs 2015
Page 153
Copyright Sauce Labs 2015
This is the command you would issue to Nose to run the tests:
Page 154
Copyright Sauce Labs 2015
browsers = [{
"platform": "Windows 10",
"browserName": "internet explorer",
"version": "11"
}, {
"platform": "OS X 10.11",
"browserName": "safari",
"version": "8.1"
}]
username = 'YOUR_SAUCE_USERNAME'
access_key = 'YOUR_SAUCE_ACCESSKEY'
def launchBrowser(caps):
caps['name'] = inspect.stack()[1][3]
return webdriver.Remote(
command_executor = "http://%s:%s@ondemand.saucelabs.com:80/wd/hub" %
(username, access_key),
desired_capabilities = caps);
def teardown_func():
global driver
driver.quit()
sauce_client = SauceClient(username, access_key)
status = sys.exc_info() == (None, None, None)
sauce_client.jobs.update_job(driver.session_id, passed=status)
@with_setup(None, teardown_func)
def verify_google(browser):
global driver
driver = launchBrowser(browser)
driver.get("http://www.google.com")
assert ("Google" in driver.title), "Unable to load google page"
elem = driver.find_element_by_name("q")
elem.send_keys("Sauce Labs")
elem.submit()
Page 155
Copyright Sauce Labs 2015
This is the command you would issue to pytest to execute the test:
browsers = [{
"platform": "Windows 10",
"browserName": "internet explorer",
"version": "11"
}, {
"platform": "OS X 10.11",
"browserName": "safari",
"version": "8.1"
}]
username = 'YOUR_SAUCE_USERNAME'
access_key = 'YOUR_SAUCE_ACCESSKEY'
@on_platforms(browsers)
class FirstSampleTest(unittest.TestCase):
Page 156
Copyright Sauce Labs 2015
Page 157
Copyright Sauce Labs 2015
Page 158
Copyright Sauce Labs 2015
Page 159
Copyright Sauce Labs 2015
Example sauce_driver.rb File for Running Ruby Tests in Parallel Expand source
on Sauce
require "selenium/webdriver"
module SauceDriver
class << self
def sauce_endpoint
"http://YOUR_SAUCE_USERNAME:YOUR_SAUCE_ACCESSKEY@ondemand.saucelabs.com:80/wd/hub
"
end
def caps
caps = {
:platform => "Mac OS X 10.9",
:browserName => "Chrome",
:version => "31"
}
end
def new_driver
Selenium::WebDriver.for :remote, :url => sauce_endpoint,
:desired_capabilities => caps
end
end
end
Now you need to make RSpec create a new driver for each spec. The cleanest way to do this is by defining an around hook, which will
be run, naturally, around every spec.
4. Create a file in the spec directory called spec_helper.rb.
This file will be require `d by every spec you create, as this is where, by convention, any setup code is placed.
Page 160
Copyright Sauce Labs 2015
Example spec_helper.rb File for Running Ruby Tests in Parallel Expand source
with Spec
require "rspec"
require_relative "sauce_driver"
RSpec.configure do |config|
config.around(:example, :run_on_sauce => true) do |example|
@driver = SauceDriver.new_driver
begin
example.run
ensure
@driver.quit
end
end
end
On line 5 you set up a new block of code to be run around every example tagged with :run_on_sauce => true. This lets you have
non-Selenium tests that don't spin up Selenium sessions. You have to make sure you include :run_on_sauce on all your Selenium
tests, though!
On line 6 you use the SauceDriver class you set up earlier to create a new Selenium driver, 'pointed' at Sauce Labs. Then, on line 8,
you run the example. On lines 9 - 11 we call quit on the Selenium session; This is done in an ensure block so that each test always
closes off its driver, even if something goes wrong.
Now you have RSpec set up to create drivers and close them down. Your next question might be, "How do I use these drivers?" Super simple.
Because driver is an instance variable, and the around block runs in the context of the spec, it can use the driver directly. Consider this
example spec.
puts @driver.title
end
end
On line 1 you require spec_helper. Then, on line 4 you add :run_on_sauce => true to make sure the around block runs. You can use the
created driver, @driver, without any further setup, and you don't have to do anything to close it off either. This means you're much less likely to
forget to do so when you write more tests.
Now, parallel testing! If you go ahead and create some more specs like this one (you can copy google_spec.rb into other files in the spec dire
ctory, just make sure the filenames end in spec.rb), then run the specs from your project root directory with:
Page 161
Copyright Sauce Labs 2015
You should be able to log into Sauce Labs and see your tests running in parallel. If your account has more than two concurrency slots (meaning,
you have a paid account), you can increase the number after -n to match your concurrency, and parallel_tests will spin up more tests at
once.
Page 162
Copyright Sauce Labs 2015
Add Logging
Why log instead of using trace tools?
How should I do my logging?
What should I actually log?
Check How Much Parallelisation Your Tests Can Stand
Run Fewer Tests
Read Your Logs
Incorrect driver setup
Non-thread-safe code
Selenium Lifecycle Problems
Problem Still Unsolved
Add Logging
Many languages have tools for tracing through code as it runs, monitoring what lines and classes are currently executing. These can be extremely
useful for debugging code problems, provided you're already familiar with them. Because many people aren't familiar with these tools, we
recommend you start by adding logging to your tests. Lots of logging. All the Logging. Logging also makes it easier to reason about multiple
threads over a period of time.
You can use your language or test framework's logging tools, your container's logging tools, or even printing to standard out. Printing to standard
out is a brute force approach, but can often be the best one to use when trying to debug problems on a continuous integration system, where
logging framework output may be hard to access.
1. Timestamps.
2. ID of the current thread or process (where applicable).
3. ID of the Selenium driver currently in use (where applicable).
If you're logging using a tool that allows for log levels, log to the DEBUG or VERBOSE levels of logging.
The purpose of logging is to inform you of concurrency problems that are occurring. So, you should log everything relevant to the problem you're
seeing. At a minimum, you should add logging to show:
Page 163
Copyright Sauce Labs 2015
When a test is about to do something that is network intensive for the browser
When test exceptions occur
When driver setup exceptions occur
When any pre-test actions that set up data or browser state, are about to run
When any pre-test actions that set up data or browser state have run
When any post-test actions that clean up data or browser state have run
When any post-test actions that clean up data or browser state have run
You should always include test names when talking about specific tests, Session IDs when using Selenium drivers, and Thread or Process IDs.
You should also try, whenever possible, to improve the error messages your test suite throws when problems occur.
You should also check to see if there's a level of parallelization at which your tests work, and one where. Some Sauce Labs users have problems
only once they've exceeded a certain number of parallel tests at once. For instance, problems with queuing and network congestion are often
exposed when running higher numbers of parallel tests.
First up, check how many parallel tests your account is able to run simultaneously. You can check this by logging in to Sauce Labs. In the
left-hand column you'll see the number of Concurrent VMs allowed for your account, which corresponds to the number of tests you can run in
parallel. Make sure you're not exceeding this number, and if you are, simply throttle back on the number of parallel tests you're running until the
problem resolves.
If your problem continues try slowly lowering the number of tests and see if there's a level, higher than one, at which you're no longer
experiencing problems. If you find the level at which this occurs, then you can start investigating your logging to see what your tests do at higher
levels, that differs from lower ones. For instance, you might discover that some of your tests rely on running in browsers with other tests, and
when your parallelisation goes higher, this no longer happens.
If there's no level of parallelisation where your tests work correctly in parallel, or there is but it's not related to your Sauce Labs concurrency limit a
nd you're certain it's not a networking problem, leave your parallelisation at 2 and carry on diagnosis.
Take tests out of your test suite! Similar to the steps above, removing tests from your test suite can surface problematic tests. It also shows if
you have a problem with the length of individual thread lifecycles.
If there's a point where you remove some tests and things start functioning, try adding some of the tests you removed earlier back in, and see if
they're not working correctly also. If they are, you've identified a problematic test you can check out further.
If you don't experience more stable tests by removing a couple of unstable ones, or if every test above a certain number causes issues, configure
your tests to run the lowest number of tests that exhibits a problem, and keep debugging.
Non-thread-safe code
Selenium sessions being created all at once, but only used by tests much later
Selenium sessions all quit at once
Selenium session IDs being used across multiple threads
Page 164
Copyright Sauce Labs 2015
Unfortunately, if all of your tests get unique Selenium sessions created, those sessions are started and stopped correctly, are only ever used by a
single thread, and don't get queued, then its likely your problems arise from something else in your test suite. Unfortunately, these are out of
scope of Sauce Labs' support. It can be helpful to investigate your database and application server's ability to deal with concurrent tests, shared
sessions, and test data. Good Luck!
Page 165
Copyright Sauce Labs 2015
Viewing Screenshots, Commands, Logs, and Metadata for Sauce Test Results
Using Status Badges and the Browser Matrix Widget to Monitor Test Results
Sharing the Results of Sauce Labs Tests
Embedding Test Results in HTML Pages
Building Links to Test Results
Managing Archived Test and Build Results
Searching for Test Results and Builds on Your Archive Page
Search Fields and Operators
Using Favorites to Save Your Searches
Deleting Test and Build Results
Changing the Layout of Your Archives Page
Page 166
Copyright Sauce Labs 2015
Viewing Screenshots, Commands, Logs, and Metadata for Sauce Test Results
1. Log in to Sauce Labs.
2. Click Dashboard.
3. Select Automated Tests or Manual Tests, depending on the type of test result you want to view.
4. Click the name of the test with the results you want to view.
5. Click Watch to view screenshots and video of the test.
6. Click Commands to see the API commands that were issued during the test.
The Commands tab also includes controls for filtering the commands displayed and playing back the commands.
7. Click Logs to see the logs generated by your test.
The kinds of logs you can see are determined by the type of test you ran. For example, Web application tests will include a Selenium log,
while mobile application tests will contain an Appium log.
8. Click Metadata to see the metadata attached to your test.
Some of the test metadata, such as Passed, can be updated via the the Sauce REST API. You can also download video and
screenshots of your test in this tab.
For iOS tests, you'll notice that the iOS simulator log is embedded within the Appium log. The information from the iOS simulator is
grayed out throughout the Appium log and has the tag name: info: [IOS_SYSLOG_ROW ].
For Android tests you can find the Android emulator logs by clicking the Metadata tab in your test page and searching for the Logcat
.log file. This file contains all the information from the Android emulator log.
Page 167
Copyright Sauce Labs 2015
Using Status Badges and the Browser Matrix Widget to Monitor Test Results
Status badges and the Sauce Labs browser matrix widget help you keep track of the status of your latest test runs. All you have to do is add
either markdown or HTML code to your GitHub README or project site that references your Sauce Labs username and access key, and annotat
e your jobs with the REST or WebDriver API.
There are three status badges that correspond to the three states of a finished test: Passing, Failed, and Unknown.
Badge Status
Passing
Failed
With the browser matrix, you can keep track of the test status of your project for various browser/platform/operating system combinations.
[](https://saucelabs
.com/u/YOUR_SAUCE_USERNAME)
Alternatively, you can use this HTML code on your project site.
Page 168
Copyright Sauce Labs 2015
<a href="https://saucelabs.com/u/YOUR_SAUCE_USERNAME">
<img src="https://saucelabs.com/buildstatus/YOUR_SAUCE_USERNAME" alt="Sauce
Test Status"/>
</a>
[](https://saucela
bs.com/u/YOUR_SAUCE_USERNAME)
<a href="https://saucelabs.com/u/YOUR_SAUCE_USERNAME">
<img src="https://saucelabs.com/browser-matrix/YOUR_SAUCE_USERNAME.svg" alt="Sauce
Test Status"/>
</a>
If you want to display the build status of a private Sauce account, you need to provide a Hash-based Message Authentication Code (HMAC) token
generated from your username and access key.
python
from hashlib import md5
import hmac
"?auth=" + hmac.new("YOUR_SAUCE_USERNAME:YOUR_SAUCE_ACCESSKEY", None, md5).hexdigest()
https://saucelabs.com/u/YOUR_SAUCE_USERNAME?auth=HMAC_TOKEN
Page 169
Copyright Sauce Labs 2015
Sharing Description
Option
Public Setting the sharing option for your Test Details page to Public means that it is accessible to everyone who has the link to
the page, and may be listed on public web pages and indexed by search engines.
Public If you want to share your Test Details page and allow access to the test video and screenshots, but restrict log access to
Restricted yourself, select Public Restricted. By restricting access to the raw Selenium log and the job log, you can prevent sensitive
information such as passwords from being visible to others.
Team The Test Details page is visible to your account and its sub accounts.
2. Copy and send the URL of the Test Details page to anyone you want to share it with.
You can also set the sharing options for a test through the REST API.
Page 170
Copyright Sauce Labs 2015
You can embed test pages in CI test results or other test reports. Using the format below, add the HTML to any page where you need to embed
test results, replacing YOUR_JOB_ID with the ID of the job you want:
<script src="https://saucelabs.com/job-embed/YOUR_JOB_ID.js">
</script>
In addition to full test results, you can embed videos as well. Using the format below, add the HTML to any page where you want to embed job
videos, replacing YOUR_JOB_ID with the ID of the job you want:
<script src="https://saucelabs.com/video-embed/YOUR_JOB_ID.js">
</script>
Authentication Required
Both of these configurations will only work for browsers logged in using your account, but you can use authentication tokens to make
this work for anonymous viewers. Check out the section on creating authentication tokens in the topic Building Links to Test Results for
more information.
<script src="https://saucelabs.com/video-embed/YOUR_JOB_ID.js?auth=AUTH_TOKEN">
</script>
Page 171
Copyright Sauce Labs 2015
In Selenium, when a client requests a new browser session, the server returns a session ID, which is used to identify that session throughout the
test. The session ID is stored as a member variable of the instantiated Selenium object and named sessionId or session_id, depending on
the client library. Sauce uses that session ID as the job id for accessing test results.
To directly access a specific job, you will first need to note the session ID locally, usually by writing it to a log file. You can then use it to create a
URL with the following format and replace YOUR_JOB_ID with the session ID.
http://saucelabs.com/jobs/YOUR_JOB_ID
Notice that links to jobs in this format will only work if you are logged in with the account that ran the job or if that account is a sub-account of
yours. For generating public links, see the next section.
The links you create to your jobs in can be constructed in a way that doesn't require anonymous viewers to login and use your credentials. This is
based on authentication tokens.
Auth tokens are generated on a per-job basis and give the receiver access using an hmac-based algorithm. You can also find hmac
implementations for different programming languages.
The digest algorithm to use is MD5. The message and key used to generate the token should be the following:
Key: sauceUsername:sauceAccessKey
Message: job-id
Here's an example in Python for generating the token for a job with id: 5f9fef27854ca50a3c132ce331cb6034
Once the auth token has been obtained, you can use it to build a link in this format: https://saucelabs.com/jobs/YOUR_JOB_ID?auth=AUTH_TOK
EN
You can extend the links generated with authentication tokens to make them work for either one day or one hour duration, based on parameters
that you set. During the hmac generation, set the key like this:
Key: YOUR_USERNAME:YOUR_ACCESS_KEY:YOUR_DATE_RANGE
The date range can take two formats: YYYY-MM-DD-HH and YYYY-MM-DD. These should be set in UTC time and will only work during the date or
hour you set.
Page 172
Copyright Sauce Labs 2015
You can filter your archived test results based on criteria such as build, owner, browser, platform, status, date, and user-defined tags, create
structured searches using multiple filters, and search using freeform text. You can also save your search queries as favorites, so you'll always be
be able to find the results that are most important to you!
Page 173
Copyright Sauce Labs 2015
The Archives page includes a number of filters you can use to search through your tests and builds. You can search using a single filter, or you
can use multiple filters to build a structured search.
Basic Filtering
1. Click Archives.
2. Click the filter you want to use to open it.
3. In the filter text field, enter the terms you want to search for.
As you type, autocomplete will suggest existing results that match your search terms. If you want to select a date or date range, use the
Calendar icon in the Date filter.
4. When you find the items you want to use in your filter, select them.
5. When you've finished selecting your filter criteria, click Apply.
With this option, you would select filters and filter criteria as you would for basic filtering, but each time you make a selection, you will see it added
to the Search field to build the query. Using this option, there is an implied AND between the different filters you select, and an implied OR
between the values within a specific filter.
If you want to create a more complex search using AND, OR, or special operators associated with a specific filter, you can write your own
structured search in the Search field. As you enter search criteria, the autocomplete will suggest values, operators, and filters to match your text.
If your search query syntax is incorrect, your query text will turn orange, and you will see suggestions for how to correct it below the search field.
When your syntax is correct, the text will turn blue.
Find all of the tests that were tagged as Selenium_194 or Selenium_ tag:(Selenium_194 Selenium_193) and status:failed
193 that have failed since 03/10/2015 and date:[2015-10-03 TO *]
Find only the IE tests that have failed with the word Main in the title. name:"Main*" AND browser:"Internet Explorer *"
Page 174
Copyright Sauce Labs 2015
You can use any of these filters singly or or combination to search through the tests and builds on your Archive page. The Example column
shows how you could construct a search using a specific filter in the Search text field. See Searching for Test Results and Builds on Your Archive
Page for examples of how to build structured searches using multiple filters in the Search field.
Text Search for any mention of the string across test details. text: Appium
Platform Search for tests that ran on one or multiple operating systems. This field only accepts platform:("OS X 10.10" "Windows
operating systems currently supported by Sauce Labs. 8.1")
Browser Search for tests that ran on one or multiple browsers. Only accepts browsers currently browser:("Google Chrome 43"
supported by Sauce Labs. "Internet Explorer 11")
Date Search for tests that ran on a specific date or over a specified range. Dates should be date:[2014-05-05 TO 2015-05-05]
in YYYY-MM-DD format.
date: [2014-05-05 TO *]
Status Search for tests based on their status. Currently there are four possible states: failed, status: failed
passed, complete, error.
Build Search for tests that belong to a specific build. build:main and
browser:"Internet Explorer 11"
Tag Search for tests that have one or multiple tags. tag: Jenkins
Owner Search for tests that were created by a specific user. owner: admin
Page 175
Copyright Sauce Labs 2015
1. After you've built your search from the filters or written it in the Search text field on the Archives page, click the Star icon next to the text
field to save it.
2. Click the expand icon next to the Star to view your favorited searches.
You can select a favorite search to run it, or remove it by clicking the Delete icon.
Page 176
Copyright Sauce Labs 2015
Page 177
Copyright Sauce Labs 2015
Your layout changes will be saved until you change them again.
Page 178
Copyright Sauce Labs 2015
You upload apps using the upload_file API endpoint. You can use any REST client, one of the Sauce REST API libraries, or cURL. Check
out Temporary Storage Methods for more information.
Parameter Description
upload_filename The name you want to store the file under on Sauce Storage, for example SuperApp.zip
path/to/your_file_name The path to where the file is saved on your local machine, for example users/Tester/builds/super_app
_tst_1228_build.zip
If you're using curl for the upload, you must include the @ before path/to/your_file_name
Sauce Storage URLs are in the form sauce-storage:<upload_filename>. After you're uploaded the file, you can replace the value of the ap
p desired capability with the Sauce Storage URL.
Page 179
Copyright Sauce Labs 2015
https://saucelabs.com/rest/v1/storage/someuser/SuperApp.zip?overwrite=true
--data-binary @/users/Tester/builds/super_app_tst_1228_build.zip
If you're running tests against your app as part of your development process and continuous integration, you should upload your app at the start
of every test run to ensure any changes to the app are accounted for. This is usually best accomplished automatically as part of your test suite,
using a REST client.
Page 180
Copyright Sauce Labs 2015
using RestSharp;
using RestSharp.Authenticators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
// Uploads a file to Sauce Temporary Storage via REST API using the
// RestSharp library. Be sure to replace the string values for
// FileName, FilePath, UserName, and AccessKey.
Page 181
Copyright Sauce Labs 2015
In addition to providing a means for Sauce Labs to access your application or website, Sauce Connect has some other uses in your testing
network architecture:
As an alternativee to whitelisting
As a means of monitoring upstream traffic through a proxy like BrowserMob
As a way to stabilize network connections (for instance, detecting/re-sending dropped packets)
Topics in this section cover the setup and use of Sauce Connect, as well as topics on how Sauce Connect works within a network architecture.
Page 182
Copyright Sauce Labs 2015
For saucelabs.com certificate authentication, the server hosting Sauce Connect may need to connect to Online Certificate Status
Protocol (OCSP) or Certificate Revocation List (CRL) services as well. Check out Sauce Connect Certificate Handling for more info.
Topics in this section describe how Sauce Connect functions in a network, and provide some examples of different network configurations using
Sauce Connect as an alternative to whitelisting, connecting to proxied sites, or monitoring traffic through a proxy like BrowserMob.
Page 183
Copyright Sauce Labs 2015
During startup, Sauce Connect issues a series of HTTPS requests to the Sauce Labs REST API. These are outbound connections to saucelabs
.com on port 443. Using the REST API, Sauce Connect checks for updates and other running Sauce Connect sessions, and ultimately launches
a remote tunnel endpoint virtual machine (VM). Once the VM is started, a tunnel connection is established to a makiXXXXX.miso.saucelabs.
com address on port 443, and all traffic between Sauce Labs and Sauce Connect is then multiplexed over this single encrypted TLS connection.
Page 184
Copyright Sauce Labs 2015
1. Sauce Connect makes HTTPS REST API calls to saucelabs.com:443 using the username and access key provided when starting
Sauce Connect.
2. Sauce Labs creates a dedicated virtual machine that will serve as the endpoint of the tunnel connection created by Sauce Connect.
3. Sauce Labs responds with the unique ID of the virtual machine created in step 2.
4. Sauce Connect establishes a TLS connection directly to the dedicated virtual machine created in step 2. (makiXXXXX.miso.saucelab
s.com).
5. All test traffic is multiplexed over the tunnel connection established in step 4.
Once Sauce Connect is terminated (typically via ctrl-c), a call will be made from Sauce Connect to the REST API with instructions to terminate
the tunnel VM. Sauce Connect will continue to poll the REST API until the tunnel VM has been halted and deleted.
Page 185
Copyright Sauce Labs 2015
Data transmitted by Sauce Connect is encrypted through the TLS protocol, using the AES-256 cipher. Sauce Connect also uses a caching web
proxy to minimize data transfer. You can disable this with the command line option -B, --no-ssl-bump-domains, which is described further
in the Sauce Connect Command Line Reference.
Page 186
Copyright Sauce Labs 2015
Connections to the Sauce Labs API go through https://saucelabs.com. The way in which Sauce Connect is able to access the certificates
to secure the connection depends on the operating system of the machine where Sauce Connect is installed.
Linux
On Linux machines, Sauce Connect will look for the directory where the certificate bundle is installed, typically something like /etc/ssl/certs.
If it can't find the directory, it will generate an error when trying to connect to the Sauce Labs API.
Windows
On Windows machines, certificates are managed through the Security Support Provider Interface API over SChannel, which requires access to
the OCSP and CRL URLs to verify certificates. If you have set up highly restrictive firewalls or proxies on the machine where Sauce Connect is
running and it can't connect to these URLs, you'll get an error when attempting to connect to the Sauce Labs API.
OS X
On OS X machines, certificates are pre-installed as part of the Trust Store and are accessible through the Keychain. If Sauce Connect is installed
on an OS X machine, no troubleshooting should be necessary as long as it can access the Keychain.
Connections from Sauce Connect to the virtual machine that run your tests on browsers in the Sauce Labs cloud are managed through the SSL/T
LS protocol, and a Sauce Labs self-signed certificate that is included in the application.
Page 187
Copyright Sauce Labs 2015
Page 188
Copyright Sauce Labs 2015
Whitelist Domains
A common use case for this is if you need your requests to your internal environment to route through Sauce Connect, with external resources
being pulled as usual.
-t internal-site.com
Blacklist Domains
In this case, the use case is that you need most things to go through the tunnel, but certain external assets must be retrieved directly, for example
from a Content Delivery Network (CDN).
-D cdn.external-site.com
You may not access to some external assets at all, for the sake of speed or just not interfering with user metrics, such as analytics.
-F analytics-provider.com
Page 189
Copyright Sauce Labs 2015
Shorthand Longhand
SC Host Machine in your network that the Sauce Connect application is running on.
Sauce SC The virtual machine that hosts Sauce Connect on the Sauce Labs side. The configuration is more complicated than just one
Host machine, but for representational purposes it's treated as a single machine.
Page 190
Copyright Sauce Labs 2015
This is a good example of a dysfunctional setup with Sauce Connect. The problem is that the SC host is in the same VPN, and thus the same
internal network, as the Site Under Test (SUT), but in geographically separate locations. This means that requests from Sauce Connect to the
SUT need to reach back through the internet to be completed, rather than over the same internal network. An example this network configuration
would be an SC Host in Berlin, with the SUT located in a data center in Chicago. This would require a number of network hops, which delays
communication with the test virtual machine at Sauce Labs. The way to prevent this is to always place the SC Host in the same geographic
domain as the SUT.
Here, the SUT is in a network DMZ or Demilitarised Zone. It's exposed to the internet but isolated from the internal network.
Shorthand Longhand
SC Host Machine in your network that the Sauce Connect application is running on.
Sauce SC The virtual machine that hosts Sauce Connect on the Sauce Labs side. The configuration is more complicated than just one
Host machine, but for representational purposes it's treated as a single machine.
Page 191
Copyright Sauce Labs 2015
Sauce Connect with a Proxy for Network Monitoring and Filtering Configuration
Internet Control/Transaction Monitoring with a Proxy Configuration
Proxied Site Under Test (SUT)
You can find information on how to configure Sauce Connect to work with proxies, either through autodetection of the proxies already set up on
the SC Host, or through command line configuration, in the topic Sauce Connect Proxy Configuration. This topic will show you some of the basic
ways to set up Sauce Connect within a proxied or firewalled network architecture.
You may have a network configuration in which you use a proxy to control the flow of traffic from your internal network to the external Internet,
either as a means of adding security to your network, or whitelisting or blacklisting certain sites. In this situation you could set up Sauce Connect
behind a proxy like BrowserMob, which records all traffic that passes through it, and which can later provide a history of that traffic.
In this configuration the SUT is behind a proxy, to allow even more control over traffic before it reaches the SUT. Typical this setup is used to
control access to the SUT by means of IP whitelisting, or requiring a username and password to access the proxy.
Shorthand Longhand
SC Host Machine in your network that the Sauce Connect application is running on.
Sauce SC The virtual machine that hosts Sauce Connect on the Sauce Labs side. The configuration is more complicated than just one
Host machine, but for representational purposes it's treated as a single machine.
Page 192
Copyright Sauce Labs 2015
Page 193
Copyright Sauce Labs 2015
System Requirements
System requirements vary depending on the number of parallel tests you plan to run. Here are some samples based on simultaneous test
volume:
For increased reliability and security, use a dedicated server. You will also want an uplink capable of at least 5MB/s when running 50+ tests in
parallel.
On Unix-based systems, you may need to increase your open file limit if your parallel test count is high (for example, ulimit -n 8192
).
Page 194
Copyright Sauce Labs 2015
Prerequisites
Make sure you've reviewed the System Requirements for Sauce Connect
You should look over the examples of Sauce Connect Network Configurations to understand the best way to set up Sauce Connect in
your network architecture
You should read Sauce Connect Setup and Teardown Process to understand how Sauce Connect uses tunnels to connect your site or
application under test to a browser running on a virtual machine in the Sauce Labs data center, and Sauce Connect and Security to
understand how that tunnel is secured
Take a few minutes and read over the Sauce Connect Best Practices
Procedure
1. Download the appropriate version of Sauce Connect for your operating system.
2. On the machine where you want to install Sauce Connect, open outbound port 443.
Alternatively, you can configure Sauce Connect with a proxy that can reach saucelabs.com by using the Sauce Connect command line
options --proxy or --pac. See the topic Sauce Connect Proxy Configuration for more information.
3. After extracting the Sauce Connect files onto your machine, go to the install directory and run this command.
Page 195
Copyright Sauce Labs 2015
Setting Up Systemd
Setting Up Upstart
Setting Up Systemd
1. Navigate to your /local/bin directory where you want to install Sauce Connect.
cd /usr/local/bin
wget https://saucelabs.com/downloads/sc-4.3.11-linux.tar.gz
cp sc-4.3.11-linux/bin/sc
ls /usr/local/bin/sc
cd /etc/systemd/system
7. In the system directory, reate a service file sc.server with these contents.
Change the username and access key in the file to match your own.
Page 196
Copyright Sauce Labs 2015
[Service]
Type=simple
User=nobody
Group=nogroup
ExecStart=/usr/local/bin/sc -u <CHANGEME> -k <CHANGEME> -l /tmp/sc_long.log
--pidfile /tmp/sc_long.pid --se-port 0
[Install]
WantedBy=multi-user.target
Setting Up Upstart
1. Navigate to your /local/bin directory where you want to install Sauce Connect.
cd /usr/local/bin
wget https://saucelabs.com/downloads/sc-4.3.11-linux.tar.gz
Page 197
3.
Copyright Sauce Labs 2015
cp sc-4.3.11-linux/bin/sc
ls /usr/local/bin/sc
cd /etc/init
respawn
respawn limit 15 5
env LOGFILE="/tmp/sc_long.log"
env PIDFILE="/tmp/sc_long.pid"
Page 198
Copyright Sauce Labs 2015
post-start script
# Save the pidfile, since Sauce Connect might remove it before the
# post-stop script gets a chance to run.
n=0
max_tries=30
while [ $n -le $max_tries ]; do
if [ -f $PIDFILE ]; then
cp $PIDFILE ${PIDFILE}.saved
break
fi
n=$((n+1))
[ $n -ge $max_tries ] && exit 1
sleep 1
done
end script
post-stop script
# Wait for Sauce Connect to shut down its tunnel.
n=0
max_tries=30
pid="$(cat ${PIDFILE}.saved)"
while [ $n -le $max_tries ]; do
kill -0 $pid || break
n=$((n+1))
[ $n -ge $max_tries ] && exit 1
sleep 1
done
end script
setuid nobody
setgid nogroup
Page 199
Copyright Sauce Labs 2015
chdir /tmp
sudo start sc
sudo status sc
sudo stop sc
Page 200
Copyright Sauce Labs 2015
If you want to use multiple Sauce Connect tunnels, you need to create tunnel identifiers to manage them. This is because Sauce Connect only
supports running one tunnel with the same identifier at at a time. This table shows how tunnels running on different machines with different tunnel
identifiers will interact with each other when they start up.
To create a tunnel identifier, start Sauce Connect using the --tunnel-identifier flag (or -i) and provide your own unique identifier string.
Once the tunnel is up and running, any tests that you want going through this tunnel will need to provide the correct identifier using the tunnelId
entifier desired capability. This is how you make sure that a job uses the correct tunnel, as jobs will also automatically make use of
unidentified tunnels. This table shows what to expect when you are running jobs with both identified and unidentified tunnels.
When you No tunnels An unidentified tunnel Tunnel Alpha run An unidentified tunnel AND tunnel Alph
have running running ning a running
When
tunnel-identifier is
Not provided No tunnel is used The unidentified tunnel is No tunnel is used The unidentified tunnel is used
used
Alpha Your tests don't Your tests don't work Tunnel Alpha is Tunnel Alpha is used
work used
Beta Your tests don't Your tests don't work Your tests don't Your tests don't work
work work
If you want to run different tunnels on the same machine, you need to use additional flags to start them, because multiple tunnels on the same
machine require different ports, logfiles and PID files. The required flags are --pidfile, --logfile, --sc-proxy-port, --se-port, and -i
, as shown in this example:
Flag Description
--pidfile A file used to record the process identifier. It can be erased or reused once the tunnel is shut down.
Page 201
Copyright Sauce Labs 2015
--logfile The location where Sauce Connect writes its logs. This can be reused or erased once the tunnel is shut down, but since
Sauce Labs Support will sometimes request this file if you're having test issues, deleting it automatically isn't a great
idea.
--sc-proxy-port An internal Sauce Connect port. This simply needs to be a free port.
--se-port The port for Sauce Connect's inbuilt Selenium Relay. This can be any free port if your test code sends Selenium
Commands directly to Sauce Labs. Otherwise, you'll need to match this port to the port used by the test code that will
be using this tunnel.
Page 202
Copyright Sauce Labs 2015
As of Sauce Connect 4.3.1, proxies and PAC settings are autoconfigured based on the settings of the operating system on the machine where it
is installed.
On Windows, Sauce Connect will use the proxy settings for Internet Explorer, as well as the system-wide proxy settings that set in the C
ontrol Panel.
On Mac OS X, Sauce Connect will use the proxy settings in Preferences/Network. Both proxy and PAC settings are supported.
On Linux, Sauce Connect looks for these variables, in this order:
http_proxy
HTTP_PROXY
all_proxy
ALL_PROXY.
They can be in the form http://host.name:port or host.name:port.
You can disable automatic proxy detection with the command line option ./sc -z --no-autodetect.
If automatic proxy configuration fails, you need to override the settings, or you need to enable proxies through a test script, there are several com
mand-line options that you can use to configure proxies manually.
-p
--proxy <host:port>
-w
--proxy-userpwd <user:pwd>
-T
--proxy-tunnel
--pac <url>
The second connection is to the actual tunnel virtual machine (VM) created for your Sauce Connect instance. Enabling the -T,
--proxy-tunnel flag will cause some proxy specified with -p, --proxy to be used for this connection as well. You should try to
avoid using a proxy for this connection, since it is already TLS secured, and a large volume of data tends to go over this connection.
Adding another step in the middle, in the form of a proxy, can hinder test performance.
Ideally you should only need to use -p, --proxy <host:port> (and perhaps -w, --proxy-userpwd <user:pwd> for
credentials), but -T, --proxy-tunnel is available if your network doesn't allow outgoing connections on port 443. If your tests are
slow, you may want to ask your network administrator about making an exception for this connection.
You can use BrowserMob Proxy with Sauce Connect 4.2 and higher by using the Sauce Connect PAC feature.
Since BrowserMob bumps SSL connections, and Sauce Connect 4 verifies the certificate when connecting to the REST API, that means the --pr
oxy option can't be used with a BrowserMob proxy. Sauce Connect will complain that the certificate received from the REST endpoint is invalid.
To choose a proxy in a dynamic fashion, however, you can create a PAC file that matches the REST and tunnel VM hostnames, and uses the
local BrowserMob proxy for everything else.
Page 203
1.
4. Copy the file to the same directory as Sauce Connect 4, and start Sauce Connect 4.
Sauce Connect 4 will print the proxy used for REST and the tunnel VM connection, which should be Using no proxy for
connecting to Sauce Labs REST API and Using no proxy for connecting to tunnel VM if their hostnames are
configured with DIRECT access.
Page 204
Copyright Sauce Labs 2015
-u, --user <username> You can also use the environment variable SAUCE_USERNAME
-k, --api-key <api-key> You can also use the environment variable SAUCE_ACCESS_KEY
-B, --no-ssl-bump-domains Comma-separated list of domains. Requests including hosts that matches one of these domains
<...> will not be SSL re-encrypted. See the section on SSL Bumping Enabled by Default in the Troubl
eshooting Sauce Connect topic for more information about situations in which you would want to
use this command.
-D, --direct-domains <.. Comma-separated list of domains. Requests including hosts that matches one of these domains
.> will be relayed directly through the Internet, instead of through the Sauce Connect tunnel.
-t, --tunnel-domains <.. Inverse of --direct-domains. Only requests for domains in this list will be sent through the
.> Sauce Connect tunnel.
-v, --verbose Enable verbose debugging. -vv will output HTTP headers as well.
-F, --fast-fail-regexps Comma-separated list of regular expressions. Requests with URLs matching one of these will get
<...> dropped instantly and will not go through the tunnel. See the question How Do I Use Sauce
Connect to Test Graceful Degradation in the Sauce Connect FAQs for an example of how you
would use this command to test for application or site degradation based on missing assets or
resources.
-i, --tunnel-identifier Assign <id> to this Sauce Connect instance. Future jobs will use this tunnel only when explicitly s
<id> pecified by the tunnel-identifier DesiredCapability in a Selenium client. Check out the topic
Using Multiple Sauce Connect Tunnels for information on using tunnel-identifier to run
multiple Sauce Connect tunnels simulteanously. Test Configuration Options contains more
information about the syntax for setting tunnel-identifier as a DesiredCapability.
-P --se-port <port> Port on which Sauce Connect's Selenium relay will listen for requests. Selenium commands reach
ing Sauce Connect on this port will be relayed to Sauce Labs securely and reliably through Sauce
Connect's tunnel. Defaults to 4443.
-p, --proxy <host:port> Proxy host and port that Sauce Connect should use to connect to the Sauce Labs cloud. See Sau
ce Connect Proxy Configuration and Sauce Connect with a Proxy for Network Monitoring and
Filtering Configuration for more information about using Sauce Connect with proxies.
-w, --proxy-userpwd <use Username and password required to access the proxy configured with -p. See Sauce Connect
r:pwd> Proxy Configuration and Sauce Connect with a Proxy for Network Monitoring and Filtering
Configuration for more information about using Sauce Connect with proxies.
--pac <url> Proxy autoconfiguration. Can be a http(s) or local file:// URL. See Sauce Connect Proxy
Configuration and Sauce Connect with a Proxy for Network Monitoring and Filtering Configuration
for more information about using Sauce Connect with proxies.
-T, --proxy-tunnel Use the proxy configured with -p for the tunnel connection. See Sauce Connect Proxy
Configuration and Sauce Connect with a Proxy for Network Monitoring and Filtering Configuration
for more information about using Sauce Connect with proxies.
-s, --shared-tunnel Allows sub-accounts of the tunnel owner to use the tunnel. See the question Can I Reuse a
Tunnel Between Multiple Accounts? in the Sauce Connect FAQs for more information on using
this command.
-x, --rest-url <arg> Advanced feature: Connect to SauceREST API at alternative URL. Use only if directed to do so b
y Sauce Labs support.
-f, --readyfile File that will be touched to indicate when tunnel is ready.
Page 205
Copyright Sauce Labs 2015
-a, --auth <host:port:us Perform basic authentication when a URL on <host:port> asks for a username and password.
er:pwd> This option can be used multiple times.
-z, --log-stats <seconds Log statistics about HTTP traffic every <seconds>. Information includes bytes transmitted, reque
> sts made, and responses received.
--max-logsize <bytes Rotate logfile after reaching <bytes> size. Disabled by default.
>
Page 206
Copyright Sauce Labs 2015
1. Start Sauce Connect with the --shared-tunnel command from the main account in your account tree.
2. Once the tunnel is running, provide the special parentTunnel DesiredCapability on a per-job basis.
The value of this capability should be the username of the parent account that owns the shared Sauce Connect tunnel as a string.
capabilities['parentTunnel'] = "parentAccount"
Jobs that request this capability will route all their traffic through the tunnel created using your parent account
I Have Verbose Logging On, but I'm Not Seeing anything in stdout.
What Gives?
Output from the -v flag is sent to the Sauce Connect log file rather than stdout. See the section on Generating Logs for Troubleshooting in Tro
ubleshooting Sauce Connect for more information.
1. First write a loop that will restart Sauce Connect every time it gets killed or crashes:
2. Write a cron task that will kill Sauce Connect on a regular basis:
rontab -e 00 00 * * * killall sc
Page 207
Copyright Sauce Labs 2015
This will kill Sauce Connect every day at 12am, but can be modified to behave differently depending on your requirements.
When using Sauce Connect, local web apps running on commonly-used ports are available to test at localhost URLs, just as if the Sauce Labs
cloud were your local machine.
However, because an additional proxy is required for localhost URLs, tests may perform better when using a locally-defined domain name (which
can be set in your hosts file) rather than localhost. Using a locally-defined domain name also allows access to applications on any port.
The Safari browser on OS X 10.10 Yosemite and mobile iOS 8+ proxies these common ports:
80, 443, 888, 2000, 2001, 2020, 2109, 2222, 2310, 3000, 3001, 3030, 3210, 3333, 4000, 4001, 4040, 4321, 4502, 4503, 4567, 5000, 5001, 5050,
5555, 5432, 6000, 6001, 6060, 6666, 6543, 7000, 7070, 7774, 7777, 8000, 8001, 8003, 8031, 8080, 8081, 8765, 8777, 8888, 9000, 9001, 9080,
9090, 9876, 9877, 9999, 49221, 55001
If you're testing on Safari and need a different port, please let us know! We do our best to support ports that will be useful for many customers,
such as those used by popular frameworks.
If We Have Five Users, Can We Use Five instances of Sauce Connect, or Do We Have to Set Up One
Shared Instance?
Feel free to use either, even if you only have one Sauce account! If you do decide to use five separate instances, you will need to create unique
identifiers for each. You can also create sub-accounts that each have their own individual access keys.
Page 208
Copyright Sauce Labs 2015
You can enable verbose logging with the -v flag. Verbose output will be sent to the Sauce Connect log file rather than standard out.
Check out the topics under Sauce Connect in the Network for examples of how to set up Sauce Connect within various network environments,
including examples of dysfunctional network configurations.
Page 209
Copyright Sauce Labs 2015
If you need additional help, get in touch at help@saucelabs.com. To provide our support team with additional information, please add the -vv and
-l sc.log options to your Sauce Connect command line, reproduce the problem, and attach the resulting log file (called sc.log) to your
support request.
Page 210
Copyright Sauce Labs 2015
Be Aware of How Sauce Connect Will Interact with Your Network Architecture
When you set up Sauce Connect, you don't have to set it up on the same machine as the application or website you're testing, but it must be on
the same network as that machine. For this reason, it's very important to understand how Sauce Connect will interact with components of your
network architecture such as proxies, firewalls, and geographically distributed data centers. You should read the topics under Sauce Connect in
the Network and Sauce Connect Network Configurations for more information.
Linux 32-bit Sauce Connect v4.3.11 for Linux 32-bit SHA1 checksum: f27be22c5e7b8ba905c5886cf93a4e63e6c370b3
Use a Single Sauce Connect Tunnel for Each Test Suite or Build
If you're using Sauce Connect to build a tunnel between your application and the Sauce Labs testing infrastructure, you should use a single
Sauce Connect instance for each test suite or build. Your test automation framework should launch Sauce Connect before the test suite is
triggered, and should shut it down when the suite. If you're using a continuous integration platform like Jenkins, you can use the Sauce
OnDemand plugin to launch and tear down your Sauce Connect instance.
If you use persistent tunnels for your tests and builds, you can run into issues with tunnels being unexpectedly down (an example of avoiding an
external dependency for your tests), and you can avoid the need to build logic into your tests to see if a a specific persistent tunnel is up and
passing traffic.
Page 211
Copyright Sauce Labs 2015
Page 212
Copyright Sauce Labs 2015
1. They provides a user interface that lets you populate environment variables your CI/CD server that can be used in your tests (for
example, platform configurations, or your Sauce username and access key). Much of what the plugins accomplish relates to the setting of
environment variables.
2. They automatically launch Sauce Connect when you enable it for a project.
3. They handle reporting between your CI/CD platform and Sauce.
Page 213
Copyright Sauce Labs 2015
Setting Up the Sauce Labs Manage Credentials Task for Your Build
The Manage Credentials task is what allows you to authenticate with your Sauce Labs account via VSO and
start Sauce Connect. You need to configure the task to create a new service endpoint that will contain your
Sauce Labs username and access key.
1. In your VSO dashboard, click Build.
2. Under Build Definition, choose an appropriate template for your project.
3. Configure your Source Settings for the project.
4. Click Create.
5. Click Add Build Step.
6. Under Test, search for and add Sauce Labs - Manage Credentials.
7. Under Add build step, select Sauce Labs - Manage Credentials.
8. Next to the Sauce Labs Credentials menu, click Manage.
This will open the Services tab.
9. Click New Service Endpoint.
10. Select New Sauce Labs Credentials.
11. For Connection Name, enter an appropriate name.
12. For User name and API Token, enter your Sauce username and access key.
13. Click OK.
14. Go back to the build steps for your project, and make sure that under Control Options for the Manage Credentials task, the Enabled o
ption is selected
Sauce Connect is a tunneling application that established a secure connection between applications or sites under test in your local network or
machine, and the virtual machines running browsers in the Sauce Labs testing cloud. It is not necessary to set up Sauce Connect to run tests with
the Sauce Labs browser cloud, you only need to use it if the application or site under test is not publicly accessible over a network. Check out the
topics under Using Sauce Connect for Testing Behind the Firewall or on Localhost for more information.
If you want to use Sauce Connect with VSO, you need to both Enable Sauce Connect in your Manage Credential task and add the Sauce
Labs - Stop Sauce Connect task to your build. These will start up a Sauce Connect tunnel when your build begins, and then close the tunnel
when it finishes.
Page 214
Copyright Sauce Labs 2015
Page 215
Copyright Sauce Labs 2015
You can install the Sauce plugin through the Bamboo Administration page.
Page 216
Copyright Sauce Labs 2015
Create a Plan
Configure Tasks
Configure the Plan
Enable the Sauce Plugin
Run the Example Tests
Create a Plan
Configure Tasks
1. Under Plan Configuration > Stages and Jobs > Default Stage, select Default Job.
2. Click Miscellaneous.
3. For Job Name, enter Default Job.
4. Select Job Enabled.
5. Click Save.
Page 217
Copyright Sauce Labs 2015
Page 218
Copyright Sauce Labs 2015
Create a Plan
Configure Tasks
Configure the Plan
Enable the Sauce Plugin
Run the Example Tests
Create a Plan
Configure Tasks
1. Under Plan Configuration > Stages and Jobs > Default Stage, select Default Job.
2. Click Miscellaneous.
3. For Job Name, enter Default Job.
4. Select Job Enabled.
5. Click Save.
5.
Page 219
Copyright Sauce Labs 2015
5. Click Save.
Page 220
Copyright Sauce Labs 2015
Variable Description
SELENIUM_DRIVER Contains the operating system, version and browser name of the selected browser, in a format designed for
use by the Selenium Client Factory
SAUCE_ACCESS_KEY The access key for the user used to invoke Sauce OnDemand
SAUCE_ONDEMAND_BROWSERS A JSON-formatted string representing browsers you selected for the job configuration, as described Setting
Desired Capabilities for Jenkins Projects
Page 221
Copyright Sauce Labs 2015
The session id can be obtained from the RemoteWebDriver instance and the job-name can be any string, but is generally the name of the
test class being executed.
To make sure that your test results and Sauce jobs are associated properly, you need to output the session id to stdout. For example, this is the
code you would use to output the session id to the Java stdout.
Page 222
Copyright Sauce Labs 2015
1. It provides a user interface that lets you populate environment variables on the Jenkins server that can be used in your tests (for
example, platform configurations, or your Sauce username and access key). Much of what the plugin does relates to the setting of
environment variables.
2. It automatically launches Sauce Connect when you enable it for a project.
3. It handles reporting between Jenkins and Sauce.
These topics describe how to install and configure the Jenkins plugin. They assume that you have some familiarity with Jenkins and the basics of
automated testing, but even if this is your first time working with Jenkins and Sauce, you should be able to set up a successful integration.
Page 223
Copyright Sauce Labs 2015
Requirements
You need to be able to access the IP range 162.222.72.0/21, saucelabs.com, and ondemand.saucelabs.com from your Jenkins
server. Check out the Jenkins documentation if you need to set up a proxy or other advanced network configuration.
You can install the Sauce OnDemand plugin for Jenkins though the Jenkins Administration page.
The Jenkins plugin provides an interface for storing your Sauce Labs authentication credentials as environment variables on the Jenkins server,
which is one of our best practices for testing with Sauce. This allows you to reference your credentials without having to hardcode them into your
tests, and because the plugin manages authentication at the global level, you can have multiple jobs running at the same time that use these
credentials.
1. After the plugin has installed and Jenkins has restarted, go to the Administration page in Jenkins.
2. Click Manage Jenkins.
3. Click Configure System.
4. Under Sauce Support, enter the Username and API Access Key for your Sauce account.
Check out the topic Setting Desired Capabilities for Jenkins Projects for more information about using environment variables.
Page 224
Copyright Sauce Labs 2015
The Jenkins plugin for Sauce automatically installs Sauce Connect on your Jenkins server, but you will need to configure your project to use it.
There are also global and per-project configuration options for Sauce Connect.
When you run a Jenkins build with Sauce Connect enabled, the default behaviour of the plugin is to extract the Sauce Connect binary that is
appropriate for your operating system to your home directory. You can change the location where the plugin extracts Sauce Connect for specific
projects, or at the global level for all projects. Note that Sauce Connect should always run on the same network as the site or application under
test, but does not have to be on the same machine.
There are a number of command line options you can use with Sauce Connect, which you can configure to execute at both the global level and
on a per-project basis when Sauce Connect launches.
Page 225
Copyright Sauce Labs 2015
Another advanced option is launching Sauce Connect on the Jenkins slave node that is executing the build, rather than on the Master node.
Page 226
Copyright Sauce Labs 2015
Prerequisites
Setting Desired Capabilities for Your Project
Setting Up Your Tests to Use the Environment Variables
Prerequisites
If you haven't enabled the Sauce plugin for Jenkins yet, you should follow the instructions in Installing and Configuring the Sauce
OnDemand Plugin for Jenkins.
If you select a single operating system/browser combination, then the environment variables SELENIUM_PLATFORM, SELENIUM_VERSIO
N, and SELENIUM_BROWSER will be populated with your selections. If you select a mobile operating system/browser, the variables SELEN
IUM_DEVICE and SELENIUM_DEVICE_TYPE will be populated.
If you select multiple OS/browser combinations, the SAUCE_ONDEMAND_BROWSERS environment variable will be populated with a
JSON-formatted string containing the attributes of the selected browsers, as shown in this example:
Page 227
Copyright Sauce Labs 2015
In your test script, you reference the environment variables as part of your desired capabilities. Though the exact syntax will vary depending on
your scripting language, this example illustrates the way you would reference the environment variables SELENIUM_BROWSER, SELENIUM_VERS
ION, AND SELENIUM_PLATFORM in your test script.
desiredCapabilities.setBrowserName(System.getenv("SELENIUM_BROWSER"));
desiredCapabilities.setVersion(System.getenv("SELENIUM_VERSION"));
desiredCapabilities.setCapability(CapabilityType.PLATFORM,
System.getenv("SELENIUM_PLATFORM"));
This example is for a single operating system/browser combination. If you have multiple selections, you can load the JSON string for the SAUCE_
ONDEMAND_BROWSERS environment variable by using the JSON library for your scripting language, and then loop through the string to send the
various combinations to your test framework.
Page 228
Copyright Sauce Labs 2015
Variable Description
SELENIUM_DRIVER Contains the operating system, version and browser name of the selected browser, in a format designed for
use by the Selenium Client Factory
SAUCE_ACCESS_KEY The access key for the user used to invoke Sauce OnDemand
SAUCE_ONDEMAND_BROWSERS A JSON-formatted string representing browsers you selected for the job configuration, as described Setting
Desired Capabilities for Jenkins Projects
Page 229
Copyright Sauce Labs 2015
1. Configure your test script to run tests in parallel following the examples for your scripting language.
2. Set up your Jenkins project as a Matrix Project.
3. Configure you Jenkins build as a Parameterized Build.
Page 230
Copyright Sauce Labs 2015
Jenkins matrix projects, also know as multi-configuration projects, allow you to run the same build with different input parameters. The Sauce
plugin for Jenkins provides an additional option for multi-configuration projects to specify the browser combination for each build.
1. When setting up your job in Jenkins, select Multi-Configuration Project, and then click OK.
2. under Configuration Matrix, click Add Axis.
3. Select the type of test you want to run with Sauce, for example Sauce OnDemand WebDriver tests.
The option you select will determine the list of operating systems and browsers you can choose in the next step.
4. Select the operating systems and browser combinations that you want to test against.
A separate job will run for each OS and browser combination that you select. The environment variables for SELENIUM_PLATFORM, SEL
ENIUM_VERSION, SELENIUM_BROWSER, and SELENIUM_DRIVER will be populated for each job with your selections.
Related Links
Page 231
Copyright Sauce Labs 2015
Setting up a parameterized build lets you configure your build so you can select the operating system and browsers to test against at build run
time, rather than in the build configuration itself. This is useful, for example, if you have a Jenkins project that's configured to run regression tests
and you want to quickly determine if your website will test successfully against a new browser combination without having to test against every
combination.
Page 232
Copyright Sauce Labs 2015
desiredCapabilities.setBuild(System.getenv("JENKINS_BUILD_NUMBER"));
This will ensure that the Jenkins build number is stored when the job is first run, and then you will be able to access your test reports in the Sauce
Labs dashboard by looking for the build number and then clicking through to the report, and the Sauce jobs that were executed as part of the build
will be listed on the Jenkins Build Details page.
The Sauce plugin for Jenkins will also mark the Sauce jobs as passed or failed, but you need to configure Jenkins to parse the test results.
Page 233
Copyright Sauce Labs 2015
Page 234
Copyright Sauce Labs 2015
Page 235
Copyright Sauce Labs 2015
Page 236
Copyright Sauce Labs 2015
Variable Description
SELENIUM_DRIVER Contains the operating system, version and browser name of the selected browser, in a format designed for
use by the Selenium Client Factory
SAUCE_ACCESS_KEY The access key for the user used to invoke Sauce OnDemand
SAUCE_ONDEMAND_BROWSERS A JSON-formatted string representing browsers you selected for the job configuration, as described Setting
Desired Capabilities for Jenkins Projects
Page 237
Copyright Sauce Labs 2015
The session id can be obtained from the RemoteWebDriver instance and the job-name can be any string, but is generally the name of the
test class being executed.
To make sure that your test results and Sauce jobs are associated properly, you need to output the session id to stdout. For example, this is the
code you would use to output the session id to the Java stdout.
Page 238
Copyright Sauce Labs 2015
Page 239
Copyright Sauce Labs 2015
Page 240
Copyright Sauce Labs 2015
Page 241
Copyright Sauce Labs 2015
Page 242
Copyright Sauce Labs 2015
Page 243
Copyright Sauce Labs 2015
Page 244
Copyright Sauce Labs 2015
Page 245
Copyright Sauce Labs 2015
Page 246
Copyright Sauce Labs 2015
Access Configuration
On your Team Management page, you can configure the saucelabs.com domain for your organization, require that all users in your organization
use Sauce Connect, and enable Single Sign-On (SSO) to manage user creation and authentication.
Page 247
Copyright Sauce Labs 2015
Page 248
Copyright Sauce Labs 2015
Related Topics
Page 249
Copyright Sauce Labs 2015
Page 250
Copyright Sauce Labs 2015
Okta
OneLogin
PingIdentity (PingOne)
Page 251
Copyright Sauce Labs 2015
Depending on your provider or unique configuration, you may need to upload SAML metadata to your identity provider to enable SAML
assertions.
PingIdentity Documentation
Okta Application Network
OneLogin Application Catalog
Page 252
Copyright Sauce Labs 2015
The SSO integration relies heavily on convention to keep set up quick and simple. Configuring your assertion using these specifications will
ensure a smooth transition for your users.
Configuring Attributes
The following attributes must be included in your assertion, with the expected values, for the integration to work correctly.
Required Attributes
Optional Attributes
Page 253
Copyright Sauce Labs 2015
Page 254
Copyright Sauce Labs 2015
Related Topics
Access Configuration
Page 255
Copyright Sauce Labs 2015
Page 256
Copyright Sauce Labs 2015
Adding Users
You can add users, set their concurrency limit, and associate them with a parent account on the Team Management page. You have the option
to invite users, in which case they set their own user name and password, or you can set the username and password yourself.
5. Enter a Username and Password for the user, along with an optional First Name and Last Name.
6. If you've configured Single Sign On (SSO) for your domain, select SSO User and usernames and passwords will be automatically
generated by your identity provider.
7. Under Concurrency Limit, enter the number of VMs and Devices you want to allocate to the user.
8. Select Admin if you want the user to be able to manage concurrency allocations for their peers and sub accounts.
If you want users associated with your account to also be able to add users, you need to select this option under Access Settings, as
explained in Managing Access Settings for All Users.
9. Click Done.
If you want to continue adding users, select Continue Creating Users and then click Done.
Page 257
Copyright Sauce Labs 2015
Deleting Users
You can delete users from your account on the Team Management page.
Page 258
Copyright Sauce Labs 2015
Page 259
Copyright Sauce Labs 2015
Page 260
Copyright Sauce Labs 2015
Page 261
Copyright Sauce Labs 2015
Account Description
Type
Owner There is only one owner per Organization. This is most top-level account in the hierarchy.
Admins Admins can manage both their peers (accounts that share the same parent) and any subaccounts below themselves or their
peers.
User Users can manage their own accounts, but no one else.
Page 262
Copyright Sauce Labs 2015
Page 263
Copyright Sauce Labs 2015
Page 264
Copyright Sauce Labs 2015
The API is versioned by URL. The current version is v1, and resides under the saucelabs.com/rest/v1/base URL. Some v1.1 methods have
been introduced under saucelabs.com/rest/v1.1/.
Authentication
The Sauce Labs REST API uses HTTP Basic Authentication. To authenticate, either include the Sauce username and access key in the request
URL, or add an Authorization header to the request.
Java SauceREST Java is a Java client for the Sauce OnDemand REST API, which https://github.com/saucelabs/saucerest-java
supersedes the previous sauce-rest-api. With this client you can update Job
info, including Pass/Fail status and other information.
Ruby Sauce_whisk provides an "ActiveRecord"-style client for the Sauce Labs API. https://github.com/saucelabs/sauce_whisk
PHP Your one-stop shop for everything Selenium + Sauce Labs + PHP. This is a https://github.com/jlipps/sausage
set of classes and libraries that make it easy to run your Selenium tests, either
locally or on Sauce Labs. You run the tests with PHPUnit.
Sausage comes bundled with Paratest (for running your PHPUnit tests in
parallel) and optionallySauce Connect (for testing locally-hosted sites with
Sauce).
Page 265
Copyright Sauce Labs 2015
Node.js Wrapper around the Sauce Labs REST API for Node.js. https://github.com/holidayextras/node-saucelabs
Page 266
Copyright Sauce Labs 2015
cURL and libcurl come pre-installed with OS X and Linux, and if you wanted to use the examples in this wiki to access the Sauce Labs API, all
you would need to do is open a terminal, paste in the command with your authentication credentials, and hit Enter to execute the API call. If you
are using a Windows machine, the situation is a little tricker, since cURL is a utility that you have to download and install. While the native
PowerShell command line tool for Windows includes the CmdLets Invoke-RestMethod and Invoke-WebRequest for accessing APIs, these
are only available if you are using PowerShell 3.0, and the interaction with the Sauce Labs API has not been fully tested. For these reasons, the
Sauce Labs recommendation for Windows users is to set up cURL on your machine, and then use the example cURL commands in the API
documentation to construct your API calls.
To run cURL on the command prompt, you need to set the path of the curl.exe to the PATH environment variable.
Single quotes (') do not work in Windows cURL. For commands that need them, you would need to use double quotes (")
For some API calls, the quotes that are inside brackets ('{') need to be escaped by a backslash (\). For example, if you wanted to run the
Change Job Status API call on Windows, the call would look like this:
Page 267
Copyright Sauce Labs 2015
Account Methods
These methods provide user account information and management.
Get User
Create User
Get User Concurrency
Get List of Sub Accounts
Get Sub Account Information
Windows Example
curl https://saucelabs.com/rest/v1/users/YOUR_US
-u YOUR_USERNAME:YOUR_ACCESS_KEY
Windows Example
curl https://saucelabs.com/rest/v1/users/YOUR_US
ency -u YOUR_USERNAME:YOUR_ACCESS_KEY
Page 268
Copyright Sauce Labs 2015
Page 269
Copyright Sauce Labs 2015
Bug Methods
Methods for interacting with the bug tracking system for jobs.
Windows Example
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY -G \https://s
aucelabs.com/rest/v1/bugs/update/YOUR_BUG_ID \ --dat
a-urlencode 'update={"Property-name-1":
"Property-Value-1"}
The only bug properties that can be updated via the API are Tit
le and Description.
Page 270
Copyright Sauce Labs 2015
Information Methods
Information resources are publicly available data about Sauce Lab's service.
Page 271
Copyright Sauce Labs 2015
Page 272
Copyright Sauce Labs 2015
Job Methods
Multiple Jobs Methods
Get Jobs
Get Number of Jobs
Get Full Jobs
Skip Jobs
Jobs to and From Time
Format Jobs
Single Job Methods
Update Job
Delete Job
Stop Job
Get Job Asset Names
Get Job Asset Files
Delete Job Assets
Windows Example
curl https://saucelabs.com/rest/v1/YOUR_USERNAME/jobs
-u YOUR_USERNAME:YOUR_ACCESS_KEY
Specifies the :username/jobs?limit=:number_of_jobs GET Example for getting last 10 job IDs
Get number of OS X/Linux Example
jobs to return.
Number Default is 100
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY \ https://saucela
bs.com/rest/v1/YOUR_USERNAME/jobs?limit=10
.
of Jobs
Windows Example
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY https://saucelabs
.com/rest/v1/YOUR_USERNAME/jobs?limit=10
Get full job :username/jobs?full=:get_full_info GET Example getting full information about the last 100 jobs
Get Full information, OS X/Linux Example
rather than
Jobs just IDs.
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY \ https://saucela
Default is fal bs.com/rest/v1/YOUR_USERNAME/jobs?full=true
se.
Windows Example
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY https://saucelabs
.com/rest/v1/YOUR_USERNAME/jobs?full=true
Response Fields
id: [string] Job Id
owner: [string] Job owner
status: [string] Job status
error: [string] Error (if any) for the job
name: [string] Job name
browser: [string] Browser the job is using
browser_version: [string] Browser version the job is using
os: [string] Operating system the job is using
creation_time: [integer] The time the job was first
requested
start_time: [integer] The time the job began executing
end_time: [integer] The time the job finished executing
video_url: [string] Full URL to the video replay of the job
log_url: [string] Full URL to the Selenium log of the job
public: [string or boolean] Visibility mode [public, public
restricted, share (true), team (false), private]
tags: [array of strings] Tags assigned to a job
Page 273
Copyright Sauce Labs 2015
Skips the :username/jobs?skip=:number_of_jobs GET Example getting the last 100 job IDs, skipping 20 most recent jobs
Skip specified OS X/Linux Example
number of
Jobs jobs. Default
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY \ https://saucela
bs.com/rest/v1/YOUR_USERNAME/jobs?skip=20
is 0.
Windows Example
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY https://saucelabs
.com/rest/v1/YOUR_USERNAME/jobs?skip=20
Get jobs :username/jobs?to=:time GET Example Request (replace EPOCH_TIME with an epoch time)
Jobs to since/until the OS X/Linux Example
specified time and
and (in epoch curl -u YOUR_USERNAME:YOUR_ACCESS_KEY \ https://saucela
time, :username/jobs?from=:time bs.com/rest/v1/YOUR_USERNAME/jobs?from=EPOCH_TIME
From calculated
from UTC) Windows Example
Time curl -u YOUR_USERNAME:YOUR_ACCESS_KEY https://saucelabs
.com/rest/v1/YOUR_USERNAME/jobs?from=EPOCH_TIME
Get job info in :username/jobs?format=:job_format GET Example getting last 100 job IDs using the CSV format
Format the specified OS X/Linux Example
format.
Jobs Supported
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY \ https://saucela
bs.com/rest/v1/YOUR_USERNAME/jobs?format=csv
formats are j
son and csv
Windows Example
. Default is
json. curl -u YOUR_USERNAME:YOUR_ACCESS_KEY https://saucelabs
.com/rest/v1/YOUR_USERNAME/jobs?format=csv
Page 274
Copyright Sauce Labs 2015
Windows Example
curl -u YOUR_USERNAME:YOUR_ACCESS_KEY -X PUT -d https
NAME/jobs/YOUR_JOB_ID/stop
Response Fields
Each of these fields will be set to null if the specific asset isn't cap
The job
assests will
be deleted
from the test
page after 30
days. Thus,
after 30 days
all your test
commands,
logs,
screenshots
and the
screencast
recording will
be gone. This
is the reason
why we
strongly
recommend
to download
your job
assets if this
is an
information
that you must
keep in your
records.
Page 275
Copyright Sauce Labs 2015
Page 276
Copyright Sauce Labs 2015
Upload File
Get Stored Files
Overwriting Files
By default, the REST API prevents overwriting files already stored in
storage. The overwrite=true query parameter (shown in the exa
overwriting.
Page 277
Copyright Sauce Labs 2015
Page 278
Copyright Sauce Labs 2015
Page 279
Copyright Sauce Labs 2015
Tunnel Methods
Get Tunnels
Get Tunnel
Delete Tunnel
Response Fields
https://saucelabs.com/rest
ID
Windows Example
curl -u YOUR_USERNAME:YOUR_
-X DELETE \
https://saucelabs.com/rest/
Page 280