Latest Event Updates

Highlight elements with Selenium WebDriver

Posted on Updated on

Problem

We like to highlight elements with Selenium WebDriver like we could do with the previous version of Selenium. This will help us to see what is actually is going on in the browser. This method will slow down your tests a bit, but sometimes it is useful for debugging purpose.

Solution

 
1
2
3
4
5
6
7
8
9
public void highlightElement(WebDriver driver, WebElement element) {
    for (int i = 0; i < 2; i++) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                element, "color: yellow; border: 2px solid yellow;");
        js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                element, "");
    }
}

How to use it

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Test
public void highlightTest() {
    WebElement searchField = driver.findElement(By
            .cssSelector("input#search_query_top"));
    highlightElement(searchField);
    searchField.sendKeys("ipod nano");

    WebElement searchButton = driver.findElement(By.cssSelector("input[name='submit_search']"));
    highlightElement(searchButton);
    searchButton.click();

    String searchHeader = driver.findElement(By.cssSelector("H1")).getText().toLowerCase();
    Assert.assertTrue(searchHeader.contains("ipod nano"));
}

public void highlightElement(WebElement element) {
    for (int i = 0; i < 2; i++) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                element, "color: yellow; border: 2px solid yellow;");
        js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                element, "");
    }
}

– See more at: http://selenium.polteq.com/en/category/tips-tricks/#sthash.G7LIVZco.dpuf

Capture javascript errors with Selenium WebDriver

Posted on Updated on

import java.io.IOException;
import java.util.List;

import net.jsourcerer.webdriver.jserrorcollector.JavaScriptError;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class CaptureJavascriptErrors {
    private static WebDriver driver;
    
    @BeforeClass
    public void setUp() throws IOException {
        FirefoxProfile ffProfile = new FirefoxProfile();
        JavaScriptError.addExtension(ffProfile);
        driver = new FirefoxDriver(ffProfile);
        driver.get("http://www.telegraaf.nl/");
    }
    
    @AfterClass
    public void tearDown() {
        List<JavaScriptError> jsErrors = JavaScriptError.readErrors(driver);
        System.out.println("###start displaying errors");
        for(int i = 0; i < jsErrors.size(); i++) {
            System.out.println(jsErrors.get(i).getErrorMessage());
            System.out.println(jsErrors.get(i).getLineNumber());
            System.out.println(jsErrors.get(i).getSourceName());
        }
        System.out.println("###start displaying errors");
        driver.close();
        driver.quit();
    }
    
    @Test
    public void returnJavascriptErrors() throws InterruptedException {
        Thread.sleep(5000);
    }
}

 

Display the HAR format

Posted on Updated on

Problem

We have seen the HAR (Http ARchive) format as the output from the BrowserMob proxy implementation and the NetExport implementation. The HAR file contains a log with requests and responses to the server. The file can be displayed as a waterfall or as an expandable tree. This recipe shows a couple of ways to view the HAR format.

 

Prerequisites

Make sure you gathered a HAR file from the application under test.

Solution

We will see how to view a HAR file by using an online viewer.

  1. Open the online HAR viewer, http://www.softwareishard.com/har/viewer/
  2. Copy and paste the contents of the HAR file into the textbox. We can also drag and drop the file from our file-system to the website.
  3. Press Preview, in case you copied the contents of the HAR file.
  4. The result will look like the image below:

What has been done

The online HAR viewer reads the HAR file and builds the waterfall diagram.

There’s more…

There are more ways to view the HAR files. This section will cover a couple of frequently used ways.

Fiddler

We have to follow a couple of steps before we can view a HAR file in Fiddler. The steps are described below:

  1. Download fiddler from the following website: http://www.fiddler2.com
  2. Install Fiddler on your local machine
  3. Click on File → Import Sessions… and select your import format
  4. Select the existing HAR file from your filesystem.
  5. All the details from the sessions are visible in Fiddler.

Showslow.com

NetExport gives us the functionality to upload the HAR file to http://www.showslow.com/beacon/har/. The HAR file is now accessible from the internet and can be easily shared with others. It is even possible to install ShowSlow on a private server to limit the risk.

– See more at: http://selenium.polteq.com/en/category/measuring-performance/#sthash.rJ3UHvgw.dpuf

Use NetExport to export Firebug’s NET panel

Posted on Updated on

Problem

Firebug comes with a create feature which is visible in the NET panel. The NET panel gives use the per item download time in a breakdown structure. This structure is build up from a HAR file. This recipe shows us how we can export the HAR file from a code perspective.

Prerequisites

We have to download three firefox add-ons, before we can start implementing this. It is not mandatory to install the add-ons, we can also store them locally. The following three files are available from http://getfirebug.com/releases/ : firebug, NetExport and firestarter.

Solution

The following code can be used in the setup method to implement the NetExport measurements:

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@BeforeMethod
public void setUp() {
    FirefoxProfile profile = new FirefoxProfile();
    try {
        profile.addExtension(new File("c:/firebug-1.7.2.xpi"));
        profile.addExtension(new File("c:/netExport-0.8b16.xpi"));
        profile.addExtension(new File("c:/fireStarter-0.1a6.xpi"));
    } catch (IOException e) {
        throw new RuntimeException("Could not load required extensions, did you download them to the above location? ", e);
    }
        profile.setPreference("extensions.firebug.currentVersion", "9.99");
        profile.setPreference("extensions.firebug.DBG_NETEXPORT", false);
        profile.setPreference("extensions.firebug.onByDefault", true);
        profile.setPreference("extensions.firebug.defaultPanelName", "net");
        profile.setPreference("extensions.firebug.net.enableSites", true);
        profile.setPreference("extensions.firebug.net.persistent", true);
        profile.setPreference("extensions.firebug.netexport.alwaysEnableAutoExport", true);
        profile.setPreference("extensions.firebug.netexport.autoExportToFile", true);
        profile.setPreference("extensions.firebug.netexport.autoExportToServer", false);
        profile.setPreference("extensions.firebug.netexport.defaultLogDir", "C:\\temp");
        profile.setPreference("extensions.firebug.netexport.showPreview", true); // preview.
        profile.setPreference("extensions.firebug.netexport.sendToConfirmation", false);
        profile.setPreference("extensions.firebug.netexport.pageLoadedTimeout", 1500);
        profile.setPreference("extensions.firebug.netexport.Automation", true);
    driver = new FirefoxDriver(profile);
    selenium = new WebDriverBackedSelenium(driver, "http://www.google.com");
}

Do not forget to update the paths to the latest version of the extensions. The code above is tested with Mozilla Firefox 3.6.

What has been done

The script will load three add-ons while launching the Firefox browser. Some parameters are set, like the default logging folder.

– See more at: http://selenium.polteq.com/en/category/measuring-performance/#sthash.rJ3UHvgw.dpuf

Implement code timings

Posted on Updated on

Problem

The easiest way to get some performance related metrics is to implement timings in your testcode. This will work in every browser which is the big advantage. The disadvantage is probably that we have to enrich the testcode with timers. A lot of websites will use AJAX or other JavaScript functionality, these days. It can be interesting to see how long it takes before an element appears in the HTML DOM. In this recipe we will see how we can implement a timing strategy in the testcode itself.

Prerequisites

Think of the objectives you want to measure, because the outcome really depends on the implementation.

Solution

The script within a testmethod will be executed hierarchically, from top till down. The moment the script hits the line with long startTime, the start-time will be stored in a local variable. The moment the script hits the line with long endTime, the end-time will be stored in a local variable. After that the time difference is calculated, with long totalTime = endTime – startTime;.

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Test
public void codeTimings() {
    driver.get("/");
    long startTime = System.currentTimeMillis();
    WebElement search = driver.findElement(By.id("q"));
    search.sendKeys("Selenium");
    search.submit();
    assertTrue(driver.findElement(By.tagName("body")).getText()
                .contains("Selenium"));
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("Totaltime: " + totalTime + "milliseconds");
    WebElement result = driver.findElement(By.linkText("Selenium"));
    result.click();
    assertTrue(driver.findElement(By.tagName("body")).getText()
                .contains("Selenium"));
    
}

There’s more…

We have to enrich our testscripts with a lot of extra code, following the above principles. What will happen if the way we calculated the time difference will change or we want to store the time difference in a database? We have to adjust the code on multiple places. A solution for this challenge is to extract the code to a separate class. We can use the class below to calculate the timings.

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Timer {
    private long startTime = 0;
    private long endTime = 0;

    public void start() {
        this.startTime = System.currentTimeMillis();
    }

    public void end() {
        this.endTime = System.currentTimeMillis();
    }

    public long getStartTime() {
        return this.startTime;
    }

    public long getEndTime() {
        return this.endTime;
    }

    public long getTotalTime() {
        return this.endTime - this.startTime;
    }
}

We have to initialize a new object if we want to use the functions. We can use the code below for implementing the timer class.

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Test
public void measureWebTimings() {
    driver.get("/");
    Timer timer = new Timer();
    timer.start();
    WebElement search = driver.findElement(By.id("q"));
    search.sendKeys("Selenium");
    search.submit();
    assertTrue(driver.findElement(By.tagName("body")).getText()
                .contains("Selenium"));
    timer.end();
    System.out.println("Totaltime: " + timer.getTotalTime()
                + " milliseconds");
    WebElement result = driver.findElement(By.linkText("Selenium"));
    result.click();
    assertTrue(driver.findElement(By.tagName("body")).getText()
                .contains("Selenium"));
}

– See more at: http://selenium.polteq.com/en/category/measuring-performance/#sthash.rJ3UHvgw.dpuf

Run test scripts against a real iPhone device

Posted on Updated on

Problem

We want to execute our testscripts on a iphone device. The iphone driver allows us to execute the WebDriver tests on a real iphone device.

Prerequisites

We need to install Xcode which is available for the Mac operating systems. We also need a provisoning profile for running the script on a real device.

  1. We need to create a provisioning profile, so go to this website http://developer.apple.com/programs/ios/ and create a profile.
  2. We need to download Xcode from the following location: http://developer.apple.com/iphone
  3. The iPhone WebDriver application is not available from the App Store, therefore we need to check-out the code and build it manually. We can do the check-out by entering the following terminal command: svn checkout http://selenium.googlecode.com/svn/trunk/ selenium-read-only

More information on SVN checkouts: http://www.linuxfromscratch.org/blfs/edguide/chapter03.html

Solution

  1. Open the project selenium-read-only/iphone/iWebDriver.xcodeproj in Xcode.
  2. Double-click on the project and set the build configuration to the latest version of the iPhone Simulator, by using the drop-down box in the top left corner.
  3. Configure and install the iPhone provisioning profile.
  4. Open Info.plist and edit the Bundle Identifier to com.NAME.$ {PRODUCT_NAME:identifier} where NAME is the name you registered your provisioning profile to be an authority on.
  5. Make sure your device is connected to your computer. Your device must also be routable from your computer. The easiest way to do this is to configure a wifi network and connect your device to it.
  6. Click on Run (play button). After compiling, the iphone simulator should appear and the iWebDriver app will be installed in it.
  7. Now we can use the IPhoneDriver in our tests.
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.iphone.IPhoneDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class MobileIphoneSimulator {
    private static WebDriver driver;
    
    @BeforeClass
    public void setUp() throws Exception {
        driver = new IPhoneDriver();
        driver.get("http://selenium.polteq.com/prestashop/");
    }
    
    @AfterClass
    public void tearDown() {
        driver.close();
        driver.quit();
    }
    
    @Test
    public void measurePerformance() throws InterruptedException {
        Thread.sleep(1500);
        driver.findElement(By.cssSelector("input#search_query_top")).sendKeys("ipod nano");
        driver.findElement(By.cssSelector("input[name='submit_search']")).click();
        String searchHeader = driver.findElement(By.cssSelector("H1")).getText().toLowerCase();
            
        Assert.assertTrue(searchHeader.contains("ipod nano"));
    }
}

– See more at: http://selenium.polteq.com/en/category/testing-on-mobile-browsers/#sthash.tHTffaYJ.dpuf

Run tests on a real Android device

Posted on Updated on

Problem

We want to run our testscripts on a real Android device. The android driver allows us to execute our tests against an Android browser. This can be a simulator or a real device.

Prerequisites

Before we can register our device we have to download the android SDK (Software Development Kit) from the following location: http://developer.android.com/sdk/

Solution

We can divide this section into three parts: setup the device, install the WebDriver APK and finally run the test.

Setup the device

Connect the android device with the computer using a USB cable.

Install the WebDriver APK

  1. We need to retrieve the serial id with the following command: /android_sdk/platform-tools/adb devices
  2. Download the Android server from http://code.google.com/p/selenium/downloads/list and save it in the platform-tools directory. To install the application enter: $./adb -s <serialId> -e install -r android-server.apk
  3. Start the Android WebDriver application,by running this command: $./adb -s <serialId> shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity
  4. Now we need to setup the port forwarding in order to forward traffic from the host machine to the emulator. Enter the following in the terminal: $./adb -s <serialId> forward tcp:8080 tcp:8080

Run the test

Now we have our environment setup we can run our tests. The test will look like this:

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.android.AndroidDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class MobileAndroidDevice {
    private static WebDriver driver;
    
    @BeforeClass
    public void setUp() throws Exception {
        driver = new AndroidDriver();
        driver.get("http://selenium.polteq.com/prestashop/");
    }
    
    @AfterClass
    public void tearDown() {
        driver.close();
        driver.quit();
    }
    
    @Test
    public void measurePerformance() throws InterruptedException {
        Thread.sleep(1500);
        driver.findElement(By.cssSelector("input#search_query_top")).sendKeys("ipod nano");
        driver.findElement(By.cssSelector("input[name='submit_search']")).click();
        String searchHeader = driver.findElement(By.cssSelector("H1")).getText().toLowerCase();
            
        Assert.assertTrue(searchHeader.contains("ipod nano"));
    }
}

– See more at: http://selenium.polteq.com/en/category/testing-on-mobile-browsers/#sthash.tHTffaYJ.dpuf

Running tests on an Android simulator

Posted on Updated on

Problem

The android driver allows us to execute our tests against an Android browser. This can be a simulator or a real device. This recipe will walk us through the steps we have to do to run our tests in a simulator.

Prerequisites

Before we can register our simulator we have to download the android SDK (Software Development Kit) from the following location: http://developer.android.com/sdk/

Solution

We can divide this section into three parts: setup the emulator, install the WebDriver APK and finally run the test.

Setup the emulator

Navigate to the tools directory and create an Android Virtual Device.

 
1
2
$cd ~/android_sdk/tools/
$./android create avd -n my_android -t 12 -c 100M

-n: specifies the name of the AVD -t: specifies the platform target -c: specifies the SD card storage space

We can list the targets with the following command to check if the creation succeeded:

./android list targets

Finally we can start the emulator with the following command:

$./emulator -avd my_android &

Install the WebDriver APK

  1. We need to retrieve the serial id with the following command: /android_sdk/platform-tools/adb devices
  2. Download the Android server from http://code.google.com/p/selenium/downloads/list and save it in the platform-tools directory. To install the application enter: $./adb -s <serialId> -e install -r android-server.apk
  3. Start the Android WebDriver application,by running this command: $./adb -s <serialId> shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity
  4. Now we need to setup the port forwarding in order to forward traffic from the host machine to the emulator. Enter the following in the terminal: $./adb -s <serialId> forward tcp:8080 tcp:8080

Run the test

Now we have our environment setup we can run our tests. The test will look like this:

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.android.AndroidDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class MobileAndroidDevice {
    private static WebDriver driver;
    
    @BeforeClass
    public void setUp() throws Exception {
        driver = new AndroidDriver();
        driver.get("http://selenium.polteq.com/prestashop/");
    }
    
    @AfterClass
    public void tearDown() {
        driver.close();
        driver.quit();
    }
    
    @Test
    public void measurePerformance() throws InterruptedException {
        Thread.sleep(1500);
        driver.findElement(By.cssSelector("input#search_query_top")).sendKeys("ipod nano");
        driver.findElement(By.cssSelector("input[name='submit_search']")).click();
        String searchHeader = driver.findElement(By.cssSelector("H1")).getText().toLowerCase();
            
        Assert.assertTrue(searchHeader.contains("ipod nano"));
    }
}

– See more at: http://selenium.polteq.com/en/category/testing-on-mobile-browsers/#sthash.wQAUNFGT.dpuf

Switch to User Agent – Firefox | Chrome

Posted on Updated on

Switching user-agent can be done through browser custom profile.

Firefox

1| Install the Firefox Add-on, User Agent Switcher
2| Go to Tools > Default User Agent > Edit User Agents… 
3| Select any User agent from list and click Edit button
4| Get the user agent string. e.g., Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile(“default”);
myprofile.setPreference(“general.useragent.override”, “Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)”);  // here, the user-agent is ‘Yahoo Slurp’
WebDriver driver = new FirefoxDriver(myprofile);

Google Chrome

1| Install the Chrome Add-on, User Agent Switcher
2| Go to chrome://extensions/
3| Click ‘Options’ under User-Agent Switcher for Chrome
4| Get the desired ser agent string. e.g., iPhone 4
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5

System.setProperty(“webdriver.chrome.driver”,”C:\\chromedriver.exe”);
ChromeOptions options = new ChromeOptions();
options.addArguments(“user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data”);  
options.addArguments(“–user-agent=Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5”);//iPhone 4
options.addArguments(“–start-maximized”);
driver = new ChromeDriver(options);

INTERNET EXPLORER OPTIONS : SELENIUM

Posted on Updated on

 

 
org.openqa.selenium.ie.InternetExplorerDriver

Capabilities [{platform=WINDOWS, elementScrollBehavior=0, javascriptEnabled=true, enablePersistentHover=true, ignoreZoomSetting=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=9, cssSelectorsEnabled=true, ignoreProtectedModeSettings=false, allowAsynchronousJavaScript=true, requireWindowFocus=false, handlesAlerts=true, initialBrowserUrl=, nativeEvents=true, takesScreenshot=true}]
 
InternetExplorerOptions options = new InternetExplorerOptions
                                                  {
                                                      IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                                                      UnexpectedAlertBehavior =InternetExplorerUnexpectedAlertBehavior.Ignore,
                                                      IgnoreZoomLevel = true,
                                                      EnableNativeEvents = true,
                                                      RequireWindowFocus = true,
                                                      EnablePersistentHover = true,
                                                      ElementScrollBehavior =InternetExplorerElementScrollBehavior.Top,
                                                      BrowserAttachTimeout = TimeSpan.FromSeconds(timeOut),
                                                  };
 IWebDriver webDriver = new InternetExplorerDriver(ieDriverPath, options,TimeSpan.FromMinutes(20));
 
Properties Description
 
Name
Description
ElementScrollBehavior
Gets or sets the value for describing how elements are scrolled into view in the IE driver. Defaults to scrolling the element to the top of the viewport.
EnableNativeEvents
Gets or sets a value indicating whether to use native events in interacting with elements.
EnablePersistentHover
Gets or sets a value indicating whether to enable persistently sending WM_MOUSEMOVE messages to the IE window during a mouse hover.
IgnoreZoomLevel
Gets or sets a value indicating whether to ignore the zoom level of Internet Explorer .
InitialBrowserUrl
Gets or sets the initial URL displayed when IE is launched. If not set, the browser launches with the internal startup page for the WebDriver server.
IntroduceInstabilityByIgnoringProtectedModeSettings
Gets or sets a value indicating whether to ignore the settings of the Internet Explorer Protected Mode.
RequireWindowFocus
Gets or sets a value indicating whether to require the browser window to have focus before interacting with elements.
UnexpectedAlertBehavior
Gets or sets the value for describing how unexpected alerts are to be handled in the IE driver. Defaults to Default.