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