Wednesday, May 13, 2015

How to Run TestNG xml Programmatically

public static void main(String[] args) {
  TestNG testng = null;
  List suites = null;
  try {
   testing = new TestNG();
   suites = Lists.newArrayList();
         suites.add("D:/Projects/SeleniumTests/testng1.xml");//path to xml..
         suites.add("D:/Projects/SeleniumTests/testng2.xml");//If need to execute more xml files
   testng.setTestSuites(suites);
   testing.run();
  } catch (Exception e) {
   e.printStackTrace();
  }
}


Using Bat File:
D:
cd Projects\SeleniumTests
set MyProjectPath=D:\Projects\SeleniumTests
echo %MyProjectPath%
set classpath=%MyProjectPath%\bin;%MyProjectPath%\lib\*
echo %classpath%
java org.testng.TestNG %MyProjectPath%\testng.xml

Friday, February 13, 2015

Exceptions that may happen in all the webdriver code

Exceptions that may happen in all the webdriver code.
exception selenium.common.exceptions.ElementNotSelectableException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.ElementNotVisibleException(msg=None, screen=None, stacktrace=None)
Thrown to indicate that although an element is present on the DOM, it is not visible, and so is not able to be interacted with.
exception selenium.common.exceptions.ErrorInResponseException(response, msg)
An error has occurred on the server side.
This may happen when communicating with the firefox extension or the remote driver server.
exception selenium.common.exceptions.ImeActivationFailedException(msg=None, screen=None, stacktrace=None)
Indicates that activating an IME engine has failed.
exception selenium.common.exceptions.ImeNotAvailableException(msg=None, screen=None, stacktrace=None)
Indicates that IME support is not available. This exception is thrown for every IME-related method call if IME support is not available on the machine.
exception selenium.common.exceptions.InvalidCookieDomainException(msg=None, screen=None, stacktrace=None)
Thrown when attempting to add a cookie under a different domain than the current URL.
exception selenium.common.exceptions.InvalidElementStateException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.InvalidSelectorException(msg=None, screen=None, stacktrace=None)
Thrown when the selector which is used to find an element does not return a WebElement. Currently this only happens when the selector is an xpath expression is used which is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. “count(//input)”).
exception selenium.common.exceptions.InvalidSwitchToTargetException(msg=None, screen=None, stacktrace=None)
The frame or window target to be switched doesn’t exist.
exception selenium.common.exceptions.MoveTargetOutOfBoundsException(msg=None, screen=None, stacktrace=None)
Indicates that the target provided to the actions move() method is invalid
exception selenium.common.exceptions.NoAlertPresentException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.NoSuchAttributeException(msg=None, screen=None, stacktrace=None)
find_element_by_* can’t find the element.
exception selenium.common.exceptions.NoSuchElementException(msg=None, screen=None, stacktrace=None)
find_element_by_* can’t find the element.
exception selenium.common.exceptions.NoSuchFrameException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.NoSuchWindowException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.RemoteDriverServerException(msg=None, screen=None, stacktrace=None)
exception selenium.common.exceptions.StaleElementReferenceException(msg=None, screen=None, stacktrace=None)
Indicates that a reference to an element is now “stale” — the element no longer appears on the DOM of the page.
exception selenium.common.exceptions.TimeoutException(msg=None, screen=None, stacktrace=None)
Thrown when a command does not complete in enough time.
exception selenium.common.exceptions.UnableToSetCookieException(msg=None, screen=None, stacktrace=None)
Thrown when a driver fails to set a cookie.
exception selenium.common.exceptions.UnexpectedTagNameException(msg=None, screen=None, stacktrace=None)
Thrown when a support class did not get an expected web element
exception selenium.common.exceptions.WebDriverException(msg=None, screen=None, stacktrace=None)

Thursday, January 29, 2015

XLS Reading for DDF

package com.stta.utility;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;



public class Read_XLS {   
    public  String filelocation;
    public  FileInputStream ipstr = null;
    public  FileOutputStream opstr =null;
    private HSSFWorkbook wb = null;
    private HSSFSheet ws = null;   
   
    public Read_XLS(String filelocation) {       
        this.filelocation=filelocation;
        try {
            ipstr = new FileInputStream(filelocation);
            wb = new HSSFWorkbook(ipstr);
            ws = wb.getSheetAt(0);
            ipstr.close();
        } catch (Exception e) {           
            e.printStackTrace();
        }
       
    }
   
    //To retrieve No Of Rows from .xls file's sheets.
    public int retrieveNoOfRows(String wsName){       
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return 0;
        else{
            ws = wb.getSheetAt(sheetIndex);
            int rowCount=ws.getLastRowNum()+1;       
            return rowCount;       
        }
    }
   
    //To retrieve No Of Columns from .xls file's sheets.
    public int retrieveNoOfCols(String wsName){
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return 0;
        else{
            ws = wb.getSheetAt(sheetIndex);
            int colCount=ws.getRow(0).getLastCellNum();           
            return colCount;
        }
    }
   
    //To retrieve SuiteToRun and CaseToRun flag of test suite and test case.
    public String retrieveToRunFlag(String wsName, String colName, String rowName){
       
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return null;
        else{
            int rowNum = retrieveNoOfRows(wsName);
            int colNum = retrieveNoOfCols(wsName);
            int colNumber=-1;
            int rowNumber=-1;           
           
            HSSFRow Suiterow = ws.getRow(0);               
           
            for(int i=0; i                if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
                    colNumber=i;                   
                }                   
            }
           
            if(colNumber==-1){
                return "";               
            }
           
           
            for(int j=0; j                HSSFRow Suitecol = ws.getRow(j);               
                if(Suitecol.getCell(0).getStringCellValue().equals(rowName.trim())){
                    rowNumber=j;   
                }                   
            }
           
            if(rowNumber==-1){
                return "";               
            }
           
            HSSFRow row = ws.getRow(rowNumber);
            HSSFCell cell = row.getCell(colNumber);
            if(cell==null){
                return "";
            }
            String value = cellToString(cell);
            return value;           
        }           
    }
   
    //To retrieve DataToRun flag of test data.
    public String[] retrieveToRunFlagTestData(String wsName, String colName){
       
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return null;
        else{
            int rowNum = retrieveNoOfRows(wsName);
            int colNum = retrieveNoOfCols(wsName);
            int colNumber=-1;
                   
           
            HSSFRow Suiterow = ws.getRow(0);               
            String data[] = new String[rowNum-1];
            for(int i=0; i                if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
                    colNumber=i;                   
                }                   
            }
           
            if(colNumber==-1){
                return null;               
            }
           
            for(int j=0; j                HSSFRow Row = ws.getRow(j+1);
                if(Row==null){
                    data[j] = "";
                }
                else{
                    HSSFCell cell = Row.getCell(colNumber);
                    if(cell==null){
                        data[j] = "";
                    }
                    else{
                        String value = cellToString(cell);
                        data[j] = value;   
                    }   
                }
            }
           
            return data;           
        }           
    }
   
    //To retrieve test data from test case data sheets.
    public Object[][] retrieveTestData(String wsName){
        int sheetIndex=wb.getSheetIndex(wsName);
        if(sheetIndex==-1)
            return null;
        else{
                int rowNum = retrieveNoOfRows(wsName);
                int colNum = retrieveNoOfCols(wsName);
       
                Object data[][] = new Object[rowNum-1][colNum-2];
       
                for (int i=0; i                    HSSFRow row = ws.getRow(i+1);
                    for(int j=0; j< colNum-2; j++){                   
                        if(row==null){
                            data[i][j] = "";
                        }
                        else{
                            HSSFCell cell = row.getCell(j);   
                   
                            if(cell==null){
                                data[i][j] = "";                           
                            }
                            else{
                                cell.setCellType(Cell.CELL_TYPE_STRING);
                                String value = cellToString(cell);
                                data[i][j] = value;                       
                            }
                        }
                    }               
                }           
                return data;       
        }
   
    }       
   
   
    public static String cellToString(HSSFCell cell){
        int type;
        Object result;
        type = cell.getCellType();           
        switch (type){
            case 0 :
                result = cell.getNumericCellValue();
                break;
               
            case 1 :
                result = cell.getStringCellValue();
                break;
               
            default :
                throw new RuntimeException("Unsupportd cell.");           
        }
        return result.toString();
    }
   
    //To write result In test data and test case list sheet.
    public boolean writeResult(String wsName, String colName, int rowNumber, String Result){
        try{
            int sheetIndex=wb.getSheetIndex(wsName);
            if(sheetIndex==-1)
                return false;           
            int colNum = retrieveNoOfCols(wsName);
            int colNumber=-1;
                   
           
            HSSFRow Suiterow = ws.getRow(0);           
            for(int i=0; i                if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
                    colNumber=i;                   
                }                   
            }
           
            if(colNumber==-1){
                return false;               
            }
           
            HSSFRow Row = ws.getRow(rowNumber);
            HSSFCell cell = Row.getCell(colNumber);
            if (cell == null)
                cell = Row.createCell(colNumber);           
           
            cell.setCellValue(Result);
           
            opstr = new FileOutputStream(filelocation);
            wb.write(opstr);
            opstr.close();
           
           
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
   
    //To write result In test suite list sheet.
    public boolean writeResult(String wsName, String colName, String rowName, String Result){
        try{
            int rowNum = retrieveNoOfRows(wsName);
            int rowNumber=-1;
            int sheetIndex=wb.getSheetIndex(wsName);
            if(sheetIndex==-1)
                return false;           
            int colNum = retrieveNoOfCols(wsName);
            int colNumber=-1;
                   
           
            HSSFRow Suiterow = ws.getRow(0);           
            for(int i=0; i                if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
                    colNumber=i;                   
                }                   
            }
           
            if(colNumber==-1){
                return false;               
            }
           
            for (int i=0; i                HSSFRow row = ws.getRow(i+1);               
                HSSFCell cell = row.getCell(0);   
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String value = cellToString(cell);   
                if(value.equals(rowName)){
                    rowNumber=i+1;
                    break;
                }
            }       
           
            HSSFRow Row = ws.getRow(rowNumber);
            HSSFCell cell = Row.getCell(colNumber);
            if (cell == null)
                cell = Row.createCell(colNumber);           
           
            cell.setCellValue(Result);
           
            opstr = new FileOutputStream(filelocation);
            wb.write(opstr);
            opstr.close();
           
           
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

Tuesday, December 30, 2014

Selecting a date from Datepicker using Selenium WebDriver

  driver.switchTo().frame(0); 
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
 //Click on textbox so that datepicker will come 
  driver.findElement(By.id("datepicker")).click(); 
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); 
  //Click on next so that we will be in next month 
  driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click(); 
   
  /*DatePicker is a table.So navigate to each cell  
   * If a particular cell matches value 13 then select it 
   */ 
  WebElement dateWidget = driver.findElement(By.id("ui-datepicker-div")); 
  List rows=dateWidget.findElements(By.tagName("tr")); 
  List columns=dateWidget.findElements(By.tagName("td")); 
   
  for (WebElement cell: columns){ 
   //Select 13th Date  
   if (cell.getText().equals("13")){ 
   cell.findElement(By.linkText("13")).click(); 
   break; 
   } 
  }  
 
  (OR)
 
   WebElement dateWidget;
 List rows;
 List columns;
 List 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;

 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;
  }
 }
 }

 
Datepicker

Tuesday, December 23, 2014

@DataProvider Annotation in TestNG

 
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderExample {

//This test method declares that its data should be supplied by the Data Provider
// "getdata" is the function name which is passing the data
// Number of columns should match the number of input parameters
 
@Test(dataProvider="getData")
public void setData(String username, String password)
{
System.out.println("you have provided username as::"+username);
System.out.println("you have provided password as::"+password);
}

@DataProvider
public Object[][] getData()
{
//Rows - Number of times your test has to be repeated.
//Columns - Number of parameters in test data.
Object[][] data = new Object[3][2];

// 1st row
data[0][0] ="sampleuser1";
data[0][1] = "abcdef";

// 2nd row
data[1][0] ="testuser2";
data[1][1] = "zxcvb";
// 3rd row
data[2][0] ="guestuser3";
data[2][1] = "pass123";

return data;
}
}

Tuesday, October 21, 2014

Java Code to convert Html to PDF Using wkhtmltopdf

Basic thing to do:
     Need to install all the basic stuffs for java and download wkhtmltopdf from below link
     Link : http://code.google.com/p/wkhtmltopdf/downloads/detail?name=wkhtmltopdf-0.9.9-installer.exe&
Source Code :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Java_pdf {
   public static void main(String[] args) throws IOException {
        try
        {
            String htmlFilePath = "D:/html2pdf/a.html";
            String pdfFilePath = "D:/html2pdf/test.pdf";
            ProcessBuilder pb = new ProcessBuilder("C:/Program Files/wkhtmltopdf/wkhtmltopdf.exe", htmlFilePath, pdfFilePath);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
          
            String line = inStreamReader.readLine();
          
                    while(line != null)
                    {
                        System.out.println(line);
                        line = inStreamReader.readLine();
                    }
        }
        catch(Exception e)
        {
            System.out.println("coming-->"+e.getMessage() );
        }
    }
}

Saturday, September 13, 2014

JFree Chart for Test Case Execution Status


import java.io.File;
import java.io.IOException;
import org.jfree.chart.*;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;


 public void pieChartReport()

 {

  // Creating a simple pie chart with 
DefaultPieDataset dataset = new DefaultPieDataset();

   dataset.setValue("PASSED", new Integer(60));
   dataset.setValue("FAILED", new Integer(25));
   dataset.setValue("SKIPPED", new Integer(10));
   dataset.setValue("NOTRUN", new Integer(5));


  JFreeChart piechart = ChartFactory.createPieChart("Test Cases Execution  Status", dataset, true, true, false);
PiePlot plot = (PiePlot) piechart.getPlot();

PieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator("{0} = {2}", new DecimalFormat("0"),new DecimalFormat("0.00%"));

       
        plot.setLabelGenerator(generator);
        plot.setBackgroundPaint(Color.WHITE);
        plot.setSectionPaint("PASSED", Color.GREEN);
        plot.setSectionPaint("FAILED", Color.RED);
        plot.setSectionPaint("SKIPPED", Color.BLUE);
        plot.setSectionPaint("NOTRUN", Color.YELLOW);

   try {

   ChartUtilities.saveChartAsJPEG(new File(

"D:\\simplePiechart.jpg"), 1, piechart, 640, 480);

  } catch (IOException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }
 
Note: Required JFreeChart and JCommon jars.