Showing posts with label webdriver. Show all posts
Showing posts with label webdriver. Show all posts

Thursday, October 17, 2013

Speedup Your Selenium Test with PhantomJS

I was searching some way to speedup my WebDriver tests and this is what I came across, PhantomJS. It took awhile to understand how it works but it's worth spending time as I can say it's more than 50% faster when your run your test with PhantomJS. So,

What is PhantomJS?

PhantomJS is a headless WebKit scriptable with a JavaScript API. It's okay if you didn't understand it by this single line. Let me explain it to you.
Webkit is a browser engine which allows web browser to render pages, and it is used by many streamline browser (I guess Firefox and Google chrome both uses this). Now what is this headless then? Headless mean you won't be able to see any GUI component of the browser.

So Why PhantomJS is faster ?

This is the second question you might come up with. That if it is the same engine that many browser uses then how my test cases will execute faster if I will run them on PhantomJS.
The reason is, it just process data (request and response) it doesn't draw canvas.

We have had enough talk, now let's compare the result.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.testng.annotations.Test;

public class TestPhantoJS {

 /**
  * @author Gaurang_Shah
  * Following test will search the keyword on google 
  * and will print all websites on first page.
  */
 @Test
 public void GoogleSearch(){
  WebDriver driver = new PhantomJSDriver();
//  WebDriver driver = new FirefoxDriver();
  driver.get("http://google.com");
  driver.findElement(By.name("q")).sendKeys("phantomjs");
  driver.findElement(By.name("q")).submit();
  List<WebElement> sites = driver.findElements(By.xpath("//cite"));
  System.out.println(driver.getTitle());
  int index=1;
  for(WebElement site: sites){
   String siteName=site.getText();
   if(!siteName.equalsIgnoreCase(""))
    System.out.println(index+++":--"+site.getText());
  }
  driver.close();
 }
}
On my machine when I am running above test with PhantomJSdriver and FirefoxDriver following is the result.
FirefoxDriver - ~28 seconds
PhantomJSDriver - ~13 seconds
Pretty Fast. Right ??

Let Me Move My all Tests to PhantomJSDriver 

this is the first thought that my come up in your mind after this result. Right ???, however I wouldn't advice you to do that. And there are reason to this as well as mention below.
PhantomJS is just a headless WebKit which uses JavaScript, however it uses GhostDriver to run your test cases used webdriver. And it's in intermediate stage and you might feel bit trouble with someone the WebDriver API.

What is GhostDriver?? 

I am sure you must have this question in mind. Let me try to explain it to you. It's a Webdriver wire protocol in simple javascript for PhantomJS. (what the hell ??? ) ohh. let me make it more simple. GhostDriver is not but some kind of communicator between your Webdriver Bidning and PhantomJS. PhantomJS comes with the GhostDriver inbuilt, however it's available separately as well.

Tuesday, October 1, 2013

WebDriver: TestNG with ANT

Few posts back I explained how to use Maven with Webdriver and TestNG. Now let's see how to use ANT with WebDriver and TestNG.
<project name="WebDriverAntTestNG" default="run" basedir=".">
 
 <path id="libs">
  <!-- Include all the external Jar files -->
  <fileset dir="${basedir}\src\jars">
   <include name="*.jar"/>
  </fileset>
  <!-- Include all the compile classes -->
  <fileset dir="bin">
   <include name = "**/*.class"/>
  </fileset>
  <pathelement path="${basedir}\bin"/>
  </path>
 
 <target name="run">
    <antcall target="init"/>
    <antcall target="compile"/>
    <antcall target="runTests"/>
  </target>
 
   <!-- Delete old data and create new directories -->
  <target name="init" >
   <echo>Initlizing...</echo>
   <delete dir="bin" />
    <mkdir dir="bin"/>
    <delete dir="report" />
    <mkdir dir="report"/>
    
  </target>
 
 <!-- Complies the java files -->
 <target name="compile">
    <echo>Compiling...</echo>
    <javac includeantruntime="false" debug="true" srcdir="src" destdir="bin"   classpathref="libs" />
  </target>

 <!-- Runs the file and generates Reportng report -->
 <target name="runTests" description="Running tests" >
  <echo>Running Tests...</echo>
    <taskdef resource="testngtasks" classpathref="libs"/>
    <testng outputDir="report"
    haltonfailure="true"
    classpathref="libs"
      >
   <classfileset dir="bin" includes="**/*.class" />
    </testng>
  </target>

</project>

Targets Explained:


Run: This is main target, which will call all the below target in order.
Init: This target will delete the Bin an Report directory and will crate again in order to clean. 
Compile: This target will compile all the java classes. 
runTests: This target contain the TestNGTask which will all the testng tests. 


Monday, September 2, 2013

WebDriver with Jenkins

In the last post we see how to create Maven Project for WebDriver from eclipse. Now let's configure same Webdriver Maven Project on Jenkins.

Setup Jenkins on Windows 

download the jenkins from following location
http://jenkins-ci.org/
Running Jenkins as War file 
You can run jenkins using war file, if you are doing it you don't need any slave to start on machine. Running Jenkins as Windows Service 
If you have installed Jenkins as Windows Services then you need to Start Slave and Bind you project to that slave.

Create/Run Slave Node 

If Jenkins is installed as Windows Services you need to start the JNLP slave node on machine where you need to execute your test cases. Follow the process to create node.
  • Go to Manage Jenkins->Manage Nodes and Click on New Node
  • Enter the Node Name and choose Dumb Slave
    Create Jenkins Slave node for WebDriver Execution
    Create Jenkins Slave node for WebDriver Execution


  • Enter the information as mention in the screenshot
    Configure Node for WebDriver
    Configure Node for WebDriver
  • After saving node will be listed under Nodes 
    All Available Nodes in Jenkins
    All Available Nodes in Jenkins
  • Start the node by Running displayed command in CMD
    Start JNLP node in Jenkins
    Starting JNLP Node in Jenkins
  • if everything has been done correctly if you will able to see small java program running
    Connected JNLP Node
    Connected JNLP Node


Configure Maven in Jenkins

Before you create a new Job for Maven WebDriver Project, let's configure Maven in jenkins
Go to Manage Jenkins->Configure System and Provide Installation directory for JDK and Maven as mention in screenshot below
Configure JDK and Maven in Jenkins
Configure JDK and Maven in Jenkins

Create New Job on Jenkins

Now let's create the new Job for Project
  • Go to Home page and click on New Job
    Create Jenkins Job for Maven WebDriver Project
    Create Jenkins Job for Maven WebDriver Project
  • Restrict the job to run on the Slave Node we created
    Configure WebDriver Project to run on Specific Node
    Configure WebDriver Project to run on Specific Node
  • Click on Use custom workspace and Mention your workspace location und Directory
  • Provide the path of pom.xml in Root POM and provide Test in Goals and Options
    Provide Maven in Goal in Jenkins
    Provide Maven Goal in Jenkins

Sunday, September 1, 2013

WebDriver with Maven

Maven is a build Automation Tool somewhat like ANT. Having use ANT for the previous project wanted to try Maven this time. I thought it would be easy as I know ANT, however it took a while for me to figure out as i didn't find any proper tutorial on net. And this is the reason I am writing new Blogpost.

I have just started, So if someone knows the better way to do few things mention here please let me know in comment.

Now let's try setting up new Maven Project for Webdriver using Eclipse. However before you do, you need to download and setup Maven on you local machine.

Setup up Maven
  • download the appropriate maven from the following site.
    http://maven.apache.org/download.cgi Extract it to some location and setup the PATH variable. 
  • If you have done everything correctly, Following command on CMD will let you know the Maven Version.
    mvn --version 


Install Maven Plug-in in Eclipse 
Install the m2Eclipse plugin in you eclipse

Setup Maven Project for WebDriver.

  • In Eclipse choose New Maven Project and check the "Create Simple Project" 
  • Fill the Group id and Artifact id 
  • Create New Class named "GoogleTest" under "src/test/java" Copy Following code in it.
  • GoogleTest.java 

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.testng.annotations.Test;
    
    /**
     * @author Gaurang_Shah
     */
    public class GoogleTest {
     private WebDriver driver;
    
     @Test
     public void verifySearch() {
      driver = new FirefoxDriver();
      driver.get("http://www.google.com/");
      driver.quit();
     }
    }


  • It will show you some compile time error as we haven't added the dependencies yet.
  • Maven mention all the dependencies in pom.xml file. Please copy and replace the following pom.xml with your project pom.xml file.
    <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>MavenWebDriverDemo</groupId>
     <artifactId>MavenWebDriverDemo</artifactId>
     <version>0.0.1-SNAPSHOT</version>
    
     <dependencies>
      <dependency>
       <groupId>org.seleniumhq.selenium</groupId>
       <artifactId>selenium-java</artifactId>
       <version>2.33.0</version>
      </dependency>
      <dependency>
       <groupId>org.seleniumhq.selenium</groupId>
       <artifactId>selenium-server</artifactId>
       <version>2.33.0</version>
      </dependency>
      <dependency>
       <groupId>org.testng</groupId>
       <artifactId>testng</artifactId>
       <version>6.8.5</version>
      </dependency>
     </dependencies>
    </project>
  • Running Project
    • To run from Eclipse, Right click on pom.xml and choose Run as --> Maven Test 
    • To run from command line, Go to project directory and enter following command
       mvn test

    Monday, July 22, 2013

    webdriver - handle untrusted ssl certificate

    While doing automation of https site there are chances when you get the following error.
    This Connection is Untrusted. 



    Reason: This certificate is not issued by some valid authority, it's a self signed certificate.

    Solution:

    • Create a new profile and add this certificate in that profile by using following steps.
    • Make sure you are accessing site though the domain for which certificate has issued.
    •  If you get the above screen after accessible the site, You need to add certificate in Exception so next time it doesn't give you error.
    • However while adding certificate make sure "Permanently store this exception" check box is selected. 
    • If  "Permanently store this exception" is enable the history.

    • Now you need to give path of this newly created profile while creating the object of WebDriver.

    Monday, January 28, 2013

    WebDriver: isTextPresent

    WebDriver is way far better in many ways than selenium RC, However if you have migrated from Selenium RC, you will miss few functions. And two on the top lists are isTextPresent and isElementPresent. Though it's not available in webdriver, it's not complicated to implement, there are various ways to the same thing. I will discuss few ways in following post.

    1. Using in in-build PageSource API
    2. public boolean isTextPresent(String text){
       if (driver.getPageSource().contains(text)) {
        return true;
       }
       else 
        return false;
      }
      Disadvantages:
      • It is too slow as compared other two options as it checks in whole page source.
      • Result might be wrong as it doesn't verify only visible text on webpage but whole source code (script + html tags)
    3. Using XPath
    4. public boolean isTextPresent(String text){
       try {
        driver.findElement(By.xpath("//*[contains(.,'"+text+"')]"));
        return true;
       }catch(NoSuchElementException e){
        return false;
       }
      }
      Disadvantages:
      As it is using XPath, it might be slow on IE than on Firefox and Chrome Browsers.
    1. Using Selenium RC Function.
    2. public boolean isTextPresent(String text){
       try{
        WebDriverBackedSelenium selenium = new WebDriverBackedSelenium(driver, "");
        if(selenium.isTextPresent(text)){
         return true;
        }else{
         return false;
        }
       }catch(Exception e){
        return false;
       }
      }
      Disadvantages:
      It is using Selenium RC code.

    Thursday, October 18, 2012

    WebDriver - Take Screenshots on Test Case Fail.

    There are two way you can achieve this if you are using TestNG as you unit testing framework. Refer the following blog post to see how to do this using TestNG.
    http://qtp-help.blogspot.in/2010/07/testng-take-screenshot-of-failed-test.html

    Below we will discuss how to do the same thing using WebDriver listeners. Webdriver has a WebDriverEventListener interface which you can implement and override the particular listener you want. WebDriverEventListener interface has onException method which is being called whenever a WebDriver exception occurs, So we will override this method and will write down the code to take screenshot in it.

    WebDriverEventListenerDemo.java
    you need to implement all the methods of the WebDriverEventListener class, here I haven't show that to make code looks small.
    import java.io.*;
    import org.apache.commons.io.FileUtils;
    import org.openqa.selenium.*;
    import org.openqa.selenium.support.events.WebDriverEventListener;
    
    /***
     * Implements WebDriverEventListener and overrides onException method
     * @author Gaurang
     * 
     */
    public class WebDriverEventListenerDemo implements WebDriverEventListener {
     @Override
     public void onException(Throwable exception, WebDriver driver) {
      File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      try {
       FileUtils.copyFile(screenShot, new File("c:\\tmp\\exception.png"));
      } catch (IOException e) {
       e.printStackTrace();
      }
      
     }
    }
    
    TestWithEvenRegistered.java
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.events.EventFiringWebDriver;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;
    
    /***
     * Class registers the Event listern class we created 
     * @author gshah
     *
     */
    public class TestWithEvenRegistered {
     
     WebDriver driver = new FirefoxDriver();
     EventFiringWebDriver eventFiringWebDriver;
     @BeforeClass
     public void setup() {
      eventFiringWebDriver = new EventFiringWebDriver(driver);
      eventFiringWebDriver.register(new WebDriverEventListenerDemo());
      eventFiringWebDriver.get("http://google.com");
      
     }
     
     /**
      * "qq" is wrong element id and so NoElementFound Exception will 
      * be generated, which will call our overridden method of WebDriverEventListenerDemo
      * class and will take the screenshot. 
      */
     @Test
     public void test(){
      eventFiringWebDriver.navigate().to("http://google.com");
      eventFiringWebDriver.findElement(By.name("qq"));
      
     }
    }
    

    Monday, October 8, 2012

    WebDriver - Selecting from CSS dropdown

    In last few years the web designing has advanced too much. And for better look and feel people sometimes uses CSS to overwrite basic HTML component like editbox, dropdown, checkbox. It doesn't create any problem until you try to Automate it, but the moment you think to automate it started giving problem.
    The biggest problem is, tools specifically selenium doesn't identify them as a proper element. For example, "All Categories" dropdown on flipcart.com.

    If you will see it's code it is not standard HTML dropdown box, you wouldn't be able to find any select tag. And so the following code would fail.
    @Test
     public void selectCSSDropDown(){
      driver.get("http://flipcart.com");
      Select catagoryDropDown = new Select(driver.findElement(By.className("fk-menu-selector")));
      catagoryDropDown.selectByVisibleText("Cameras");
     }
    It will give you error somewhat like blow:
    org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "a"
    There are two workarounds to this.
    1. Click on the Dropdown and then click on the item you want to select 
       However using this you will be able to select by index only and not by visible text
      @Test
      public void selectCssDropDownUsingCSS() {
      
       driver.get("http://flipcart.com");
       driver.findElement(By.className("fk-menu-selector")).click();
       driver.findElement(By.cssSelector("div#fk-mI li:nth-child(5)")).click();
      
      }
    2. Through JavaScript
      You are lucky if your website if using JavaScript function to select an item, that way we can directly call those JavaScript functions as mention below
      @Test
      public void selectCssDropDownUsingJavaScript(){
       driver.get("http://flipcart.com");
       JavascriptExecutor js = (JavascriptExecutor) driver;
       js.executeScript("selectMItem('Cameras', 'cameras')");
      }

    Sunday, October 7, 2012

    Webdriver - Page Object Pattern

    What I am going to discuss here is Page Object Pattern with Page Factory for Webdriver. Let's not talk much about theory and let's see how to implement it. let's take one scenario and see how we can automate it without and with Page Object Pattern Scenario:
    1. Open http://newtours.demoaut.com/ site 
    2. Login to the site. 
    3. Log out. Now if we are not using any design patten the testcase will look like below
    @Test
    public void testLogin() {
     driver.findElement(By.id("userName")).clear();
     driver.findElement(By.id("userName")).sendKeys("testuser33");
     
     driver.findElement(By.id("password")).clear();
     driver.findElement(By.id("password")).sendKeys("password123");
     
     driver.findElement(By.id("login")).click();
     
     driver.findElement(By.linkText("SIGN-OFF")).click();
    
    }
    
    Now let's see how the code will look like if we will have to use the Page Object Pattern with Page Factory. LoginPage.java - contains Login page web elements and functions

    package Pages;
    
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.How;
    import org.openqa.selenium.support.PageFactory;
    
    public class LoginPage {
     
     final WebDriver driver;
     
     @FindBy(how = How.NAME, using = "userName")
     private WebElement usernameEditbox;
     
     @FindBy(how = How.NAME, using = "password")
     private WebElement passwordEditbox;
     
     @FindBy(how = How.NAME, using = "login")
     private WebElement singinButton;
    
     public LoginPage(WebDriver driver) {
      this.driver = driver;
     }
    
     public void enterUsername(String login) {
      usernameEditbox.clear();
      usernameEditbox.sendKeys(login);
     }
    
     public void enterPassword(String password) {
      passwordEditbox.clear();
      passwordEditbox.sendKeys(password);
     }
    
     public void clickSigninButton() {
      singinButton.click();
     }
    
     public FindFlightPage login(String login, String password) {
      enterUsername(login);
      enterPassword(password);
      clickSigninButton();
      return PageFactory.initElements(driver, FindFlightPage.class);
     }
    }
    
    
    FindFlightPage.java - contains Find Flight page web elements and functions
    package Pages;
    
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.How;
    import org.openqa.selenium.support.PageFactory;
    
    public class FindFlightPage {
    
     final WebDriver driver;
     
     public FindFlightPage(WebDriver driver) {
      this.driver = driver;
     }
     
     @FindBy(how = How.LINK_TEXT, using="SIGN-OFF")
     private WebElement signOff;
     
     public LoginPage singOff(){
      signOff.click();  
      return PageFactory.initElements(driver, LoginPage.class);
     }
    }
    
    
    LoginTest.java  - Actual class which contains tests for login page
    package Tests;
    
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.PageFactory;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;
    
    import Pages.FindFlightPage;
    import Pages.LoginPage;
    
    public class LoginTest {
    
     WebDriver driver;
     private static String login = "testuser33";
     private static String pass = "password123";
    
     @BeforeClass
     public void setUp() throws Exception {
      driver = new FirefoxDriver();
      driver.get("http://newtours.demoaut.com/mercuryreservation.php");
     }
    
     @Test
     public void testLogin() {
     
      LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
      FindFlightPage findPage = loginPage.login(login, pass);
      
      loginPage = findPage.singOff();
     }
     
     @AfterClass
     public void tearDown() throws Exception {
      driver.quit();
     }
    }
    
    

    Wednesday, March 7, 2012

    WebDriver - Dynamic Table

    Scenario: Sometimes we have a dynamic table, in which neither the number of rows, or the order is constant. And in such case if you have to verify and particular values from the table you can use the following technique.

    Assumption: Following table is dynamic table, which can have any number of rows and order or the records may also change every time you load.

    Names Designationsalary
    GaurangConfused45000
    AjayTeam Lead50000
    BinoyQA40000
    SantoshProject Manager100000

    TestCase: Verify the Salary of Gaurang from the above table.

    /**
     * @author Gaurang Shah
     * Purpose: To demonstrate how to verify Dynamic Table in Selenium 
     */
    import static org.junit.Assert.*;
    
    import java.util.List;
    
    import org.junit.AfterClass;
    import org.junit.BeforeClass;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class WebDriverTable {
     public static WebDriver driver;
    
     @BeforeClass
     public static void setup() {
      // Create a new instance of the Firefox driver
      driver = new FirefoxDriver();
      driver.get("http://qtp-help.blogspot.in/2012/02/selenium-verify-table.html");
     }
    
     @AfterClass
     public static void tearDown() {
      // Close the browser
      driver.quit();
     }
    
     @Test
     public void testDynamicTable() throws InterruptedException {
    
      String salary = "0";
      List<WebElement> totalRows = driver.findElements(By
        .xpath("//table[@name='salaryTable']/tbody/tr"));
    
      for (int row = 1; row <= totalRows.size(); row++) {
       // Fetch the text of first column (name)
       String name = driver.findElement(By.xpath("//table[@name='salaryTable']/tbody/tr["+row+"]/td[1]")).getText();
    
       // If name matches gaurang fetch the text of third column (salary)
       if (name.equalsIgnoreCase("gaurang")) {
        salary = driver.findElement(By.xpath("//table[@name='salaryTable']/tbody/tr["+row+"]/td[3]")).getText();
       }
      }
    
      System.out.println(salary);
      assertEquals("Verify Salary", "45000", salary);
     }
    }
    
    

    Friday, September 2, 2011

    Selenium Grid with Webdriver

    Recently I gone through the webdriver and then I thought to configure it with Selenium grid. On selenium grid site they have mention how to configure it but it's not in details so i though to write that on this blog.
    To configure webdriver with Selenium grid you require grid2.

    Prerequisites.
    • TestNG
    • Grid2
      Download the selenium-server-standalone-version.jar from the below location.
      Download Grid2

    We will see two things in Selenium Grid.
    1. Run Testcase in parallel
    2. Run same testcase on different browser in parallel for browser compatibility testing.

    Run Testcases in parallel.

    In this example we will run testcases of GridWithWebdriver and GridWithWebdriver1 class on Internet Explorer.

    GridWithWebdriver.java
    /**
     * @author Gaurang Shah
     * To Demonstrate how to configure webdirver with Selenium Grid
     */
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import org.junit.AfterClass;
    import org.openqa.selenium.*;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import org.testng.annotations.*;
    
    public class GridWithWebdriver {
     
     public WebDriver driver;
     
     @Parameters({"browser"})
     @BeforeClass
     public void setup(String browser) throws MalformedURLException {
      DesiredCapabilities capability=null;
       
      if(browser.equalsIgnoreCase("firefox")){
       System.out.println("firefox");
       capability= DesiredCapabilities.firefox();
       capability.setBrowserName("firefox"); 
       capability.setPlatform(org.openqa.selenium.Platform.ANY);
       //capability.setVersion("");
      }
     
      if(browser.equalsIgnoreCase("iexplore")){
       System.out.println("iexplore");
       capability= DesiredCapabilities.internetExplorer();
       capability.setBrowserName("iexplore"); 
       capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
       //capability.setVersion("");
      }
      
      driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
      driver.navigate().to("http://google.com");
      
     }
     
     @Test
     public void test_first() throws InterruptedException{
      Thread.sleep(3000);
      WebElement search_editbox = driver.findElement(By.name("q"));
      WebElement search_button = driver.findElement(By.name("btnG"));
      search_editbox.clear();
      search_editbox.sendKeys("first");
      search_button.click();
     }
     
     @Test
     public void test_second(){
      WebElement search_editbox = driver.findElement(By.name("q"));
      WebElement search_button = driver.findElement(By.name("btnG"));
      search_editbox.clear();
      search_editbox.sendKeys("second");
      search_button.click();
     }
     
     @AfterClass
     public void tearDown(){
            driver.quit();
     }
    }
    
    GridWithWebdriver1.java
    /**
     * @author Gaurang Shah
     * To Demonstrate how to configure webdirver with Selenium Grid
     */
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import org.junit.AfterClass;
    import org.openqa.selenium.*;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import org.testng.annotations.*;
    
    public class GridWithWebdriver1 {
     
     public WebDriver driver;
     
     @Parameters({"browser"})
     @BeforeClass
     public void setup(String browser) throws MalformedURLException, InterruptedException {
      DesiredCapabilities capability=null;
       
      if(browser.equalsIgnoreCase("firefox")){
       System.out.println("firefox");
       capability= DesiredCapabilities.firefox();
       capability.setBrowserName("firefox"); 
       capability.setPlatform(org.openqa.selenium.Platform.ANY);
       //capability.setVersion("");
      }
     
      if(browser.equalsIgnoreCase("iexplore")){
       System.out.println("iexplore");
       capability= DesiredCapabilities.internetExplorer();
       capability.setBrowserName("iexplore"); 
       capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
       //capability.setVersion("");
      }
      
      driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
      driver.navigate().to("http://google.com");
      
     }
     
     @Test
     public void test_third() throws InterruptedException{
      Thread.sleep(3000);
      WebElement search_editbox = driver.findElement(By.name("q"));
      WebElement search_button = driver.findElement(By.name("btnG"));
      search_editbox.clear();
      search_editbox.sendKeys("third");
      search_button.click();
      
     }
     
     @Test
     public void test_fourth(){
      WebElement search_editbox = driver.findElement(By.name("q"));
      WebElement search_button = driver.findElement(By.name("btnG"));
      search_editbox.clear();
      search_editbox.sendKeys("foruth");
      search_button.click();
      
     }
     
     @AfterClass
     public void tearDown(){
            //Close the browser
         //   driver.quit();
    
     }
    }
    

    Testng.xml
    <suite name="Selenium Grid with webdriver" verbose="3"  parallel="classes" thread-count="2">   
      <test name="Selenium Grid Demo">
      <parameter name="browser" value="iexplore"/>
        <classes>
          <class name="tests.GridWithWebdriver"/>
       <class name="tests.GridWithWebdriver1"/>
        </classes>
     </test>
     </suite>
    

    Now in order to run using testng.xml we need to start the Grid hub and two remote control with Iexplore as browser.

    Now to start the Grid and remote control open CMD and navigate to folder where Grid2 jar (selenium-server-standalone-x.x.x.jar) file is located and use the following commands

    To start the Grid Hub
    java -jar selenium-server-standalone-2.5.0.jar -role hub
    To start the remote control supporting Internet explore
    java -jar selenium-server-standalone-2.5.0.jar -role webdriver -hub http://localhost:4444/grid/register -browser browserName=iexplore,platform=WINDOWS
    To start another the remote control supporting Internet explore
    java -jar selenium-server-standalone-2.5.0.jar -role webdriver -hub http://localhost:4444/grid/register -browser browserName=iexplore,platform=WINDOWS -port 5556

    After this open http://localhost:4444/grid/console in you browser. You should be able to see something like below image.



    Now if you will run using testng.xml you will see two Internet explorer will open and one will execute test_first() and test_second() while another will execute test_third() and test_fourth() in parallel.

    Run same testcases on different browser in parallel.

    In this example we will execute GridWithWebdriver tests on Firefox and Internet Explorer in parallel.

    To do so you need to modify you testng.xml as below.
    Testng.xml
    <suite name="Same TestCases on Different Browser" verbose="3"  parallel="tests" thread-count="2">   
      <test name="Run on Internet Explorer">
     <parameter name="browser"  value="iexplore"/>
        <classes>
          <class name="Tests.GridWithWebdriver"/>
        </classes>
     </test>  
    
      <test name="Run on Firefox">
     <parameter name="browser"  value="firefox"/>
        <classes>
          <class name="Tests.GridWithWebdriver"/>
        </classes>
     </test>  
     </suite>
    Now to run testcases we need to start grid hub and one remote control supporting Firefox and another supporting Internet Explorer.

    Now to start the Grid and remote control open CMD and navigate to folder where Grid2 jar (selenium-server-standalone-x.x.x.jar) file is located and use the following commands
    To start the Grid Hub
    java -jar selenium-server-standalone-2.5.0.jar -role hub
    To start the remote control supporting Firefox
    java -jar selenium-server-standalone-2.5.0.jar -role webdriver -hub http://localhost:4444/grid/register -browser browserName=firefox,platform=WINDOWS
    To start another the remote control supporting Internet explore
    java -jar selenium-server-standalone-2.5.0.jar -role webdriver -hub http://localhost:4444/grid/register -browser browserName=iexplore,platform=WINDOWS -port 5556
    After this open http://localhost:4444/grid/console in you browser. You should be able to see something like below image.

    Now if you will run above test case one Firefox and one IE will launch and both test_first() and test_second() will execute in both browser simultaneously.

    Thursday, July 28, 2011

    WebDriver First look

    WebDriver has been for a while but never get a chance to look at it. finally today I downloaded the webdriver and executed the simple testcase. Let's see how to configure webdriver for java.

    First download the selenium-java-2.2.0.zip (version may differ) from http://code.google.com/p/selenium/downloads/list

    The first thing you will notice when you will extract this zip is, too much JAR files, too much as compared to only two in selenium RC.

    Now create the simple java project in eclipse. Put all the extracted JAR files in the buildpath of the project.

    Copy and paste the following code and run using Junit. (you don't require to run any selenium server)

    package Tests;
    
    import static org.junit.Assert.assertTrue;
    
    import org.junit.AfterClass;
    import org.junit.BeforeClass;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    /**
     * 
     * @author Gaurang
     *
     */
    public class GoogleTest  {
    
     public static WebDriver driver;
     @BeforeClass
     public static void setup(){
     // Create a new instance of the Firefox driver
            driver = new FirefoxDriver();
            
            // And now use this to visit Google
            driver.get("http://www.google.com");
     }
     
     @AfterClass
     public static void tearDown(){
            //Close the browser
            driver.quit();
    
     }
     @Test
     public void testSearch() throws InterruptedException {
            // Find the text input element by its name
            WebElement element = driver.findElement(By.name("q"));
            // Enter something to search for
            element.sendKeys("Cheese!");
            //driver.findElement(By.name("btnG")).click();
            // Now submit the form. WebDriver will find the form for us from the element
            element.submit();
            // Check the title of the page
            System.out.println("Page title is: " + driver.getTitle());
            Thread.sleep(3000);
            assertTrue(driver.getTitle().contains("cheese!"));
      }
    }

    To run the webdriver testcase in Internet Explorer
    replace the driver = new FirefoxDriver(); line from the setup() method with following line.
    driver = new InternetExplorerDriver();

    To run the webdriver testcase in Opera
    replace the driver = new FirefoxDriver(); line from the setup() method with following line.
    driver = new OperaDriver();

    To run the Webdriver testcase in Chrome
    Download the chrome driver form the below URL
    Download Chrome driver

    Now extract the zip file and set the path of executable in PATH variable.

    replace the driver = new FirefoxDriver(); line from the setup() method with following line.

    driver = new ChromeDriver();

    Sunday, April 17, 2011

    Email Testing with Selenium

    If you web application is sending some emails and if you have to test writing code that opens email client (gmail or yahoo) and then check the mails is tedious and also not reliable. The best thing you can do for this is you can have your own SMTP server, that sends the mail for you and stores any system generated mail, rather than sending to actual user for your testing. The best SMTP server I came across is Dumbster.

    Now let's see how to use this
    Dumster.java
    public class Dumbster{
      private SimpleSmtpServer server;
    
         public Dumbster() {       
           if(server == null)
            server = SimpleSmtpServer.start(25);
         }
    
         public int howManyMainsSent() {
             int noOfMailsSent = server.getReceivedEmailSize();
             server.stop();          
             return noOfMailsSent;
         }
      
           /**
          * Use only when you are sure only 1 email has been generated
          * @return Subject of the first email
          */
        public String getEmailSubject() {
             Iterator mailIterator = server.getReceivedEmail();
             SmtpMessage email = (SmtpMessage)mailIterator.next();
             return email.getHeaderValue("Subject");
         }
      
         /**
          * Use when more then 1 email has been generated
          * @param count If more than one mails are being generated, Index of the mail
          * @return Subject of the requested email
          */
         public String getEmailSubject(int count) {
              Iterator mailIterator = server.getReceivedEmail();
              SmtpMessage email = null;
              for(int i=1; i<=count; i++){
                email = (SmtpMessage)mailIterator.next();
              }
              return email.getHeaderValue("Subject");
          }
    }

    Now to use Test the mail you just need to create the server of this class just before you mails shoots and then you need to call the particular function you want.