Wednesday, November 3, 2010

Cucumber Automation


What is Cucumber actually?

  • Behavior driven development testing tool.
  • Bunch of behaviors in the form of scenarios.
  • Written mainly by non-technical people
  • Written in plain English.

What should you do actually?

  • Write a behavior in the form of scenarios in a feature files.
  • Write the code in order to satisfy the scenario.
  • Run the feature file.
  • Watch it fail
  • Write the automation scripts with the template provided by the cucumber.
  • The behavior of the application is satisfied by the test script.

Cucumber Installation on Windows Platform:

 1. Ruby Installation.

·        First, go to Ruby site and download the latest version of Ruby installer. Click on Rube installer exe file and then install the ruby.

·        Set up the classpath for Ruby by adding home directory path of the ruby into the Classpath variable.

·        Setup the Path system variable for Ruby by add the path string of the ruby bin dir into the path system variable.

·        Make sure ruby installed properly by open the command prompt and type the command ‘gem update --system’.
Note: More details about Ruby http://www.sapphiresteel.com/IMG/pdf/LittleBookOfRuby.pdf

2. Install Cucumber:

·        Make sure Ruby installed properly by doing the steps of the Ruby installation.
·        Open command prompt and execute the command “gem install cucumber win32console” and wait for some time for installation.
·        Once installation is done and make sure cucumber installed or not by the command “cucumber --version”.
3. Install Rspec gem:
·        RSpec Cucumber is an engine that lets you map English statements (or any language actually) to executable code in order to validate software specifications written as scenarios with the code written to fulfill them.
·        Install Rspec by the command “gem install rspec”

4. Install watir gem:
·        Watir is an open-source family of Ruby libraries for automating web browsers. It allows you to write tests that are easy to read and maintain. It is simple and flexible.
·        Install watir by the command “gem install watir”

Demo Project:

Demo in windows platform (Please refer “Cucumber Installation on Windows Platform” section for installations before starting the project).

Let’s consider the test case, search some word in Google search home page).

1. First, create a sample project (i.e. create any directory) and then create a sub directory “features’.

2. Create a feature file with extension ‘.feature’ inside the features directory.

3. Copy the below info into the feature file.

Feature: Google Search
In order to find out more about cucumber benefits
I need to able to search Google

Scenario: Google Search for cucumber benefits
Given that I am on the Google Homepage
When I search for cucumber benefits
Then I should see "Cucumber Benefits for Great Skin and Eyes"

Let’s consider the sample project dir structure as below

4. Now go to command prompt, run the command “cucumber features” as below
 

It will generate the template of the step definitions (blue text in screen shot)) for the above scenario

5. Now create a ‘step_definitions’ directory inside of the features directory and then create a ruby file and then copy the step definitions template.

6. Now, implement the logic for the step definitions by using Ruby, Watir Driver scripts.

Please find below the sample step-definitions file.


7. Finally, execute the features in command prompt as above.

Monday, November 1, 2010

Selenium with CSS locators.

XPath locator is one of the most quirky and one of the most precise locator. This disadvantage is clearly seen while running the tests under IE while Firefox works with xpath pretty well. This problem is related to internal browser features in particular to the libraries being used for elements location definition. But this is another story. The main thing is that tests which intensively use XPath work extremely slow under IE and this feature is the cause of huge variety of problems related to execution speed as well as quality of the tests itself especially during operations with dynamic content. For this reason CSS locators can be good alternative of XPath.
What can we do with CSS locators?

First of all,
CSS locators also give the ability to describe object hierarchy. For instance, the XPath locator like:
Xpath=//div//span/a

can be described via
CSS in the following way:
css=div * span > a

From the sample above we may see analogy for XPath and
CSS namely:
a) Character "/"  meaning next level of
DOM hierarchy corresponds to CSS operator ">".
b) Character "//" meaning any object hierarchy level under current object corresponds to
CSS operator "*".

Secondly, just like XPath, the
CSS locators can locate object by thier attribute values. For example the locator like:
Xpath=//div[@id="some_id"]

can be described via
CSS in the following way:
css=div[id=some_id]

Also there\'s abitity to check for partial attribute value matching. But
CSS locators are a little bit limited in this area. There\'s ability to verify that attribute value consists of several space-separated words but one word equals to some value. It means that the XPath locator like:
xpath=//div[contains(@title,"title")]

can be expressed via
CSS like:
css=div[@title~=title]

Both the locators can detect the element like 

<div title="some multiword title" />  while the element like  <div title="my_title" />
  
can\'t be detected by CSS locator from above.

Also
CSS has simplified form for some attributes. For instance, the element having the id attribute like  <div id=some_id /> can be located by the following CSS:
css=div#some_id

In addition to that
CSS locators have specific way to define the object by the class attribute. The XPath locator like:
xpath=//div[@class="myclass"]

has the following
CSS analog:
css=div.myclass

Such features make
CSS suitable in some cases.

 More details about CSS can be found by the forllowing URL: http://www.w3.org/TR/CSS2/selector.html

So, in some cases CSS locators are the analogs of XPath locators with one serious advantage: CSS works fast no matter what the browser we use.

Of course,
CSS locators have their own limitations like: problems to locate objects by index, problem to locate objects higher in the object hierarchy or so.

Tuesday, October 12, 2010

Selenium-RC setup

Selenium-RC automation Setup:

 Follow the below steps for setup the RC project.
 1.Install Java
2.Install any java IDE ( Eclipse or any IDE)
3.Download RC from SeleniumHQ downloads page
4.Start any java IDE (eclipse or any IDE)
5.Create new project
6.Add to your project classpath selenium-java-client-driver.jar
7.Record your test from Selenium-IDE and translate it to java code (Selenium IDE has automatic translation feature to generate tests in variety of languages)
8.Run selenium server from console
9.Run your test in the IDE

Selenium automation problems

Handling Ajax events:

If you want to automate an UI which is having some UI elements are behaving based on ajax events.
Suppose there is an UI element (text field),when you type some text on the field  that will invoke some ajax call for hitting the server and get some info from server and showing on the screen.
Now problem is when you use the type command in selenium ,it wont call the ajax events.You need to call
ajax events after type the text into the text field.

Selenium is providing the following commands for automate the ajax events.

Selenium.type(xpath of element,some text); // this will do the type the text ,but it wont invokes the ajax events
Selenium.fireEvent(xpath of element,"blur"); //this will do the ajax calls.

Verify vertical scrollbar appears for the text-area element:

Selenium is not providing any command to checking the appearance of the vertical scrollbar.
We need to findout by using java script and need to invoke the script by the selenium.
Selenium API is providing the command for executing the java script.

Use below script when you know only the classname for the text-area.

Selenium.type(xpath of the text-area element,text value);
String str1=Selenium.getEval("this.browserbot.getCurrentWindow().document.getElementsByClassName('cssclassname')[0].clientHeight");
String str = Selenium.getEval("this.browserbot.getCurrentWindow().document.getElementsByClassName('cssclassname')[0].scrollHeight");
int clientHeight = Integer.parseInt(str1);
int scrollHeight = Integer.parseInt(str);

if(clientHeight < scrollHeight){
System.out.println("Vertical scrollbar appears");
}else{
System.out.println("Vertical scrollbar is not appear");
}

Note: If you know the Id or Name of the text-area field then
use getElementById() or getElementByName() instead of the getElementByClassName method.

I'm unable to upload a file using selenium core; when I try to type in the file upload text field, nothing happens!

There seems to be two inter-related problems:

1 – Unfortunately, this is yet another JavaScript security restriction; JS is not allowed to modify the value of input type=”file” form fields. You can work around this by running your tests under Selenium IDE or under Selenium RC running in the experimental “*chrome” mode for Firefox, but at present there is no straight forward way to do this in Selenium Core.

2 – Handling of the “Choose File” dialog box with Selenium alone is not possible. We need to have another program running to select the path and file from the “Choose File” dialog box.

So, How can we upload files?
Fortunately, there exists a workaround to the above problems. This is where the magic of AutoIt and Selenium combination can work wonders!

First we will write a simple script in AutoIt and save the file as an executable: (please read documentation on AutoIt website to learn how to save the scripts as an executable file)


1    WinWaitActive("Choose file")
2    Send("C:\attach\samplefile.txt") \\location of the file you want to attach to the form and submit
3    Send("{ENTER}")

We shall name the above file as attachFile.exe

Now, within a Java code, we can run a process which will execute the above program just before when we want to upload and submit a file.

01    package com.company;
02   
03    import java.io.IOException;
04    import com.thoughtworks.selenium.Selenium;
05   
06    public class AddAttachment {
07       public static void attach(Selenium selenium, String fileName) {
08          try {
09             String[] commands = new String[]{};
10             commands = new String[]{"c:\\test\\attachFile.exe"}; //location of the autoit executable
11             Runtime.getRuntime().exec(commands);
12          } catch (IOException e) {}
13   
14          //autoit executable is now waiting for a "Choose file" dialog to popup
15          selenium.click("name=browseButton");
16          //once the "Choose file" dialog is opened, the autoit will input the path and file name
17       }
18    }

The above seems to be the easiest way to deal with file uploads and attachments using Selenium.

Note: Use AutoIt for the things which are not automated by the selenium-core like handling browser certification,authentication popups etc.

How to start selenium server using Java code

When test automating a web application using Selenium, we have to start the Selenium server first, so that a new Selenium session is created to talk to the web browser. This can be either done manually, i.e user running a command line to start the Selenium server, or to get the pure automation effect of Selenium, it is best to start the Selenium server via a program code.

01    package com.company;
02    import org.openqa.selenium.server.RemoteControlConfiguration;
03    import org.openqa.selenium.server.SeleniumServer;
04    import com.thoughtworks.selenium.Selenium;
05    import java.net.BindException;
06    import java.net.ServerSocket;
07   
08    public class Server {
09        public static SeleniumServer server;
10        public static void startSeleniumServer() throws Exception {
11   
12           try {
13            ServerSocket serverSocket = new ServerSocket(RemoteControlConfiguration.DEFAULT_PORT);
14            serverSocket.close();
15                    //Server not up, start it
16                    try {
17                     RemoteControlConfiguration rcc = new RemoteControlConfiguration();
18                     rcc.setPort(RemoteControlConfiguration.DEFAULT_PORT);
19                     server = new SeleniumServer(false, rcc);
20   
21                    } catch (Exception e) {
22                        System.err.println("Could not create Selenium Server because of: "
23                                + e.getMessage());
24                        e.printStackTrace();
25                    }
26                    try {
27                        server.start();
28                        System.out.println("Server started");
29                    } catch (Exception e) {
30                        System.err.println("Could not start Selenium Server because of: "
31                                + e.getMessage());
32                        e.printStackTrace();
33                    }
34                } catch (BindException e) {
35                    System.out.println("Selenium server already up, will reuse...");
36                }
37        }
38   
39        public static void stopSeleniumServer(Selenium selenium){
40            selenium.stop();
41            if (server != null)
42              {
43                 try
44                 {
45                     selenium.shutDownSeleniumServer();
46                     server.stop();
47   
48                    server = null;
49                 }
50                 catch (Exception e)
51                 {
52                    e.printStackTrace();
53                 }
54              }
55        }
56   
57    }

Selenium Failed to start new browser in iexplore mode when starting/stoping the server dynamically by the code in IE.

I'm unable to run my scripts with IE using iexplore mode when starting the server using java code(dynamically) and I'm getting below error

java.lang.RuntimeException: Could not start Selenium session: Failed to start new browser session: Error while launching browser
    at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:89)
    at com.aol.patch.util.SeleniumBase.openBrowser(SeleniumBase.java:91)
    at com.aol.patch.tests.CommonTest.testEnter(CommonTest.java:28)
Caused by: com.thoughtworks.selenium.SeleniumException: Failed to start new browser session: Error while launching browser
    at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97)
    at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91)
    at com.thoughtworks.selenium.HttpCommandProcessor.getString(HttpCommandProcessor.java:262)
    at com.thoughtworks.selenium.HttpCommandProcessor.start(HttpCommandProcessor.java:223)
    at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:81)
   
Here the problem is selenium is trying to start in iehta mode eventhough  specified that start in a iexplore mode.


After doing some quick search, I found that there is work around to start a selenium in iehta mode.

The only way to get the original iexplore is to change the browser mode to "*iexploreproxy" or "piiexplore".

So, I changed my config file to start selenium using "*iexploreproxy" instead of "*iexplore" and  working fine with IE.
I hope this can be helpful.

What is Selenium?

Selenium is a suite of tools used to automate web application testing across many platforms. It is an open source tool developed in Java Script and browser technologies and hence supports all the major browsers on all the platforms. It was developed by ThoughtWorks Inc.
  • Web testing tool.
  • Javascript based.
  • Supports the multiple languages for writting the client script.
  • Supports multiple Operating systems.
  • Supports multiple browsers
  • Execute the testcases parallely(in Grid fashion)
Selenium Components

1) Selenium Core:

This is the original JavaScript-based testing system. It is now used primarily as a component of Selenium Remote Control, but it can also be used as a pure JavaScript/HTML testing system. To run Selenium Core tests, they normally have to be installed on the server on which you want to test.

2) Selenium IDE:

Selenium IDE is an integrated development environment for Selenium tests. It is implemented as a Firefox (2+) extension, and allows you to record, edit, and debug tests.

Features:

    * Easy record and playback
    * Intelligent field selection using IDs, names, or Xpath, as needed
    * Autocomplete for all common Selenium commands
    * Walk through tests
    * Debug and set breakpoints
    * Save tests as HTML, Ruby scripts, or any other format
    * Support for Selenium user-extensions.js file
    * Option to automatically assert the title of every page

Drawbacks:

    * The biggest drawback of Selenium IDE is its limitation in terms of browser support. Though Selenium scripts can be used for most of the browsers and operating systems, scripts written using Selenium IDE can be used for only the Firefox browser if it is not used with Selenium RC or Selenium Core.
    * Selenese, the simple scripting language used by IDE, is somewhat primitive as it has no conditionals (no “if” statements), and no loops (no “for” statements).
    * Does not help with the launching and closing of the browser

Note: Selenium IDE can be configured to repeat a specific test by using flowControl extensions: goto, While, and so on, by installing the selenium-goto extension (download it from http://wiki.openqa.org/pages/viewpageattachments.action?pageId=379). To install it, open the Options panel in the Selenium IDE browser extension and specify the location of the user-extension.js file.


3) Selenium Remote Control:

Selenium Remote Control (RC) is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser. The RC server also bundles Selenium Core, and automatically loads it into the browser.

Selenium RC comes in two parts:

a) A server, which automatically launches and kills browsers, and acts as a HTTP proxy for web requests from them.

b) Client libraries for your favorite computer language (Java, .NET, Perl, Python, C#, PHP and Ruby).

Click on selenium for a simplified architectural representation.

As a test suite starts, the following happens

    * The client/driver reaches out to the Selenium-Server.
    * The Selenium-Server launches a browser (or reuses an old one) with a URL that will load the Selenium core web page.
    * The Selenium-Core gets the first instruction from the client/driver (via the HTTP Proxy built into the Selenium RC Server).
    * The Selenium-Core acts on that first instruction, typically opening a page of the AUT.
    * The web server is asked for that page, and it renders it in the frame/window reserved for it.

4) Selenium Grid:

Selenium Grid runs tests on many servers at the same time, cutting down on the time it takes to test multiple browsers or operating systems.

Installation:

   1. Selenium IDE:
          * Selenium IDE can be downloaded from http://seleniumhq.org/download/.
          * Open Mozilla Firefox.
          * Drag and drop the file into it.
          * Install it and restart Firefox
          * If installed properly, Selenium can be accessed from Tool –> Selenium IDE in your browser toolbar.
   2. Selenium RC:
          * Selenium RC can be downloaded from http://seleniumhq.org/download/.
          * Unzip the file and extract it in the directory of your choice.
          * JRE 1.5 or higher version should be installed on your machine. To check the version, type the following command at the dos prompt: java -version.