Saturday, 27 April 2013


Object Identification In Selenium


Element Locators tell Selenium which HTML element a command refers to.

Identifiers
Syntax1
Syntax2
Comments
id
id =id
id
Select the element with the specified @id attribute
name
name=username
username
Select the first element with the specified @name attribute
dom
dom=document.images[1]
Find an element using JavaScript traversal of the HTML DOM
xpath
xpath=//img[@alt='do]
//img[0]
Locate an element using an XPath expression
link
link=The link text
Select the link (anchor) element which contains text matching.
CSS
css=a[href="#id3"]
Select the element using css selectors

Eclipse configuration for Selenium RC


Steps:
1. Create  your java project in eclipse
    -> Launch Eclipse
                -> Creat a java project named TestProject (for example)
2. Add Junit Library to your project
  ->  Go to Project Properties(Right Click on Project and click on Properties)
  ->  Go to Java Build Path
  ->  Click on Libraries tab
  ->  Click on 'Add Library' button
  ->  Select 'Junit' option from list and click on next
  ->  Select version 'Junit4' from drop down and click on finish.
3. Add required  Jar files into Project:
                ->  Go to Project Properties
                 ->  Go to Java Build Path
                 ->  Click on Libraries tab
                ->  Click on 'Add External Jars'  button
                ->  Browse for “selenium-java-client-driver.jar” and “selenium-server.jar”
4. Add your test (Java class )  in our Project
                ->  In eclipse go to create a new java class
->  Create it with name MyFirstTestCase (for example) and paste the code from file( record the application and convert to junit4 from selenium IDE)
                ->  Choose "com.thoughtworks.selenium.SeleneseTestCase" as its super class
 ->  Finish it
5. Add Steps to start selenium server
Write below line at the start of setUp() method.
SeleniumServer sServer = new SeleniumServer();
sServer.start();

Note :- write below line at the start of this test( next to package, if package exist)
            import org.openqa.selenium.server.SeleniumServer;
6. Change the browser name in  DefaultSelenium() method
            exp:- write *iexplore for internet explorer

7.Run the test
     
      Right click on project and choose run as junit

Commonly used Selenium Commands


1.     Action Commands
                                        Open(Locator) – This Command will open the specified
                                        click(Locator) – This Command will Click at specified target
                                        check(Locator) – Toggles the checked value of a checkbox
                                        type(Locator, value) –Sends text input to an element
                                        select (Locator, value)– This will select the specified item in a list
Note: most action commands in Selenium IDE also have a duplicate command with the AndWait suffix.   When these are used the action is performed and a page load is expected and the command will not complete until the page has loaded or the timeout is reached.
2.     Store, Check, and Wait
·         store(expression, variableName) – Allows you to temporarily store a value
·         verify(pattern) – performs verification and skip execution, if fails.
·         assert(pattern)  – performs verification and stop execution, if fails.
·         waitFor(pattern)   – Waits until the value matches the specified value or the timeout.
Note: These Commands are heart of Selenium ,as these deal with verifiacation and validation part.

3.     Triggering Events

·         mouseDown / mouseUp(locator) – This simulates clicking the left mouse button.
·         keyDown / keyUp(locator, keySequence) – Simulate the user pressing a key or releasing a key.
·         fireEvent(locator, eventName) – If all else fails you can fire the JavaScript event directly.

 

Note:  When using the type and click commands, you might find that certain JavaScript events aren’t firing. For this reason there are several alternative commands that may help. Some of these are listed above.


Whats Selenium?

As we all know everything is automated nowadays you name it and you get it. Similar is the way we do testing of applications. We have got many softwares that can do the automation work for you. Just Record it and Play it and your automation of a use case is done.
One of the famous automation tool in industry is Selenium. Its an Open Source Functional Testing tool.
Selenium provides mainly three types of tools that you can use for automation.
1.
Selenium IDE - is a Firefox add-on that records clicks, typing, and other actions to make a test, which you can play back in the browser.
2.
Selenium RC - runs your tests in multiple browsers and platforms. Tweak your tests in your preferred language.
3.
Selenium Grid - extends Selenium RC to distribute your tests across multiple servers, saving your time by running tests in parallel.Selenium IDE
It is an integrated development environment for Selenium tests. It is implemented as a Firefox extension, and allows you to record, edit, and debug tests. Selenium IDE includes the entire Selenium Core, allowing you to easily and quickly record and play back tests in the actual environment that they will run.
Selenium IDE is not only recording tool: it is a complete IDE. You can choose to use its recording capability, or you may edit your scripts by hand. With autocomplete support and the ability to move commands around quickly, Selenium IDE is the ideal environment for creating Selenium tests no matter what style of tests you prefer.
Selenium RC
It 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.
Selenium RC comes in two parts.
1.A server which automatically launches and kills browsers, and acts as a HTTP proxy for web requests from them.
2.Client libraries for your favorite computer language.
The RC server also bundles Selenium Core, and automatically loads it into the browser.
Selenium Remote Control is great for testing complex AJAX-based web user interfaces under a Continuous Integration system. It is also an ideal solution for users of Selenium Core or Selenium IDE who want to write tests in a more expressive programming language.
Selenium Grid
Selenium RC can only execute your programs in a single type of environment and limited to a single machine. Selenium Grid gives you the power to execute multiple tests in parallel and also onto some remote machines hence saving the time for the test execution.

In my coming posts I will describe in detail how to use Selenium for automation.

Useful Functions and Notes while writing cases in Selenium RC

Useful Functions of Selenium
You have a huge list of selenium functions that we can use for writing test cases. Some of the main functions are:
isElementPresent(location) – Returns true or false based on whether “location” of the element passed is present on the page or not. Verifies that the specified element is somewhere on the page. This function can be used while you are working on an Ajax based system or in a system where you need to identify whether the element is present before we execute any action on the said "location". It is good to check if the location is present or not if your test case include clicking on some link or page refresh and then taking some action.
getValue(location)- Returns the data stored in the said “location” of the element that is passed to the function. Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter). For checkbox/radio elements, the value will be "on" or "off" depending on whether the element is checked or not.This function is useful when you need to get some data from some field or a particular location and need to use it in you program or testcase.
isTextPresent(text)Returns true or false based on the specified text pattern appears somewhere on the rendered page shown to the user.Used to verify the whether a text present on the page or not.
click(location) - Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), call "waitForPageToLoad" function.
waitForPageToLoad(timeout) - Waits for a new page to load. Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded" flag when it first notices a page load. Running any other Selenium command after turns the flag to false. Hence, if you want to wait for a page to load, you must wait immediately after a Selenium command that caused a page-load.
type(locator,value) - Sets the value of an input field, as though you typed it in.
select(locator,option locator) - Select an option from a drop-down using an option locator. Using to select values from combo boxes.

Useful things while writing cases in Selenium
  1. While testing any Ajax based application use “waitForElementPresent” or “isElementPresent” before trying to do any action over the element.
  2. While writing your own case always remember to extend the “SeleneseTestCase” class.This create a “selenium” object and stores the browser session onto the created object.
  3. To set the browser on which you need to do execution of your test case add the following function to your test case class
public void setUp() throws Exception {
setUp(URL,browser name);
}
List of browsers that can used is “*firefox” -for firefox, “*iexplore” -for IE, “*safari” - for Safari, “*opera” - For Opera.This need to be placed in place of "browser name" while calling the "setUp" function.
  1. If you are internally going to call another function from your test case and going to execute some actions under it. Don't forget to pass the “selenium” object to the function otherwise your test case will fail. This happens because when you are executing a case ,the browser session details is stored with the “selenium” object and if you call a function without passing the selenium object to the function it wont be having any session details with it and hence the case will Fail.


Ant script for generating a Junit report for Selenium Test execution

We know the advantages of using Selenium RC. But Selenium RC by default does not provide us with any reports for the test execution done through it. We need to explicitly implement a reporting framework for test reporting in RC. For implementing a Reporting framework you can write your own custom code or can use an already existing reporting framework available.
There are mainly two reporting framework available for Selenium RC they are Junit and Test-NG. There are two more frameworks Report-NG and testng-xslt but they are implemented over the Test-NG framework.
In this blog I will mention about generating a Junit Report for your Selenium RC test execution using Ant script. I had written a “build.xml” for Ant for executing Selenium cases and generating a Junit report for the said selenium execution. I will be discussing about the same in this blog. If someone doesn’t have an idea about Ant can follow my steps and can generate a Junit report for Selenium Execution.

Explaining the “build.xml”
  1. In Build.xml I am mainly defining 5 properties
RELEASE_ROOT this has been set to the Java Project folder.
SRC which defines the source folder of the project
LIB which defines the lib folder of the project
BIN which defines the binary folder where the classes needs to be pasted after compiling
REPORT folder which defines the report folder where the test execution reports will be generated.
  1. There are 4 targets or tasks of ant inside the build.xml
“init’ which deletes the binary folder and creates it again.
“compile” which depends upon the “init” task and which compiles the java files under the source folder and paste the classes onto the binary folder.
“run-single-test” which depends on “compile” and runs only a single Selenium Junit test mentioned in it. This task also generates a Junit html report under the report/html folder of Java project after Selenium Test execution is done.
“run-batch-test” which depends on “compile” and runs multiple Selenium Junit test mentioned in it. This task also generates a Junit html report under the report/html folder of Java project after Selenium Test execution is done.
  1. In each of the compile, run-single-test and run-batch-test I am setting the classpath of the binary folder, the library folder and the source folder in case of “run-batch-test”.
  2. In targets “run-single-test” and “run-batch-test” I am using the “junit” task of test execution. This task provides two types of execution
Single class execution which I had used in “run-single-test” target. There is a subtask “test” of “junit” that can used for single test class execution. It is written as follows:

<test name="test.TestClass" haltonfailure="no" todir="${REPORT}/xml" outfile="TEST-result">
<formatter type="xml" />
</test>

Here “name” is the test class name. “todir” is the directory where initial xml report needs to be generated. “outfile” is the xml file name for initial result xml file. “formatter” is the initial file format type.

Batch test class execution which I had used in “run-batch-test” target. There is a subtask “batchtest” of “junit” that can used for single test class execution. It is written as follows:

<formatter type="xml" usefile="true" />
<batchtest fork="yes" todir="${REPORT}/xml">
<fileset dir="${SRC}">
<include name="**/Test*.java" />
</fileset>
</batchtest>

Here I am telling the “batchtest” what all test classes to include using the “fileset” and “include” task. Along with this if you want you can use the “exclude” task to exclude particular type of classes. In the following example the Junit will include all the test class starting from “Test” and exclude all the test class having “Base” word in their name.

<formatter type="xml" usefile="true" />
<batchtest fork="yes" todir="${REPORT}/xml">
<fileset dir="${SRC}">
<include name="**/Test*.java" />
<exclude name="**/*Base*.java" />
</fileset>
</batchtest>

5. For generating the test report I am using the “junitreport” task of ant. It takes all the xml file from the “report/xml” and generates an html report at “report/html”.

Setting up a Java Project for test execution using Ant.

In this I am just telling how to setup a basic java project for using the build.xml file attached with this blog and running the selenium test using Ant.

Preconditions:
1. Install Ant from apache.
2. Install Java JDK (not JRE) and add its bin folder to your “PATH” environment variable of your system. For checking JDK is mapped check whether "javac" is recognized in your system by typing "javac" in your command prompt.
3. Download the Selenium RC.
4. Test cases are already converted to Selenium Junit cases.

Steps:
  1. Create a Java project in your Java IDE. I am using Eclipse so I will refer to it.
  2. By default there will be the “src” folder inside your Java Project. Right click on the “src” folder and create a new package under it say”test”.
  3. Now copy your Selenium Junit classes to this new “test” package.
  4. Create a new folder called “lib” under your Java Project.
  5. Copy selenium-java-client-driver.jar, junit-4.5.jar(if you have another version of Junit 4 you can use that) and ant-junit.jar(can be found under the “lib” folder of your ant installation) to your “lib” folder of Java Project.
  6. Now create a folder called “build” under your Java Project and copy the “build.xml” file attached with this blog to the build folder you created.
  7. Now open the build.xml file for edit.
  8. Search for “run-single-test” in build.xml. Go to the “<test” under the “run-single-test” target .Replace the values for “name=” variable with your Selenium Junit class name. For ex if your class name is TestSelenium.java and it is under package “test” under “src” then replace the value with “test.TestSelenium” then save the build.xml file.
  9. Now start the Selenium RC server.
  10. Now go to the build folder of the Java Project using command prompt and run the command “ant run-single-test”
  11. It should execute your Selenium cases on selenium server and generate an html report onto the “report/html” folder of your Java project.

Similarly you can modify the “run-batch-test” target of build.xml and execute multiple Selenium Tests together.
Download build.xml from Here

Comparing and re-sizing images using Selenium

While automating a web application some of us have to deal with the test to check that an image has been successfully uploaded or not.And that the uploaded image matches with the actual one or not. To automate this test, there are certain things that we need to achieve:

  1. Saving the image that has been uploaded for comparison with the original image.
  2. Handling the re-sizing and re-formatting of the image by the web application itself.
  3. Logic to compare images.

1. Saving the image.
Selenium does not support any direct way to actually store/get an image. But there are other ways like "right-click" and "Save as" option using which you can save the image on firefox and chrome. Once you get an image you can move further with the second step that is checking size of the image.

2. Handling the re-sizing and re-formatting of the image by the web application itself.
Whenever we upload an Image to a web-app it internally re-size and re-format the image while storing or rendering to save space and improve performance. So if you save an uploaded image from your web-app  and want to compare it with the original image, it will fail. The reason being the image that you had downloaded from the web-app has been modified and may not match with the original image in terms of format, size and clarity. The solution to it can be achieved by getting the logic from the development team for re-sizing or re-formatting of image that they use inside their code. You can use then use the same code in you automation test to re-size and re-format your original image and then compare it with the downloaded image to check whether both matches or not.
Following code will give you a general idea on how to re-size an image.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public BufferedImage resize(BufferedImage img, int newW, int newH) {
//Getting the width and height of the given image. 
int w = img.getWidth();
  int h = img.getHeight();
//Creating a new image object with the new width and height and with the old image type
  BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
  Graphics2D g = dimg.createGraphics();
  g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
//Creating a graphics image for the new Image.
  g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
  g.dispose();
  return dimg;
 }

3. Logic to compare images.
Once you had completed the above two steps you can go ahead with comparison of the images.
Following is a  java code using which you can actually match two images pixel by pixel.


?
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
public void compareImage() {
  boolean ret = true;
  try {
   original = ImageIO.read(new File(
     "originalFile"));
   copy = ImageIO.read(new File("copyFile"));
   ras1 = original.getData();
   ras2 = copy.getData();
//Comparing the the two images for number of bands,width & height.
   if (ras1.getNumBands() != ras2.getNumBands()
     || ras1.getWidth() != ras2.getWidth()
     || ras1.getHeight() != ras2.getHeight()) {
      ret=false;
   }else{
   // Once the band ,width & height matches, comparing the images.
   search: for (int i = 0; i < ras1.getNumBands(); ++i) {
    for (int x = 0; x < ras1.getWidth(); ++x) {
     for (int y = 0; y < ras1.getHeight(); ++y) {
      if (ras1.getSample(x, y, i) != ras2.getSample(x, y, i)) {
     // If one of the result is false setting the result as false and breaking the loop.
       ret = false;
       break search;
      }
     }
    }
   }
   }
   if (ret == true) {
    System.out.println("Image matches");
   } else {
    System.out.println("Image does not matches");
   }
  } catch (IOException e) {
   System.out.println(e);
  }
 }

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...