Friday, August 28, 2015

Upload and Download file using AutoIT and Robots


 Upload with AutoIT:

Upload_File()
Func Upload_File()
   $File_Path = $cmdline[1]

 ;MsgBox(0,"Temp",$File_Path,"Temp")
   Sleep(5000)
   if WinExists("[CLASS:#32770]") Then 
   WinActivate("[CLASS:#32770]")
   ControlSetText("[CLASS:#32770]", "", "[ID:1148]", $File_Path)
   ;MsgBox(0,"Temp","Temp","Temp")
   Sleep(2000)
   ControlClick("[CLASS:#32770]", "", "[ID:1]")
   ControlClick("[CLASS:#32770]", "", "[ID:1]")
   EndIf
 EndFunc

(OR)
ControlFocus(“File Upload”,””,”Edit1″)
ControlSetText(“File Upload”,””,”Edit1″,$CmdLine[1])
ControlClick(“File Upload”,””,”Button1″)

Save the above script with '.au3' and compiling it into a standalone executable.

We can pass multiple arguments in AutoIT.
$CmdLine[0] ; Contains the total number of items in the array.
$CmdLine[1] ; The first parameter.
$CmdLine[2] ; The second parameter.
$CmdLine[nth] ; The nth parameter e.g. 10 if the array contains 10 items.


How to get the window element information:
1.Open'Au3Info.exe' file
2.Drag the finder tool on the " File Name" box element of file upload window to find the basic attributes info.
3.Get the required element info (Title, Class, Instance..)

How to compile AutoIt file '.au3' to '.exe' file:
There are multiple ways to do that. But the simple way is using Right Click option. To do that, we will follow the below steps

Step-1: Navigate to the .au3 file that you wish to compile.
Step-2: Select the file and Right-click on it to access the pop-up menu.
Step-3: You will get an option as 'Compile Script'. Click on 'Compile Script.
Step-4: You will get .exe file generated.

Run it like :
Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");
(OR)
Runtime.getRuntime().exec("AutoITCompiled.exe filepath"+" "+UploadFilePath");
(OR)
Runtime.getRuntime().exec(cmd /c start "+"AutoITCompiled.exe filepath"+" "+UploadFilePath");

Download with AutoIT:

WinWaitActive("Opening", "", 60)
If WinExists("Opening") Then
   WinFlash("Opening","", 4, 500) ; Just to Flash the window
   Send("!s")
   Send("{ENTER}")
   Sleep(10000)
EndIf

Run it Like:

Runtime.getRuntime().exec("E:\\AutoIT\\FileDownload.exe");
(OR)
Runtime.getRuntime().exec("cmd /c start " + AutoIt.exeFilePath+ " ");
 
 Robots:

public void uploadFile(String absolutePath)  {
        if (absolutePath != null) {
            try {
                // StringSelection is a class that can be used for copy and
                // paste operations.
                StringSelection stringSelection = new StringSelection(absolutePath);
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
                 //native key strokes for CTRL, V and ENTER keys
                Robot robot = new Robot();
                robot.keyPress(KeyEvent.VK_ENTER);
                robot.keyRelease(KeyEvent.VK_ENTER);
                robot.keyPress(KeyEvent.VK_CONTROL);
                robot.keyPress(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_CONTROL);
                robot.delay(1000);
                robot.keyPress(KeyEvent.VK_ENTER);
                robot.keyRelease(KeyEvent.VK_ENTER);
                robot.delay(5000);
            } catch (AWTException e) {
                System.out.println("Failed to upload a file" + absolutePath + " Please try by some delay ");
            }
        } else {
            System.out.println("please provide file path");
        }
    }

USAGE of Jacob API:


Pre-requisites:
  1. Create a simple Selenium Webdriver project or add a TestNG project in Eclipse(or any IDE of any choice).
  2. Download the AutoIt software from here and install it on your system. If you are using a 64-bit system, then do select the suitable option during installation. Also, make sure you just don’t copy the AutoIt files from another system, instead, let the installer run, as it not only copies all the required files but registers them with your system. It’s helpful in the application where you use AutoIt interfaces to work with the window based dialogs.
  3. Download the AutoItX4Java jar file which is a Java API wrapper for the AutoIt functions. Use the Eclipse <Build Path->Configure> option to Add this file as an external library in your project
  4. Download the Jacob library package, it comes as a zip file. Unzip the <jacob-1.18.zip> file. You’ll the find the following files under the <jacob-1.18> folder.
  • jacob.jar.
  • jacob-1.18-x64.dll.
  • jacob-1.18-x86.dll.
Add the <jacob.jar> as an external jar into your Eclipse project while copy/paste the <jacob-1.18-x86.dll> to your project. It’ll get the DLL file added to it.
Now, time to begin out work.
Jacob will give you full control to write Java code that can manage any GUI Window.
But you need to make sure all the prerequisites are in place before you get to run the below code.

    public void UploadFileUsingJacobDll()
       throws InterruptedException {
      String workingDir = System.getProperty("user.dir");
      final String jacobdllarch = System.getProperty("sun.arch.data.model")
        .contains("32") ? "jacob-1.18-x86.dll" : "jacob-1.18-x64.dll";
      String jacobdllpath = workingDir + "\\" + jacobdllarch;
      File filejacob = new File(jacobdllpath);
      System.setProperty(LibraryLoader.JACOB_DLL_PATH,
        filejacob.getAbsolutePath());
      AutoItX uploadWindow = new AutoItX();
      driver = new FirefoxDriver();
      String filepath = workingDir + "\\SeleniumWebdriverUploadFile.html";
      driver.get(filepath);
      Thread.sleep(1000);
      driver.findElement(By.id("uploadfile")).click();
      Thread.sleep(1000);
      if (uploadWindow.winWaitActive("File Upload", "", 5)) {
       if (uploadWindow.winExists("File Upload")) {
        uploadWindow.sleep(100);
        uploadWindow.send(filepath);
        uploadWindow.controlClick("File Upload", "", "&Open");
       }
      }
     }

Wednesday, August 26, 2015

Retry executing only Failed Tests using TestNG

package com.pack.test;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class Retry implements IRetryAnalyzer {
    private int retryCount = 0;
    private int maxRetryCount = 1;
// Below method returns 'true' if the test method has to be retried else 'false'
//and it takes the 'Result' as parameter of the test method that just ran
    public boolean retry(ITestResult result) {
        if (retryCount < maxRetryCount) {
            System.out.println("Retrying test " + result.getName() + " with status "
                    + getResultStatusName(result.getStatus()) + " for the " + (retryCount+1) + " time(s).");
            retryCount++;
            return true;
        }
        return false;
    }
   
    public String getResultStatusName(int status) {
     String resultName = null;
     if(status==1)
      resultName = "SUCCESS";
     if(status==2)
      resultName = "FAILURE";
     if(status==3)
      resultName = "SKIP";
  return resultName;
    }
}

package com.pack.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
public class RetryListener implements IAnnotationTransformer {
 @Override
 public void transform(ITestAnnotation testannotation, Class testClass,
   Constructor testConstructor, Method testMethod) {
  IRetryAnalyzer retry = testannotation.getRetryAnalyzer();
  if (retry == null) {
   testannotation.setRetryAnalyzer(Retry.class);
  }
 }
}


       
 

Tuesday, August 18, 2015

Separate ReportNG Report Table to send through mail


String filePath = System.getProperty("user.dir")
     + "\\test-output\\html\\overview.html";
   Document document = Jsoup.parse(new File(filePath), "UTF-8");
   Elements tableContentElement = document
     .select("table[class=overviewTable]");
   String tableHtml = tableContentElement.html();
   String[] msgBody = new String[] { config.getProperty("emailBody"),
     tableHtml, config.getProperty("emailSignature") };

Tuesday, August 11, 2015

How to add screenshot in ReportNG HTML report


public void catchExceptions(ITestResult result) {
    System.out.println("result" + result);
    String methodName = result.getName();
    System.out.println(methodName);
    if (!result.isSuccess()) {
        try {
        String failureImageFileName =  new SimpleDateFormat("MM-dd-yyyy_HH-ss").format(new GregorianCalendar().getTime())+ ".png";
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(failureImageFileName));

// To add screenshot to ReportNG HTML report as a link
  private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
            System.setProperty(ESCAPE_PROPERTY, "false");
   Reporter.setCurrentTestResult(result);
   Reporter.log("failureImageFileName+ "\"> Screenshot
");
(OR)
// To add screenshot to ReportNG HTML report as a image
private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
            System.setProperty(ESCAPE_PROPERTY, "false");
Reporter.log("" +"");


        } catch (IOException e1) {
            e1.printStackTrace();
        }
}
}

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