Posts Tagged ‘selenium’

How To Add Visual Testing To Existing Selenium Tests

February 27th, 2015 by Dave Haeffner

Thanks again to those of you who attended our recent webinar with Applitools on automated visual testing.  If you want to share it or if you happened to miss it, you can catch the audio and slides hereWe also worked with Selenium expert Dave Haeffner to provide the how-to on the subject. Enjoy his post below.

 

The Problem

In previous write-ups I covered what automated visual testing is and how to do it. Unfortunately, based on the examples demonstrated, it may be unclear how automated visual testing fits into your existing automated testing practice.

Do you need to write and maintain a separate set of tests? What about your existing Selenium tests? What do you do if there isn’t a sufficient library for the programming language you’re currently using?

A Solution

You can rest easy knowing that you can build automated visual testing checks into your existing Selenium tests. By leveraging a third-party platform like Applitools Eyes, this is a simple feat.

And when coupled with Sauce Labs, you can quickly add coverage for those hard to reach browser, device, and platform combinations.

Let’s step through an example.

An Example

NOTE: This example is written in Java with the JUnit testing framework.

Let’s start with an existing Selenium test. A simple one that logs into a website.

// filename: Login.java

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Login {

    private WebDriver driver;

    @Before
    public void setup() {
        driver =  new FirefoxDriver();
    }

    @Test
    public void succeeded() {
        driver.get("http://the-internet.herokuapp.com/login");
        driver.findElement(By.id("username")).sendKeys("tomsmith");
        driver.findElement(By.id("password")).sendKeys("SuperSecretPassword!");
        driver.findElement(By.id("login")).submit();
        Assert.assertTrue("success message should be present after logging in",
                driver.findElement(By.cssSelector(".flash.success")).isDisplayed());
    }

    @After
    public void teardown() {
        driver.quit();
    }
}

In it we’re loading an instance of Firefox, visiting the login page on the-internet, inputting the username & password, submitting the form, asserting that we reached a logged in state, and closing the browser.

Now let’s add in Applitools Eyes support.

If you haven’t already done so, you’ll need to create a free Applitools Eyes account (no credit-card required). You’ll then need to install the Applitools Eyes Java SDK and import it into the test.

// filename: pom.xml

<dependency>
  <groupId>com.applitools</groupId>
  <artifactId>eyes-selenium-java</artifactId>
  <version>RELEASE</version>
</dependency>
// filename: Login.java

import com.applitools.eyes.Eyes;
...

Next, we’ll need to add a variable (to store the instance of Applitools Eyes) and modify our test setup.

// filename: Login.java
...
public class Login {

    private WebDriver driver;
    private Eyes eyes;

    @Before
    public void setup() {
        WebDriver browser =  new FirefoxDriver();
        eyes = new Eyes();
        eyes.setApiKey("YOUR_APPLITOOLS_API_KEY");
        driver = eyes.open(browser, "the-internet", "Login succeeded");
    }
...

Rather than storing the Selenium instance in the driver variable, we’re now storing it in a localbrowser variable and passing it into eyes.open — storing the WebDriver object that eyes.openreturns in the driver variable instead.

This way the Eyes platform will be able to capture what our test is doing when we ask it to capture a screenshot. The Selenium actions in our test will not need to be modified.

Before calling eyes.open we provide the API key (which can be found on your Account Details page in Applitools). When calling eyes.open, we pass it the Selenium instance, the name of the app we’re testing (e.g., "the-internet"), and the name of the test (e.g., "Login succeeded").

Now we’re ready to add some visual checks to our test.

// filename: Login.java
...
    @Test
    public void succeeded() {
        driver.get("http://the-internet.herokuapp.com/login");
        eyes.checkWindow("Login");
        driver.findElement(By.id("username")).sendKeys("tomsmith");
        driver.findElement(By.id("password")).sendKeys("SuperSecretPassword!");
        driver.findElement(By.id("login")).submit();
        eyes.checkWindow("Logged In");
        Assert.assertTrue("success message should be present after logging in",
                driver.findElement(By.cssSelector(".flash.success")).isDisplayed());
        eyes.close();
    }
...

With eyes.checkWindow(); we are specifying when in the test’s workflow we’d like Applitools Eyes to capture a screenshot (along with some description text). For this test we want to check the page before logging in, and then the screen just after logging in — so we use eyes.checkWindow(); two times.

NOTE: These visual checks are effectively doing the same work as the pre-existing assertion (e.g., where we’re asking Selenium if a success notification is displayed and asserting on the Boolean result) — in addition to reviewing other visual aspects of the page. So once we verify that our test is working correctly we can remove this assertion and still be covered.

We end the test with eyes.close. You may feel the urge to place this in teardown, but in addition to closing the session with Eyes, it acts like an assertion. If Eyes finds a failure in the app (or if a baseline image approval is required), then eyes.close will throw an exception; failing the test. So it’s best suited to live in the test.

NOTE: An exceptions from eyes.close will include a URL to the Applitools Eyes job in your test output. The job will include screenshots from each test step and enable you to play back the keystrokes and mouse movements from your Selenium tests.

When an exception gets thrown by eyes.close, the Eyes session will close. But if an exception occurs before eyes.close can fire, the session will remain open. To handle that, we’ll need to add an additional command to our teardown.

// filename: Login.java
...
    @After
    public void teardown() {
        eyes.abortIfNotClosed();
        driver.quit();
    }
}

eyes.abortIfNotClosed(); will make sure the Eyes session terminates properly regardless of what happens in the test.

Now when we run the test, it will execute locally while also performing visual checks in Applitools Eyes.

What About Other Browsers?

If we want to run our test with it’s newly added visual checks against other browsers and operating systems, it’s simple enough to add in Sauce Labs support.

NOTE: If you don’t already have a Sauce Labs account, sign up for a free trial account here.

First we’ll need to import the relevant classes.

// filename: Login.java
...
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
...

We’ll then need to modify the test setup to load a Sauce browser instance (via Selenium Remote) instead of a local Firefox one.

// filename: Login.java
...
    @Before
    public void setup() throws Exception {
        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability("platform", Platform.XP);
        capabilities.setCapability("version", "8");
        capabilities.setCapability("name", "Login succeeded");
        String sauceUrl = String.format(
                "http://%s:%s@ondemand.saucelabs.com:80/wd/hub",
                "YOUR_SAUCE_USERNAME",
                "YOUR_SAUCE_ACCESS_KEY");
        WebDriver browser = new RemoteWebDriver(new URL(sauceUrl), capabilities);
        eyes = new Eyes();
        eyes.setApiKey(System.getenv("APPLITOOLS_API_KEY"));
        driver = eyes.open(browser, "the-internet", "Login succeeded");
    }
...

We tell Sauce what we want in our test instance through DesiredCapabilities. The main things we want to specify are the browser, browser version, operating system (OS), and name of the test. You can see a full list of the available browser and OS combinations here.

In order to connect to Sauce, we need to provide an account username and access key. The access key can be found on your account page. These values get concatenated into a URL that points to Sauce’s on-demand Grid.

Once we have the DesiredCapabilities and concatenated URL, we create a Selenium Remote instance with them and store it in a local browser variable. Just like in our previous example, we feedbrowser to eyes.open and store the return object in the driver variable.

Now when we run this test, it will execute against Internet Explorer 8 on Windows XP. You can see the test while it’s running in your Sauce Labs account dashboard. And you can see the images captured on your Applitools account dashboard.

A Small Bit of Cleanup

Both Applitools and Sauce Labs require you to specify a test name. Up until now, we’ve been hard-coding a value. Let’s change it so it gets set automatically.

We can do this by leveraging a JUnit TestWatcher and a public variable.

// filename: Login.java
...
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
...
public class Login {

    private WebDriver driver;
    private Eyes eyes;
    public String testName;

    @Rule
    public TestRule watcher = new TestWatcher() {
        protected void starting(Description description) {
            testName = description.getDisplayName();
        }
    };
...

Each time a test starts, the TestWatcher starting function will grab the display name of the test and store it in the testName variable.

Let’s clean up our setup to use this variable instead of a hard-coded value.

// filename: Login.java
...
    @Before
    public void setup() throws Exception {
        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability("platform", Platform.XP);
        capabilities.setCapability("version", "8");
        capabilities.setCapability("name", testName);
        String sauceUrl = String.format(
                "http://%s:%s@ondemand.saucelabs.com:80/wd/hub",
                System.getenv("SAUCE_USERNAME"),
                System.getenv("SAUCE_ACCESS_KEY"));
        WebDriver browser = new RemoteWebDriver(new URL(sauceUrl), capabilities);
        eyes = new Eyes();
        eyes.setApiKey(System.getenv("APPLITOOLS_API_KEY"));
        driver = eyes.open(browser, "the-internet", testName);
    }
...

Now when we run our test, the name will automatically appear. This will come in handy with additional tests.

One More Thing

When a job fails in Applitools Eyes, it automatically returns a URL for it in the test output. It would be nice if we could also get the Sauce Labs job URL in the output. So let’s add it.

First, we’ll need a public variable to store the session ID of the Selenium job.

// filename: Login.java
...
public class Login {

    private WebDriver driver;
    private Eyes eyes;
    public String testName;
    public String sessionId;
...

Next we’ll add an additional function to TestWatcher that will trigger when there’s a failure. In it, we’ll display the Sauce job URL in standard output.

// filename: Login.java
...
    @Rule
    public TestRule watcher = new TestWatcher() {
        protected void starting(Description description) {
            testName = description.getDisplayName();
        }

        @Override
        protected void failed(Throwable e, Description description) {
            System.out.println(String.format("https://saucelabs.com/tests/%s", sessionId));
        }
    };
...

Lastly, we’ll grab the session ID from the Sauce browser instance just after it’s created.

// filename: Login.java
...
        WebDriver browser = new RemoteWebDriver(new URL(sauceUrl), capabilities);
        sessionId = ((RemoteWebDriver) browser).getSessionId().toString();
...

Now when we run our test, if there’s a Selenium failure, a URL to the Sauce job will be returned in the test output.

Expected Outcome

  • Connect to Applitools Eyes
  • Load an instance of Selenium in Sauce Labs
  • Run the test, performing visual checks at specified points
  • Close the Applitools session
  • Close the Sauce Labs session
  • Return a URL to a failed job in either Applitools Eyes or Sauce Labs

Outro

Happy Testing!

 

About Dave Haeffner: Dave is the author of Elemental Selenium (a free, once weekly Selenium tip newsletter that is read by hundreds of testing professionals) as well as a new book, The Selenium Guidebook. He is also the creator and maintainer of ChemistryKit (an open-source Selenium framework). He has helped numerous companies successfully implement automated acceptance testing; including The Motley Fool, ManTech International, Sittercity, and Animoto. He is a founder and co-organizer of the Selenium Hangout and has spoken at numerous conferences and meetups about acceptance testing.

Automated Testing News: Link Round-Up

January 30th, 2015 by Amber Kaplan
Happy Friday! Here’s a quick round-up of some pieces around the web. This week, learn about some on tools for checkout optimization, how to leverage automated UI testing on Sauce with Grunt and Intern, and get more QTP/UFT VS Selenium resources.  See below for snippets and links to the full articles.

(more…)

QTP/UFT VS Selenium [RECAP]

January 29th, 2015 by Amber Kaplan

selenium-logo-160x144Thanks for joining us for our last webinar, QTP/UFT VS Selenium, featuring Tarun Lalwani, QTP expert and author of QuickTest Professional Unplugged.

In this webinar, Tarun explains how we generated an 80% execution time savings by migrating client’s test suite from QTP to Selenium, along with answering the following questions:

  • How is Selenium different from QTP?
  • Why do I need to migrate to Selenium?
  • What are the advantages and disadvantages of the migration?
  • How do I plan the migration?
  • What challenges will I face during Migration?

Missed the presentation, want to hear it again, or share with a colleague?

Listen to the recording HERE and view the slides below.

Automated Testing News: Link Round-Up

January 23rd, 2015 by Amber Kaplan
Happy Friday! Here’s a quick round-up of some pieces on automated testing, why functional and performance testing should be done simultaneously, the case for Continuous Testing in the Cloud,  how to take your career to the next level, QTP/UFT VS Selenium, and what the top 10 tools were this week on Stackshare.  See below for snippets and links to the full articles.

(more…)

QTP/UFT VS Selenium [WEBINAR]

January 21st, 2015 by Amber Kaplan

selenium testing & sauceModern testing practices have shifted dramatically in recent years. As open source tools such as Selenium have begun to be accepted and incorporated into the enterprise testing landscape, proprietary tools like HP’s QTP/UFT have begun to be transitioned out in many cases. While there are many benefits to using a tool like Selenium (for example, it’s maximized when used as an automated testing tool, works with every browser, and plays nicely with all major computer languages and frameworks), the most compelling case to make the transition is the developer and QA time saved.

Join us for our next webinar, QTP/UFT VS Selenium, featuring Tarun Lalwani, QTP Expert and author of QuickTest Professional Unplugged. Hear about how we generated an 80% execution time savings by migrating client’s test suite from QTP to Selenium. We will also answer following questions:

  • How is Selenium different from QTP?
  • Why do I need to migrate to Selenium?
  • What are the advantages and disadvantages of the migration?
  • How do I plan the migration?
  • What challenges will I face during Migration?

Click HERE to register for our next webinar on Wednesday, January 28th, 2015, at 10:00am PST.

A live Q&A will follow at the end of the presentation.

Note: This is not a “how to” or “technology session” on Selenium or QTP. This is session is focused on giving you a understanding whether Selenium is right for you or not.

Recent Updates to Selenium Builder

December 11th, 2014 by Amber Kaplan

Great news for Enterprise folks and those who are newer to Selenium! Updates were made on Selenium Builder recently. (more…)

Announcing Sauce Labs’ New Platform Configurator

November 17th, 2014 by lauren nguyen

selenium platformsWe’ve just released our new platform configurator that easily generates the code you need to configure your automated tests to run on Sauce. You can select the automation API, device type, operating system, and browser version you want to test with, and it will automatically generate a snippet of code for those desired capabilities. You can toggle between code generated for different languages. (more…)

Sauce Labs Adds Support for Chrome and Firefox Beta and Dev Versions

November 14th, 2014 by lauren nguyen

browser dev versionsWe’re excited to be releasing support for testing on Chrome and Firefox beta and dev versions for Mac OS X, Linux, and Windows. The beta and dev versions are available for both automated and manual testing. And to give you access to new platforms as quickly as possible, we’ll continue to add support for bleeding edge versions the day they’re released. (more…)

HomeAway + Sauce Labs: Continuous Delivery Made Awesome [VIDEO]

October 7th, 2014 by Amber Kaplan

A few weeks back, we sat down with Carl Shaulis at HomeAway to learn how they leverage Sauce Labs‘ cloud in their testing process.

HomeAway, Inc. is the world’s leading online marketplace for the vacation rental industry. With over one million live vacation rental listings in 190 countries paired with a family of 50 websites and hundreds of applications thanks to a series of acquisitions, quality is their top priority. To get ahead of the curve, Carl’s team is trying to automate and use best practices like continuous integration as much as possible. We were also thrilled to hear that they’re using Appium, a cross-platform test automation framework powered by Sauce Labs, for their mobile testing.  Carl also says Sauce fits perfectly into their testing process.

Watch the video below to learn more about their path towards continuous delivery, and how Sauce fits into that story.

(more…)

Recap: Sauce Labs at Selenium Conf 2014 [VIDEO]

September 24th, 2014 by Amber Kaplan

We’re still glowing from this year’s Selenium Conf in Bangalore. Santi Ordonez, Ashley Wilson, and Isaac Murchie attended the event and represented Sauce Labs.

The Selenium Conference is a volunteer-run, non-profit event presented by members of the Selenium Community. The goal of the conference is to bring together Selenium developers & enthusiasts from around the world to share ideas, socialize, and work together on advancing the present and future success of the project.

(more…)