Tuesday 23 April 2013

Selecting any date from JQuery Date Picker using Selenium Web Driver

Purpose: Selecting any date from JQuery Date Picker using Selenium Web Driver

Automating JQuery Date Picker is not as easy as selecting Date Month Year select options. Following Selenium Web Driver code will help and provide basic logic to automate different JQuery Date Pickers.

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class JQueryDatePicket {
 WebDriver driver;
 WebElement dateWidget;
 List<WebElement> rows;
 List<WebElement> columns;
 List<String> list = Arrays.asList("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
 // Expected Date, Month and Year
 int expMonth;
 int expYear;
 String expDate = null;
 // Calendar Month and Year
 String calMonth = null;
 String calYear = null;
 boolean dateNotFound;

 @BeforeTest
 public void start(){
 driver = new FirefoxDriver();
 }

 @Test
 public void testJQueryDatePicket() throws InterruptedException{

  driver.get("http://jqueryui.com/datepicker/");
  driver.switchTo().frame(0);
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  //Click on textbox of Date so that datepicker will appear
  driver.findElement(By.id("datepicker")).click();
  dateNotFound = true;
  expMonth= 3;
  expYear = 2015;
  expDate = "12";
  while(dateNotFound)
  {
  
   calMonth = driver.findElement(By.className("ui-datepicker-month")).getText();
   calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
   if(list.indexOf(calMonth)+1 == expMonth && (expYear == Integer.parseInt(calYear)))
   {
    selectDate(expDate);
    dateNotFound = false;
   }
   else if(list.indexOf(calMonth)+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();
   }
   else if(list.indexOf(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[1]/span")).click();
   }
  }
  Thread.sleep(3000);
 }
 public void selectDate(String date)
 {
 dateWidget = driver.findElement(By.id("ui-datepicker-div"));
 rows=dateWidget.findElements(By.tagName("tr"));
 columns=dateWidget.findElements(By.tagName("td"));

 for (WebElement cell: columns){
  //Selects Date
  if (cell.getText().equals(date)){
   cell.findElement(By.linkText(date)).click();
   break;
  }
 }
 }

 @AfterTest
 public void tearDown()
 {
  driver.quit();
 }
}

Monday 8 April 2013

Writing simple Data Driven Framework scripts using TestNG

Purpose: Writing simple Selenium Scripts by implementing Data Driven Framework using TestNG

Data Driven Framework scripts means executing a set of steps with multiple sets of data. Selenium is not have any default way of implementing but by using TestNG support we can implement it successfully.

Step 1: JXL API Jar - We can download it form the following URL
http://sourceforge.net/projects/jxls/files/ and download latest version

Step 2: Prepare Data Source - Open an excel and prepare data source as shown below


In this example we are discussing reading inputs from an excel sheet and writing the results in reports sheet.

Step 3: Following example will demonstrate how to access from an excel sheet and how to write the results into an excel sheet.

package com.google.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class GMail{
 private WebDriver driver;
 private String baseURL;
 private FileInputStream fi;
 private Sheet s;
 private Workbook wb;

 @BeforeClass
 public void setup() throws BiffException, IOException
 {
  driver = new FirefoxDriver();
  baseURL = "http://www.gmail.com";
  fi = new FileInputStream("TestDate\\Book1.xls");
  wb = Workbook.getWorkbook(fi);
  s = wb.getSheet(0);
 }

 @AfterClass
 public void teardown()
 {
  driver.quit();
 }
 @Test
 public void testGmail() throws InterruptedException
 {
  for(int row=0; row <s.getRows();row++)
  {
    String username = s.getCell(0, row).getContents();
    System.out.println("Username "+username);
    driver.get(baseURL);
    driver.findElement(By.name("Email")).sendKeys(username);
    String password= s.getCell(1, row).getContents();
    System.out.println("Password "+password);
    driver.findElement(By.name("Passwd")).sendKeys(password);
    Thread.sleep(10000);
    Thread.sleep(30000);
    writeExcel(0, 0, "Passes");
  }
 }

public void writeExcel(int a, int b, String text) {
    try {
        File excelFile = new File("TestDate\\Results.xls");
        WritableWorkbook book;
        WritableSheet sheet;
        Workbook existingBook = null;
        if (!excelFile.exists()) {
            book = Workbook.createWorkbook(excelFile);
            sheet = book.createSheet("TESTRESULTS", 0);
        } else {
            existingBook = Workbook.getWorkbook(excelFile);
            book = Workbook.createWorkbook(excelFile, existingBook);
            sheet = book.getSheet("TESTRESULTS");
        }
        Label i = new Label(a, b, text);
        sheet.addCell(i);
        book.write();
        book.close();
        if (existingBook != null)
            existingBook.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}



















 

Setting up Eclipse Environment for Selenium

Purpose: Setting up Eclipse IDE environment to Run Selenium Script

Following are the steps to setup successful Selenium environment for Eclipse IDE

In order to Setup, we need Java, Eclipse IDE, Selenium Webdriver, TestNG.

Step 1: Download Java and install if not installed. Visit the following URL and download JDK
URL: http://www.oracle.com/technetwork/java/javase/downloads/index.html

Step 2: Download Eclipse IED and it not require ant install. Extract and open. Visit for following URL and download Eclipse

URL: http://www.eclipse.org/downloads/ download Eclipse IDE for Java EE Developers 32bit version

Step 3: Download Selenium Webdriver and build the path. Visit the following URL and download required Selenium Softwares

URL: http://selenium.googlecode.com/files/selenium-server-standalone-2.31.0.jar

Step 4: Install TestNG for Eclipse

Select Help /  Install New Software /
Click on Add
Enter Any relevent Name for Name Field
Enter URL for Eclipse 3.4 and above, enter http://beust.com/eclipse/
For Eclipse 3.3 and below, enter http://beust.com/eclipse1/
Select TestNG Software, Click Next and Install

Step 5: Create New Java Project and Create New TestNG file
Step 6: Right Click on Project > Build Path > Configure Build Path > Click Libraries > Click Add External Jars. Select the location of Selenium Webdriver and add the Selenuium .Jar file to Eclipse IDE Environment.

Step 6: Write the script and execute. Hope it will lanch application successfully.

Capturing all Links in a page, filtering and visiting filtered pages.

Purpose: Capturing all Links in a page, filtering and visiting filtered pages.


In general while testing any application we are facing a situation where we need to visit specific link available on the Web Page. The Following script help floks how to handle it.

In the following example, I am going to visit 'www.google.com', captures all the links available on the page, filter the required link and visit that link page.

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;

public class Links {
 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.tata.com/");
  driver.manage().window().maximize();
//  Extract all links from the webpage using selenium webdriver
  List<WebElement> all_links_webpage = driver.findElements(By.tagName("a"));

//  Print total no of links on the webpage
  System.out.println("Print total no of links on the webpage---------------------------------------------");
  System.out.println(all_links_webpage.size());

//  Filter the Link and visit that link
  System.out.println("Print Links------------------------------------------------------------------------");
  for(int i=0;i<all_links_webpage.size();i++)
  {
   Thread.sleep(1000);
   if(all_links_webpage.get(i).getText().toLowerCase().contains("contact"))
   {
    System.out.println("Search Resutl found");
   String link = all_links_webpage.get(i).getAttribute("href");
   driver.navigate().to(link);
   Thread.sleep(3000);
   break;
   }
  }
 driver.quit();
 }
}

How to Run Webdriver Script under Internet Explorer and Google Chrome

Purpose: How to Run Webdriver Script for Internet Explorer and Google Chrome

Running Webdriver script for Internet Explorer & Chrome is not as same as working with Firefox browser. Following are the steps to Run:

Step 1: In order to run, we need to download IE Driver & Chrome Driver and we can download from https://code.google.com/p/selenium/downloads/detail?name=IEDriverServer_Win32_2.31.0.zip
https://code.google.com/p/chromedriver/downloads/list

Step 2: Include the respective drivers in to the Path

Step 3: Set the System property using the following Command which takes two parameters Driver and location of the driver.

System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");

Step 4: Now create an Driver Object for IE using the following command

driver = new InternetExplorerDriver();

Once we start running the script Internet Explorer will open and execute script.

Following is the sample code for IE and kept commented code for Google Chrome

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class DriversExample{
private static InternetExplorerDriver driver;
//private static ChromeDriver driver;
@BeforeClass
 public void beforeClass()
 {
  System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
  driver = new InternetExplorerDriver();
//  System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
//  driver = new ChromeDriver();
  }
@Test
 public void testDrivers() throws Exception
 {
  driver.get("http://www.google.com");
  Thread.sleep(3000);
 }
@AfterClass
 public void afterClass()
 {
  driver.close();
 }
}

Monday 1 April 2013

Capturing all Links on a Web Page and visiting those links using Web Driver

Purpose: Capturing all Links on a Web Page and visiting those links

In general while testing any application we are facing a situation where we need to visit each link available on the Web Page. The Following script help floks how to handle it.

In the following example, I am going to visit 'www.google.com', captures all the links available on the page, visiting each link and coming back to home page.



importjava.util.List;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;

public class Links {

private static String homeWindow = null;
private static String[] links = null;
private static int linksCount = 0;

public static void main(String[] args) throws InterruptedException {

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
// Fllowing instruction extract all links from the webpage using selenium webdriver
List<WebElement> all_links_webpage = driver.findElements(By.tagName("a"));
// Print total no of links on the webpage
System.out.println("Print total no of links on the webpage----------------------------------------------------");
linksCount = all_links_webpage.size();
System.out.println(linksCount);
links= new String[linksCount];// Following instruction stores each link and Prints on console
System.out.println("Print Links-----------------------------------------------------------------------------------");

for(int i=0;i<linksCount;i++)
{
links[i] = all_links_webpage.get(i).getAttribute("href");
System.out.println(all_links_webpage.get(i).getAttribute("href"));
}
// Following instruction Return an opaque handle to this window that uniquely identifies it within this driver instance.
// This can be used to switch to this window at a later date
homeWindow = driver.getWindowHandle().toString();
// Visiting Each Link in on the Page

System.
out.println("Visiting Each Links------------------------------------------------------------------------");

for(int i=0;i<linksCount;i++)
{
driver.navigate().to(
links[i]);
Thread.sleep(3000);
driver.switchTo().window(
homeWindow);
}
driver.quit();
}
}