Wednesday, December 16, 2015

Updating testng xml at runtime


import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class WebdriverITestListener implements ITestListener {
boolean ischecked=true;
public static XmlSuite suite ;
@Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailure(ITestResult test) {
// TODO Auto-generated method stub
}
@Override
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestStart(ITestResult test) {
// TODO Auto-generated method stub
String browserName=test.getMethod().getXmlTest().getParameter("browserName");
if(ischecked)
{
List tests = new ArrayList();
XmlTest testsuite = new XmlTest(test.getMethod().getXmlTest().getSuite());
testsuite.setName("defalut");

List xmlclasses = new ArrayList();
xmlclasses.add(new XmlClass("TESTCASE NAME"));

testsuite.addParameter("browserName","firefox");
testsuite.setXmlClasses(xmlclasses);
tests.add(testsuite);
suite.setTests(tests);
test.getMethod().getXmlTest().setXmlSuite(suite);
ischecked=false;
}
System.out.println(test.getMethod().getXmlTest().getSuite()+"  ------------------   ");
WebDriver driver;
try {
driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStart(ITestContext test) {
- hide quoted text -

}
}

Thursday, December 10, 2015

TestNG Parallel Execution

  • Methods: This will run the parallel tests on all @Test methods in TestNG.
  • Tests: All the test cases present inside the <test> tag will run with this value.
  • Classes: All the test cases present inside the classes that exist in the XML will run in parallel.

package com.parallel;
import org.testng.annotations.Test;

public class TestParallelOne {

    @Test
    public void testCaseOne() {
        //Printing Id of the thread on using which test method got executed
        System.out.println("Test Case One with Thread Id:- "
                + Thread.currentThread().getId());
    }

    @Test
    public void testCaseTwo() {
        ////Printing Id of the thread on using which test method got executed
        System.out.println("Test Case two with Thread Id:- "
                + Thread.currentThread().getId());
    }
}

Running test methods parallelly in TestNG using Selenium
http://testng.org/testng-1.0.dtd">
<suite name="Parallel test suite" parallel="methods" thread-count="2">
  <test name="Regression 1">
    <classes>
      <class name="com.parallel.TestParallelOne"/>
    </classes>
  </test>
</suite>

Running tests parallelly in TestNG using Selenium

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name = "Parallel Testing Suite" parallel = "tests" thread-count = "2">
   <test name = "Parallel Tests1">
      <classes>
        <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
   <test name = "Parallel Tests2">
      <classes>
         <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
</suite>
 Running test classes parallelly in TestNG using Selenium
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name = "Parallel Testing Suite">
   <test name = "Parallel Tests" parallel = "classes" thread-count = "2">
      <classes>
         <class name="com.parallel.TestParallelOne"/>
         <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
</suite>
   
 

Tuesday, October 27, 2015

Delete files in a Directory?

/**
     * Delete file
     *
     * @param filePath
     */
    public void deleteFile(String filePath) throws Exception {
        try {
            File file = new File(filePath);

            if (file.delete()) {
                System.out.println(file.getName() + " is deleted..!");
            }
        } catch (Exception e) {
            throw new Exception(">>>Error while deleting " + filePath + " file :<<<" + e.toString());
        }
    }
 
public void deleteFilesFromFolder(File directoryPath) {
        String[] myFiles;
        if (directoryPath.isDirectory()) {
            myFiles = directoryPath.list();
            for (int i = 0; i < myFiles.length; i++) {
                File myFile = new File(directoryPath, myFiles[i]);
                myFile.delete();
            }
        }
    }

EX: File directoryPath = new File("C:\\Example");

Thursday, September 10, 2015

Using log4j in Java Program

public static Logger logger_name = Logger.getLogger(classname.class);

PropertyConfigurator.configure(System.getProperty("user.dir") + "\\config\\log4j.properties");

EX:
public static Logger APP_LOGS = Logger.getLogger(DriverScript.class.getName());

log4j.properties:

# Define the root logger with appender file
log = TestOutput/Logs
log4j.rootLogger = INFO, FILE
# log4j.rootLogger = INFO,console, FILE ( To print all logging messages to both the console and a log file)

# Define the file appender(RollingFileAppender OR ConsoleAppender(to print in console))
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=${log}/SFDCTests.html

# Constrole the maximum log file size
log4j.appender.FILE.maxFileSize=10000KB

# Archive log files (one backup file here)
log4j.appender.FILE.maxBackupIndex=3

# Define the layout for file appender
(HTMLLayout OR PatternLayout)
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=Logger For SFDC Test Cases
log4j.appender.FILE.layout.LocationInfo=true

#do not append the old file. Create a new log file everytime
log4j.appender.FILE.Append=false
 
#Prevent internal log4j DEBUG messages from polluting the output.
#log4j.logger.org.apache.log4j.PropertyConfigurator=INFO
#log4j.logger.org.apache.log4j.config.PropertySetter=INFO
#log4j.logger.org.apache.log4j.FileAppender=INFO
 

Friday, September 4, 2015

Right Click Function With Selenium Webdriver



public void RightClickAndChooseAnOption()
    {
               
        WebElement oWE=driver.findElement(By.linkText("About Google"));
       
        Actions oAction=new Actions(driver);
        oAction.moveToElement(oWE);
        oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
       
    }

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