There was an error in this gadget

Technical Project Lead @ Huawei Technologies

My photo
Bangalore/Hyderabad, Karnataka/Andhra Pradesh, India
Have an overall 10 + yrs of experience Currently working as an Senior Architect.Expertise in design,implementation of Automation frameworks for Opensource automation tools like Selenium,Jmeter, Webdriver,Appium, Robotium Expertise in integrating Test & ALM Management tools like Rally,Qmetry,JIRA-Zephyr with Automation frameworks Expertise in design and developmenet Mobile Automation frameworks for tools like Appium, Robotium Remote Control,Cucumber BDD

Followers

Saturday, September 18, 2010

Starting Selenium Server on a specific port

java -jar selenium-server.jar -port 4445

Programatically Starting Selenium Server to accept SSL Certificates

  public static void startServerInProxymode(){
        // Precondition for the entire test class is Login
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(RemoteControlConfiguration.DEFAULT_PORT);
            serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Failed to create socket connection on Default PORT");
            e.printStackTrace();
        }
       
        RemoteControlConfiguration rcc = new RemoteControlConfiguration();
        rcc.setTrustAllSSLCertificates(true);
        rcc.setPort(RemoteControlConfiguration.DEFAULT_PORT);
        try {
            server = new SeleniumServer(false,rcc);
            server.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }

Wednesday, September 15, 2010

Generating Junit HTML Reports using Maven


To Generate HTML reports using maven follow the below steps
1.Firstly we have to create a Maven Project using eclipse
2.Inorder to create a Maven Project in eclipse your eclipse should have maven plugin
3.To Download maven pulgin see below steps
4 . Open Eclipse and go to Help. Select Install New Software


5.Click on add button. Now addsite dialog gets opened.
6.Provide the Name and Location and then click on ok button as shown in below snapshot



6. Wait for few seconds until the maven plugin is displayed in the list (refer below snap shot)
7. Select the checkbox option "Maven Integration for Eclipse" and click on Next Button
8. Select the plug in and click on Next Button as shown below





9. Accept the license agreement and click on Finish Button





10.The download and installation happens in background as shown below 
11.On Successful installation you would be prompted for eclipse restart. Accept the restart confirmation to restart your eclipse
12. Your eclipse is now plugged in with Maven plugin with which you can create Maven Projects
13. Ignore the console messages where eclipse tries to download maven plugins
14. Maven will create a .m2 (maven directory) folder in user directory where all the dependencies (jars are saved)
15. Go to user directory ex: C:\Documents and Settings\kiran\.m2.
16. Under .m2 directory you should see repository folder







17. Now your Eclipse is ready to create Maven Project
18. From here we will see creating Maven Projects in eclipse
19. In Eclipse navigate to File >> New Project >> Maven >> Maven Project
20. Click on Next again Next and wait for a while until the Group Ids are populated 
21. Select the default Group ID as shown in below fig and click on next

22. Provide groupid, artifactid and package as shown in below figure and click on Finish button



23. Now in you eclipse you should be able to see the Project in you eclipse package explorer



24. This project will have 2 src folders namely src/main/java for writing your AUT code and src/main/test for maintaining you Junit Tests
25 . Also you can see Maven Dependencies and a pom.xml
26. You Pom.xml is used to specify the required dependencies for your project (ex: selenium,junit ....)
27. By Default, Pom.xml will have a dependency of Junit 3.8.2 version. Change the version from 3.8.2 to Junit 4.0 and save the pom.xml. Now observe that you Maven dependencies will be updated to Junit 4 jar. So what ever dependencies you wish, you can provide the dependency in pom.xml. Maven will download the specified dependency from central repository and saves them in local repository C:\Documents and Settings\kiran\.m2\repository


  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

28. From here we will create some Selenium Tests. So In your eclipse, under src/main/test directory, com.company package, create a Junit test class with name GoogleSearchTest.java. Delete or the default AppTest.java

package com.company;

import org.junit.AfterClass;
import org.junit.BeforeClass;

public class GoogleSearchTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }   


}

 

29. Now add some testcases to the above testClass . We will add two test methods(testcases) namely testGoogleSearch()  and testGoogleAdvancedSeach(). Your test class looks like this


 package com.company;

import org.junit.AfterClass;
import org.junit.BeforeClass;

public class GoogleSearchTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }


    @Test
    public void testGoogleSearch(){
       
       //To implement Selenium Tests here
    }
   
    @Test
    public goid testGoogleAdvancedSearch(){
     
      //To implement Selenium Tests here
    }
}
Note** : Maven requires JDK1.5 and above . Configure eclipse with JDK 1.5 conpliance


30. Now we have to implement selenium tests in the two testmethods. For that we require Selenium RC Jars.
31. Open the pom.xml and ad the following dependency to Dependencies tag <dependencies></dependencies>
add the below dependency tag to your dependencies tag


<dependencies>
<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-remote-control</artifactId>
        <version>1.0.1</version>
        <type>pom</type>
    </dependency>

 <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.5</version>
        <type>maven-plugin</type>
    </dependency>

</dependencies>

32 . also add plug in for html report generation


 <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <outputName>RadaptiveTestResults</outputName>
          <includes>
            <include>SmokeTest.java</include>
          </includes>                
        </configuration>
      </plugin>
    </plugins>
  </reporting> 
   



33. On a whole your pom.xml should look like this (replace your pom.xml content with below xml content)


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

   <groupId>com.company</groupId>
  <artifactId>MyMavenProject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MyMavenProject</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.5</version>
      <scope>test</scope>
    </dependency>   
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-remote-control</artifactId>
        <version>1.0.1</version>
        <type>pom</type>
    </dependency>   
    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.5</version>
        <type>maven-plugin</type>
    </dependency> 
 </dependencies>
    <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <outputName>GoogleSearchTestResults</outputName>                  
        </configuration>
      </plugin>
    </plugins>
  </reporting>   
</project>



34 . Save the pom.xml. Now in your eclipse,under Project Explorer you should be able to see the selenium dependencies added as shown below



35. Now we have selenium dependencies and fill in the test methods with selenium implementations

36. Now we are ready with tests. How to generate HTML reports??
We will generate HTML reports from command prompt using maven commands. Before that to run maven commands from command promopt we should have maven jars.

37. Now go to the following link and download maven jars
http://www.apache.org/dyn/closer.cgi/maven/binaries/apache-maven-2.2.1-bin.zip

38.Extract the maven.zip on to you local directory

39.set Maven/bin path in system environment variables path
Open SystemProperties, click on advanced tab, edit the path and set the maven/bin in the path. click on ok button. See below

40.Maven requires JDK to execute the maven tasks. Set the JAVA_HOME USER variable
See below on how to set JAVA_HOME user variable


41. Apply the changes
42. Now to ensure that maven works, open the command prompt and type mvn -version
you should see the reponse some thing like this


Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)
Java version: 1.6.0_18
Java home: C:\Program Files\Java\jdk1.6.0_18\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows xp" version: "5.1" arch: "x86" Family: "windows"



43.Now maven setup for command prompt is ready and from the command prompt change the directory where your Maven project pom.xml is located 
 44. Now type the command mvn site. This  will run your tests before running tests, maven   will download the required maven plugin.
 45.On running the above command you should be able to see the below response in the command line console


46. Go to your project target/site directory ex: E:\eclipse\myworkspace\MyMavenProject\target\site and check for the html report generated with the name GoogleSearchTestResults.html. this is the one we have specified in pom.xml  

 47 Open GoogleSearchTestResults.html.You  should see a beautiful HTML Test Report with Pass Faill Results





Tuesday, September 7, 2010

How to Handle Windows if there are no titles


If your application has a link or a button which opens a new window, and you want to perform some action on the newly opened window though selenium, it's not that hard to handle if you have title, name or the variable associated with that window.

However this is not the case always, sometime you don’t have name of the window or any variable associated with it, and you are not even able able to identify window using title, at the time selenium sucks to identify the window. However there are some alternative ways to resolve this (which might work, not sure). But before we see that let’s see how to select the windows that can be identified easily.


Select window using SelectWindow API

    * Title
    * Name
    * Variable Name (variable to which window is assigned)
    * Inbuilt APIs to retrieve Windows Names, Titles and IDs

When SelectWindow API fails to Identify Window....


Select window using SelectWindow API >> Selenium provides the selectWindow API which takes any of the following argument to identify the window.

Title: Use whatever appears on title bar of the window you want to select as argument to selct window API.

However be careful while using title to select the window. Because it may happen that multiple windows have same titles.And in this case Selenium just says that it will choose one, but doesn't mention which one. If this is the case where both have same title I would suggest not to use the title for selecting window. And sometimes the titles of windows are dynamic, and that may create some extra noise.

Name: You can use windows name to identify the window.

For example if the code to open a new window is like as below.
window.open("http://google.co.in","Google Window");

(The second parameter here is windows name. Developer uses this to identify the window in order to use that in further part of the coding.)

You can use "Google Window" as the argument to selectWindow, to select the window as shown below if the code to open the window is as shown above.

selenium.selectWindow("Google Window"); // select new window
//Do whatever you want to do on new window
selenium.close(); //Close the newly opened window
selenium.selectWindow(null); //To choose the original window back.

Variable name: If opened window is assigned to some variable you can use that variable to identify and select that window.

For example if the code to open a new window is like as below.

GoogleWindow = window.open("http://google.co.in");
 
You can use "GoogleWindow" as argument to SelectWindow API, to select the window as shown in the code.

1.selenium.waitForPopUp("GoogleWindow", "30000");
2.selenium.selectWindow("GoogleWindow");
3.//Execute steps on new window
4.selenium.close(); //close the new window
5.selenium.selectWindow("null"); // select original window.

Using inbuilt API to retrieve Windows Names, Titles and IDs


Selenium provides some APIs to find out the names, Titles and IDs of the all opened windows. So you can use this APIs with SelectWindow API to select the window.

getAllWindowNames() – this will return you the array of all the opened windows names.
getAllWindowTitles() - this will return you the array of all the opened windows names.
getAllWindowIDs() - this will return you the array of all the opened windows names.

So if you have opened only single window you can use something like this to select the newly opened window.

1.selenium.selectWindow(getAllWindowNames()[1]);
OR

1.selenium.selectWindow(getAllWindowTitles()[1]);
OR
1.selenium.selectWindow(getAllWindowIDs ()[1]);

When SelectWindow API fails to Identify Window??


Sometimes it happens that you use all the things to select the window but it fails to identify the windows. At the time you can use one of the following ways

Check the selenium logs.!!!

The document of the selectWindow API says that if selenium is not able to identify the window after using all the things mention above you should check out for the window name in selenium log. To do that just start your selenium server with –log argument, something like following:

Java – jar path of selenium-server.jar –log log.txt

Write down the test case to open the window and execute it. Now shutdown the selenium server and checkout the logs for something like this.

Debug: window.open call intercepted; window ID

If you find this you can use this window ID to identify and select the window as the argument to selectWindow API.

Selecting the Window Using openWindow API

Sometimes selenium is not able to identify the window, one of the case is when the window is opened through onload event. Something likes this

<body onload='window.open("http://google.co.in");'>

In this case you can force selenium to identify the window using openwindow command, with URL as blank and name as you like.

1.Selenium.openWindow("","MyWindow");

2.selenium.selectWindow("MyWindow");

But if your window is not opening through onload event, and though selenium is not able to select the window after doing all the above things. The only thing left is to open the window using openwindow API with URL same as it would be if would have been opend through button or link click and name as you like. Something like as below.

1.Selenium.openWindow("http://google.co.in","MyWindow");
 
2.Selenium.selectWindow("MyWindow");




 ****Note : This article has been picked from Gauraung Shah's blog. Thanks!!! for his very detailed explanation

Executing a batch file which which starts Selenium Server

Runtime.getRuntime().exec("cmd /c start SeleniumStart.bat");

How to programatically find the RC Server port??

SeleniumServer server = new SeleniumServer();
server.start();
System.out.println(server.getPort());

How do I highlight an input field using Selenium??

use selenium.highlight("name=q");

Saturday, September 4, 2010

How to get the current URL using Selenium??

Use this command to print the current URL
System.out.println(selenium.getLocation());

How to shut down Selenium Server if it is already running on port 4444

There are chances that when you are running tests, the server might not be shutdown properly. In this case, when you try to re-run your tests, you may encounter the following error

java.net.BindException: Selenium is already running on port 4444. Or some other service is.
    at org.openqa.selenium.server.SeleniumServer.start(SeleniumServer.java:399)
    at login.testLogin(login.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at junit.framework.TestCase.runTest(TestCase.java:168)
    at junit.framework.TestCase.runBare(TestCase.java:134)
    at junit.framework.TestResult$1.protect(TestResult.java:110)
    at junit.framework.TestResult.runProtected(TestResult.java:128)
    at junit.framework.TestResult.run(TestResult.java:113)
    at junit.framework.TestCase.run(TestCase.java:124)
    at junit.framework.TestSuite.runTest(TestSuite.java:232)
    at junit.framework.TestSuite.run(TestSuite.java:227)
    at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:76)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)


Solution for the above problem is , type the below in the browser URL and the server will be stopped
http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer
Now your should be able to see the message "OKOK" in the browser window

How to execute Java Script using Selenium

in the below example,"navigator.userAgent;" is the java script

     For Printing Operating System Detail>>
     System.out.println(selenium.getEval("navigator.userAgent;"));

Thursday, September 2, 2010

How to Supress/accept SSL certificates using Selenium

Just follow 2 steps to make selenium accept the SSL certificated
1. Start your Selenium RC server using the following command
java -jar selenium-server.jar -trustAllSSLCertificates

For Firefox
2. use firefoxproxy instead of *firefox

For Internet Explorer
2. use iexploreproxy instead of *iexplore

An extra step is required for proxying SSL content with Internet Explorer. Selenium bundles a special certification authority (CA) certificate that is used to trust all the other SSL certificates.

Installing the CyberVillains Certificate on Windows

The CyberVillains certificate is bundled in the most recent Selenium RC releases in SSLSupport folder. If you download the distribution and extract it, you should be able to get going starting with Figure 1. In the explorer address bar in Figure 1 you can see where to find the certificate.










                                          Figure 1 

Double-click the CyberVillains certificate in the selenium server distribution(Refer above Image)

Click on Install Certificate Button

Click on Next Button

Select the radio button "Place all certificates in the following store"

Select Trusted Root CertificationAuthorities folder

Click on Finish button

Accept Security warning


Wednesday, September 1, 2010

How to print all the available options in a dropdown

    static SeleniumServer server;
    static Selenium selenium;
    public void testPrintDropdownValues() throws InterruptedException
    {
        //Start the server
        try {
            server.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Failed to start the server");
            e.printStackTrace();
        }
        //Stop the server
        server.stop();
      
        //Start the selenium session
        selenium = new DefaultSelenium
                               ("localhost",4444,"*firefox","http://www.google.com");
        selenium.start();
        selenium.open("");
   
        //click on Advanced Search Window
        selenium.click("link=Advanced Search");    
       
        //Print all the available options from the results dropdown in the google advanced search page
        String[] options = selenium.getSelectOptions("name=num");       
        //The above command returns a array of strings(options)
        for (int i = 0; i < options.length; i++) {
            System.out.println("Option: " + i + " is" + options[i]);
        }
       
       
        //Stop & close the selenium browsers
        selenium.close();
        selenium.stop();
    }

How to select a value from dropdown??

    static SeleniumServer server;
    static Selenium selenium;
    public void testSelectValueFromDropDown() throws InterruptedException
    {
        //Start the server
        try {
            server.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Failed to start the server");
            e.printStackTrace();
        }
        //Stop the server
        server.stop();
      
        //Start the selenium session
        selenium = new DefaultSelenium
                                   ("localhost",4444,"*firefox","http://www.google.com");
        selenium.start();
        selenium.open("");
   
        //click on Advanced Search Window
        selenium.click("link=Advanced Search");
       
        //Select  results from results dropdown
        selenium.select("name=num", "50 results");           
       
        //Stop & close the selenium browsers
        selenium.close();
        selenium.stop();
    }

How to mazimize browser window??

static SeleniumServer server;
    static Selenium selenium;
    public void testBrowserMaximize() throws InterruptedException
    {
        //Start the server
        try {
            server.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Failed to start the server");
            e.printStackTrace();
        }
        //Stop the server
        server.stop();
      
        //Start the selenium session
        selenium = new DefaultSelenium("localhost",4444,"*firefox","http://www.google.com");
        selenium.start();
        selenium.open("");
   
        //Maximize the browser window
        selenium.windowMaximize();
       
        //Stop & close the selenium browsers
        selenium.close();
        selenium.stop();
    }

Simulating Browser Back button

  static SeleniumServer server;
    static Selenium selenium;
    public void testBrowserBackButton() throws InterruptedException
    {
        //Start the server
        try {
            server.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Failed to start the server");
            e.printStackTrace();
        }
        //Stop the server
        server.stop();
      
        //Start the selenium session
        selenium = new DefaultSelenium("localhost",4444,"*firefox","http://www.google.com");
        selenium.start();
        selenium.open("");
       
        //Click on Advanced Search Link
        selenium.click("link=Advanced Search");
       
        //Click on Back Button to go back to Google Search page
        selenium.goBack();
       
        //Stop & close the selenium browsers
        selenium.close();
        selenium.stop();
    }

Creating Selenium RC Instance

    static SeleniumServer server;
    static Selenium selenium;
    public void testCreateRCInstance() throws InterruptedException
    {
        //Start the server
        try {
            server.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Failed to start the server");
            e.printStackTrace();
        }
        //Stop the server
        server.stop();
      
        //Start the selenium session
        selenium = new DefaultSelenium("localhost",4444,"*firefox","http://www.google.com");
        selenium.start();
        selenium.open("");
       
        //Stop & close the selenium browsers
        selenium.close();
        selenium.stop();
    }

Programatically start and stop the Selenium Server

    static SeleniumServer server;
   
    public void testStartSeleniumServer() throws InterruptedException
    {
        //Start the server
        try {
            server = new SeleniumServer();
            server.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Failed to start the server");
            e.printStackTrace();
        }
        //Stop the server
        server.stop();
      
    }
}