Pages

Tuesday, February 11, 2014

Selenium WebDriver hybrid framework code



Below code has three section

First section:-Excel reading

public Xls_Reader(String path)

To Download Apache POI API Jar files, GO TO THIS PAGE and click on link "poi-bin-3.10-FINAL-20140208.tar.gz" (Version 3.10 may change In future.) under Binary Distribution table. It will take you to mirror sites list page to download Apache POI API Jar files folder. Click on any mirror site link and download and extract the folder.

You will find bellow given files Inside that folder or It's sub folders. Copy all bellow given files and paste them In "JarFiles" folder of "WDDF" project.
1.               poi-3.10-FINAL-20140208.jar
2.               poi-ooxml-3.10-FINAL-20140208.jar
3.               poi-ooxml-schemas-3.10-FINAL-20140208.jar
4.               xmlbeans-2.3.0.jar (Inside ooxml-lib folder)
5.               dom4j-1.6.1.jar (Inside ooxml-lib folder)

(Note : Above jar files versions may change In future. Always Use latest version only.).

--------------------------------------------------------------------------
Second Section:-

public class TestBase
----------------------------------------------------------------------

Third section is:-

public class RegistrationTest extends TestBase


package Data;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFHyperlink;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;


import java.io.*;
import java.util.Calendar;

public class Xls_Reader {
public static String filename = System.getProperty("user.dir")+"\\src\\config\\testcases\\TestData.xlsx";
public  String path;
public  FileInputStream fis = null;
public  FileOutputStream fileOut =null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row   =null;
private XSSFCell cell = null;

public Xls_Reader(String path) {

this.path=path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
// returns the row count in a sheet
public int getRowCount(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return 0;
else{
sheet = workbook.getSheetAt(index);
int number=sheet.getLastRowNum()+1;
return number;
}

}

// returns the data from a cell
public String getCellData(String sheetName,String colName,int rowNum){
try{
if(rowNum <=0)
return "";

int index = workbook.getSheetIndex(sheetName);
int col_Num=-1;
if(index==-1)
return "";

sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num=i;
}
if(col_Num==-1)
return "";

sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(col_Num);

if(cell==null)
return "";
//System.out.println(cell.getCellType());
if(cell.getCellType()==Cell.CELL_TYPE_STRING)
 return cell.getStringCellValue();
else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){

 String cellText  = String.valueOf(cell.getNumericCellValue());
 if (HSSFDateUtil.isCellDateFormatted(cell)) {
          // format in form of M/D/YY
 double d = cell.getNumericCellValue();

 Calendar cal =Calendar.getInstance();
 cal.setTime(HSSFDateUtil.getJavaDate(d));
           cellText =
            (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
          cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +
                     cal.get(Calendar.MONTH)+1 + "/" +
                     cellText;
       
          //System.out.println(cellText);

        }



 return cellText;
 }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
     return "";
 else
 return String.valueOf(cell.getBooleanCellValue());

}
catch(Exception e){

e.printStackTrace();
return "row "+rowNum+" or column "+colName +" does not exist in xls";
}
}

// returns the data from a cell
public String getCellData(String sheetName,int colNum,int rowNum){
try{
if(rowNum <=0)
return "";

int index = workbook.getSheetIndex(sheetName);

if(index==-1)
return "";


sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(colNum);
if(cell==null)
return "";

 if(cell.getCellType()==Cell.CELL_TYPE_STRING)
 return cell.getStringCellValue();
 else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){

 String cellText  = String.valueOf(cell.getNumericCellValue());
 if (HSSFDateUtil.isCellDateFormatted(cell)) {
          // format in form of M/D/YY
 double d = cell.getNumericCellValue();

 Calendar cal =Calendar.getInstance();
 cal.setTime(HSSFDateUtil.getJavaDate(d));
           cellText =
            (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
          cellText = cal.get(Calendar.MONTH)+1 + "/" +
                     cal.get(Calendar.DAY_OF_MONTH) + "/" +
                     cellText;
       
         // System.out.println(cellText);

        }



 return cellText;
 }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
     return "";
 else
 return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e){

e.printStackTrace();
return "row "+rowNum+" or column "+colNum +" does not exist  in xls";
}
}

// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;


sheet = workbook.getSheetAt(index);


row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum=i;
}
if(colNum==-1)
return false;

sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);
if (cell == null)
       cell = row.createCell(colNum);

   // cell style
   //CellStyle cs = workbook.createCellStyle();
   //cs.setWrapText(true);
   //cell.setCellStyle(cs);
   cell.setCellValue(data);

   fileOut = new FileOutputStream(path);

workbook.write(fileOut);

   fileOut.close();

}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}


// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url){
//System.out.println("setCellData setCellData******************");
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;


sheet = workbook.getSheetAt(index);
//System.out.println("A");
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum=i;
}

if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum); //ashish
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);
if (cell == null)
       cell = row.createCell(colNum);

   cell.setCellValue(data);
   XSSFCreationHelper createHelper = workbook.getCreationHelper();

   //cell style for hyperlinks
   //by default hypelrinks are blue and underlined
   CellStyle hlink_style = workbook.createCellStyle();
   XSSFFont hlink_font = workbook.createFont();
   hlink_font.setUnderline(XSSFFont.U_SINGLE);
   hlink_font.setColor(IndexedColors.BLUE.getIndex());
   hlink_style.setFont(hlink_font);
   //hlink_style.setWrapText(true);

   XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);
   link.setAddress(url);
   cell.setHyperlink(link);
   cell.setCellStyle(hlink_style);
   
   fileOut = new FileOutputStream(path);
workbook.write(fileOut);

   fileOut.close();

}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}



// returns true if sheet is created successfully else false
public boolean addSheet(String  sheetname){

FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
    fileOut.close();  
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

// returns true if sheet is removed successfully else false if sheet does not exist
public boolean removeSheet(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;

FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();  
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName,String colName){
//System.out.println("**************addColumn*********************");

try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;

XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

sheet=workbook.getSheetAt(index);

row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);

//cell = row.getCell();
//if (cell == null)
//System.out.println(row.getLastCellNum());
if(row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());
     
       cell.setCellValue(colName);
       cell.setCellStyle(style);
     
       fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();  

}catch(Exception e){
e.printStackTrace();
return false;
}

return true;


}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try{
if(!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet=workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
style.setFillPattern(HSSFCellStyle.NO_FILL);

 

for(int i =0;i<getRowCount(sheetName);i++){
row=sheet.getRow(i);
if(row!=null){
cell=row.getCell(colNum);
if(cell!=null){
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;

}
  // find whether sheets exists
public boolean isSheetExist(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
index=workbook.getSheetIndex(sheetName.toUpperCase());
if(index==-1)
return false;
else
return true;
}
else
return true;
}

// returns number of columns in a sheet
public int getColumnCount(String sheetName){
// check if sheet exists
if(!isSheetExist(sheetName))
return -1;

sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);

if(row==null)
return -1;

return row.getLastCellNum();



}
//String sheetName, String testCaseName,String keyword ,String URL,String message
public boolean addHyperLink(String sheetName,String screenShotColName,String testCaseName,int index,String url,String message){
//System.out.println("ADDING addHyperLink******************");

url=url.replace('\\', '/');
if(!isSheetExist(sheetName))
return false;

   sheet = workbook.getSheet(sheetName);
 
   for(int i=2;i<=getRowCount(sheetName);i++){
    if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){
    //System.out.println("**caught "+(i+index));
    setCellData(sheetName, screenShotColName, i+index, message,url);
    break;
    }
   }


return true;
}
public int getCellRowNum(String sheetName,String colName,String cellValue){

for(int i=2;i<=getRowCount(sheetName);i++){
    if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
    return i;
    }
   }
return -1;

}

// to run this on stand alone
public static void main(String arg[]) throws IOException{

//System.out.println(filename);
Xls_Reader datatable = null;


datatable = new Xls_Reader("H:\\Student_Selenium_Workspaces\\Framework_Weekend\\src\\Framework_XL_Files\\Controller.xlsx");
for(int col=0 ;col< datatable.getColumnCount("TC5"); col++){
System.out.println(datatable.getCellData("TC5", col, 1));
}
}


}




package Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import junit.framework.Assert;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.events.EventFiringWebDriver;

import Data.Xls_Reader;
import Utils.TestUtills;

public class TestBase {

public static WebDriver dr;
public static EventFiringWebDriver driver;
public static Xls_Reader Data;
public static Properties OR = new Properties();
public static Properties Config = new Properties();
public static Properties AppText = new Properties();
public static boolean loginFlag = false;

public static void Initialize() throws IOException {
Data = new Xls_Reader(System.getProperty("user.dir") + "//src//Data//Data.xlsx");
// System.out.println("Data ::" +Data.path);

File f = new File(System.getProperty("user.dir") + "//src//Config//Config.properties");
FileInputStream FI = new FileInputStream(f);
Config.load(FI);

f = new File(System.getProperty("user.dir") + "//src//Config//OR.properties");
FI = new FileInputStream(f);
OR.load(FI);

f = new File(System.getProperty("user.dir") + "//src//Config//AppText.properties");
FI = new FileInputStream(f);
AppText.load(FI);

}

public static WebElement getWebElement(String locator) throws IOException {

String[] splitlocator = locator.split("_");

try {
if (splitlocator[0].contains("xpath")) {
return driver.findElement(By.xpath(OR.getProperty(locator)));
} else if (splitlocator[0].contains("css")) {
return driver.findElement(By.cssSelector(OR.getProperty(locator)));
} else if (splitlocator[0].contains("name")) {
return driver.findElement(By.name(OR.getProperty(locator)));
} else if (splitlocator[0].contains("plink")) {
return driver.findElement(By.partialLinkText(OR.getProperty(locator)));
} else if (splitlocator[0].contains("link")) {
return driver.findElement(By.linkText(OR.getProperty(locator)));
} else if (splitlocator[0].contains("id")) {
return driver.findElement(By.id(OR.getProperty(locator)));
} else if (splitlocator[0].contains("class")) {
return driver.findElement(By.className(OR.getProperty(locator)));
} else if (splitlocator[0].contains("")) {

}

} catch (Exception e) {
e.printStackTrace();
TestUtills.getScreenShot(locator);
Assert.assertTrue(locator + "not found", false);
}

return null;
}

}



// test case implementation


package Test.Suite1;

import Data.Xls_Reader;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
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.openqa.selenium.support.ui.Select;

import Test.TestBase;
import Utils.TestUtils;


//step 1
@RunWith(Parameterized.class)
public class RegistrationTest extends TestBase{


// step 2
String firstname;
String lastname;
String email;
String telephone;
String address1;
String city;
String postcode;
String country;
String state;
String password;
String confirmationpassword;
// step 3
public RegistrationTest(String firstname,String lastname,String email,String telephone,String address1,String city,String postcode,String country,String state,String password,String confirmationpassword) {
this.firstname=firstname;
this.lastname=lastname;
this.email=email;
this.telephone=telephone;
this.address1=address1;
this.city=city;
this.postcode=postcode;
this.country=country;
this.state=state;
this.password=password;
this.confirmationpassword=confirmationpassword;
}
// step 4
@Parameters
public static Collection<Object[]> getData() throws IOException {
Initialize();
return Arrays.asList(TestUtils.getData("RegistrationTest"));
}
@BeforeClass
public static void initBrowser() {
dr = new FirefoxDriver();
driver = new EventFiringWebDriver(dr);
System.out.println("In initBrowser---------------------------");
}
@Test
public void TestRegistrationForm() throws InterruptedException, IOException {

getWebElement("plink_reg_create_account_link").click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// first name
getWebElement("xpath_reg_firstname_input").sendKeys(firstname);

// last name
getWebElement("css_reg_lastname_input").sendKeys(lastname);
// email
getWebElement("name_reg_email_input").sendKeys(email);
// telephone
getWebElement("xpath_reg_telephone_input").sendKeys(telephone);
// address1
getWebElement("css_reg_address_1_input").sendKeys(address1);
// city 
getWebElement("xpath_reg_city_input").sendKeys(city);
//post code 
getWebElement("css_reg_postcode_input").sendKeys(postcode);
// country
//driver.findElement(By.xpath("//*[@id='country_id']")).sendKeys(country);
Select countryEle = new Select(getWebElement("xpath_reg_country_dropdown"));
countryEle.selectByVisibleText(country);
Thread.sleep(1000L);
System.out.println("selecting state");
// state
//driver.findElement(By.xpath("//*[@id='zone_id']")).sendKeys(state);
Select stateEle = new Select(getWebElement("xpath_reg_state_dropdown"));
stateEle.selectByIndex(2);

// password
getWebElement("xpath_reg_password_input").sendKeys(password);
// confirmation password
getWebElement("xpath_reg_confirmpassword_input").sendKeys(confirmationpassword);
getWebElement("xpath_reg_agree_checkbox").click();
// submit
getWebElement("xpath_reg_confirmpassword_input").submit();
try {
String successMsg = driver.findElement(By.xpath(OR.getProperty("xpath_reg_success_msg_text"))).getText();
if(!successMsg.equals(AppText.getProperty("xpath_reg_success_msg_text"))) {
// capture the screen shot
TestUtils.getScreenShot("RegistrationTestFailed_"+email);
//  report error
Assert.assertTrue("Actual text "+successMsg+" is not same as expected text "+AppText.getProperty("xpath_reg_success_msg_text"), false);
}
}catch(Throwable t) {
// capture the screen shot
TestUtils.getScreenShot("RegistrationTest_xpath_reg_success_msg_text_"+email);
// report error
Assert.assertTrue("xpath_reg_success_msg_text not found", false);
}
TestUtils.logOut();
}

@Before
public void openSite() {
driver.get("http://google.com");
}

@AfterClass
public static void quitBrowser() {
System.out.println("In quitBrowser---------------------------");
driver.quit();
}
}

No comments:

Post a Comment