Wednesday, May 21, 2014

Selenium : Run Test Cases on iOS or Android devices

Run Test Cases on iOS or Android devices

You can execute test cases on Android or iOs or any other mobile platforms on your Test NG Selenium Framework by using a tool called Seetest by Experitest.Here is what I think about the tool , I've listed them in points :

  1. It is a Paid tool . But you get 15 days trail version .
  2. Most asked question : Can you run the same code cross multiple devices : Answer is "YES" .You can use the same code across multiple devices and across platforms. Example you can record a script in iOs and Run the same on Android.
  3. Devices supported : Android, iOs ,BlackBerry and Windows.
  4. Applications supported: Native , web and Hybrid.
  5. The tool is specialized to convert gestures into code by using builtin code generator.
  6. Depending on the framework and language  , user can select the type of code conversion from the drop down .Ex: Java TestNG , Java Junit , C#, VB etc .,once done, the user can directly Copy paste the code into his framework . (Note : User is required to import the library files present in SeeTest installation Folder>Client . Ex: If you are using Java TestNg framework then , Goto Seetest>Client>Java and import all Jar files into your project .Now on Seetest GUI convert the code to Java TestNG and simply copy paste the code into Eclipse and Run. )
  7. Seetest also gives flexibility to convert into QTP or UFT script as well.
  8. Apart from usual recognition of Elements , Seetest has another rather unique way of recognition of Elements ie.," Image Recognition": Here a small snapshot of the element is saved in repository and used as reference. 
  9. User can execute Test Cases on 3 physical devices simultaneously (for a trial version).
  10. To make the code cross compatible , Seetest has a neat solution. SeeTest object repository can store different locator ids for the same element for different platforms. ie., A button might have specific id in Android and another id in iOS.Here the user is given the flexibility to store both ids pointing to same element.So during run time , depending on the Device which the test is running Seetest will select appropriate ids for the element from the repository.
As far as my analysis goes Seetest is the best in market (I've tried Ranorex , TestComplete ,Appium etc.,) if you are looking for re-usability across  Device Platform Automation Testing while keeping whole testing process reliable.

For Help
 General Help

For Android refer :
 Android Help
 video Demo

For iOs : (Note: For iOS 6 and above you need to Instrument the app if your AUT is a Native or Hybrid)
iOs Help

Selenium : Skip or Disable a Test or any Annotation



 To disable or skip a test or any Test NG annotation .  

 

 

Syntax: @Annotation(enabled=false)
Ex: @Test(enabled=false)   or @BeforeMethod(enabled=false)

Thursday, May 15, 2014

Selenium : One click Selenium suite execution using Bat file

One click Selenium suite execution using Bat file

Pre-Req:

  1. Works for Selenium TestNG Suite.
  2. ANT+build.xml should have been implemented in the framework.
Note : Your build.xml,TestNG.xml will all be in the same location of the project.

Steps :

  • Goto to your project , where your build.xml resides.
  • Create a new text file there .
  • Copy the below code and paste it inside the text file.
  • Rename the extension as ".bat"

Code here :

echo.
rem *** Created By Deepak ******
echo.

call ant -buildfile build.xml setClassPath init all clean compile build run

echo.
echo  **** view your Test-NG results in path "your_project\test-output\index.html" ********
echo.
echo  *** you can remove wait screen , by deleting pause command in this file ****
echo.
pause


Selenium : Simple build.xml Code for TestNG

Simple build.xml Code for TestNG

Below is the code to run TestNG suite using build.xml.Note that this does not generate xslt report or you can say below code is a cleaned up version without xslt reporting.

(You can also auto generate using Eclipse :
File -> Export -> General -> Ant Buildfiles and specify the file name, project, etc. )

Steps below:

  1. Open Eclipse >Navigate to your project.
  2. On your project folder > Right ck > Create New File  and Name it as "build.xml"
  3. Copy paste the below code with required modifications.
Note : TestNG.xml is considered to directly reside in the project folder (you can copy paste the TestNG.xml into your project folder ).

Code Below:


<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE project [
]>

<project name="Learning TestNG" default="usage" basedir="."> 

<!-- ========== Initialize Properties =================================== -->
    <property environment="env"/>   
    <property name="work.home" value="${basedir}"/>
    <property name="work.jars" value="D:\shared\selenium_tools\selenium-java-2.39.0\selenium-2.39.0\libs"/><!--Change value here , to locations where all Jar files are located-->
    <property name="test.dest" value="${work.home}/build"/>
    <property name="test.src" value="${work.home}/src/"/><!--Folder which contains Java files , folder itself might contain many packages-->


    <target name="setClassPath" unless="test.classpath">
        <path id="classpath_jars">
            <fileset dir="${work.jars}" includes="*.jar"/>
        </path>
       
        <path id = "log4j">  
            <fileset dir = "${log4j.dir}">  
                <include name = "log4j.properties" />  
            </fileset>  
        </path>
       
        <pathconvert pathsep=":"
            property="test.classpath"
            refid="classpath_jars"/>
    </target>

    <target name="init" depends="setClassPath">
        <tstamp>
            <format property="start.time" pattern="MM/dd/yyyy hh:mm aa" />
        </tstamp>
        <condition property="ANT"
            value="${env.ANT_HOME}/bin/ant.bat"
            else="${env.ANT_HOME}/bin/ant">
                    <os family="windows" />
        </condition>
        <taskdef name="testng" classpath="${test.classpath}"
               classname="org.testng.TestNGAntTask" />
   
    </target>
 
    <!-- all -->
    <target name="all">
    </target>

    <!-- clean -->
    <target name="clean">
        <delete dir="${test.dest}"/>
    </target>

    <!-- compile -->
    <target name="compile" depends="init, clean" >
        <delete includeemptydirs="true" quiet="true">
            <fileset dir="${test.dest}" includes="**/*"/>
        </delete>
        <echo message="making directory..."/>
        <mkdir dir="${test.dest}"/>
        <echo message="classpath------: ${test.classpath}"/>
        <echo message="compiling..."/>
        <javac
            debug="true"
            destdir="${test.dest}"
            srcdir="${test.src}"
            target="1.5"
            classpath="${test.classpath}"
        >
        </javac>
      </target>

    <!-- build -->
    <target name="build" depends="init">
    </target>

    <!-- run -->
    <target name="run" depends="compile">
        <testng classpath="${test.classpath}:${test.dest}" suitename="suite1">   
            <xmlfileset dir="${work.home}" includes="testng.xml"/>
        </testng>
    </target>
   
    <target name="usage">
            <echo>
                ant run will execute the test
            </echo>
    </target>

    <path id="test.c">
                <fileset dir="${work.jars}" includes="*.jar"/>

    </path>

    <!-- ****************** targets not used ****************** -->

</project>

Monday, May 12, 2014

Java : SORTING

SORTING

1. Selection Sort : 

 1st  iteration -  find the least value (for ascending ) and swap it with the first element in the array.
2nd iteration - find the 2nd lowest starting (start searching from 2nd element) and swap it with 2nd element in the array.


import javax.swing.JOptionPane;

//SELECTION SORT IN ASCENDING ORDER
public class Sort {

    public static void main(String[] args) {
       
        int a[]={34,67,9,4,3,2,1};   //ARREY TO BE SORTED
        int i,j,small=a[0],temp;
        Boolean flag=false;
        String s="";
       
//        JOptionPane.showMessageDialog(null, a.length);
        for (i=0;i<=a.length-2;i++)
        {
            for(j=i;j<=a.length-(2+i);j++)
            {
                if(a[j+1]<a[j])
                {
                    small=a[j+1];
                    flag=true;
                }
                   
            }
           
            if(flag==true)
            {
                flag=false;
                temp=a[i];
                a[i]=small;
                a[j]=temp;                               
            }                       
        }
       
        for(i=0;i<=a.length-1;i++)
             s=s+a[i]+",";
       
        System.out.print(s);

    }

}


 2. Bubble Sort :

Works by swapping technique, where each pair of value is swapped depending on ascending r descending order required.  If there are 'n' elements , then there will n-1 iteartionsie., it there are 5 elements then there will be 4 iterations .If there are 5 elements , the 1st iteration will have 4 comparisons 

Ex : n=5

Iteration = 1 , Comparisons =4  ( At the end of 1st round the largest value is pushed to the bottom).

Iterations = 2 , Comparisons = 3

public class Bubble {

    public static void main(String[] args) {
       
        int a[]={4,3,2,1}; // ARRAY TO BE SORTED
        int temp;
        String s="";
               
       
        for(int i=0;i<a.length-1;i++)
        {
            for(int j=0;j<a.length-1;j++)
            {
                if(a[j]>a[j+1])
                {
                    temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                   
                }
            }
        }
       
        for(int i=0;i<a.length;i++)
        {
            s=s+a[i]+",";
        }
        System.out.print(s);

    }

}

 3.Quick Sort (http://www.programcreek.com/2012/11/quicksort-array-in-java/) :

 
public class QuickSort {
 
 public static void main(String[] args) {
  int[] x = { 9, 2, 4, 7, 3, 7, 10 };
  printArray(x);
 
  int low = 0;
  int high = x.length - 1;
 
  quickSort(x, low, high);
  printArray(x);
 }
 
 public static void quickSort(int[] arr, int low, int high) {
 
  if (arr == null || arr.length == 0)
   return;
 
  if (low >= high)
   return;
 
  //pick the pivot
  int middle = low + (high - low) / 2;
  int pivot = arr[middle];
 
  //make left < pivot and right > pivot
  int i = low, j = high;
  while (i <= j) {
   while (arr[i] < pivot) {
    i++;
   }
 
   while (arr[j] > pivot) {
    j--;
   }
 
   if (i <= j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    i++;
    j--;
   }
  }
 
  //recursively sort two sub parts
  if (low < j)
   quickSort(arr, low, j);
 
  if (high > i)
   quickSort(arr, i, high);
 }
 
 public static void printArray(int[] x) {
  for (int a : x)
   System.out.print(a + " ");
  System.out.println();
 }
}

 

Thursday, May 8, 2014

Selenium : Object identification + Reporting +No Halt in 1 statement ,EXECUTION LIKE A BOSS !!

Object identification , LIKE A BOSS !!


I always liked the way QTP identifies the object and error reporting technique used in-case the element was not found . I find it to be more convenient for the automation tester , as he only needed to concentrate only on the reports rather than the inner mechanism.

In the back of my mind I wanted something similar to be implemented in Selenium, as you get so used to the luxurious comforts offered by QTP back in the days. Today I had a little time to spare implemented something similar .

Aim :

  1.  To identify elements as usual using Xpath , id ... what ever.
  2. Incase element not found report it to TestNG . 
  3. Take screenshot and hyper link it in the TestNG and xslt Report.
  4. Quit the current Test case go to next Test Case.
  5. Mechanism should be hidden and rather everything should be taken by 1line of code. (People using it should find it much more convenient than QTP reports ).

Basic Requirements:

  1. All the usual Eclipse , Selenium  etc.,
  2. I will be using TestNG framework.

Here is how it can be done :

1.  Usage

2. Implementation



3. Report generated :



Code Here :

//Parent Class  -  Can be your library file 

static class Findele extends SeleneseTestBase
     {
          WebDriver driver_temp;
          String sBrowser="";
       
         Findele(WebDriver driver)
         {
             this.driver_temp=driver;
            // sBrowser=ParallelRunning.sBrowser;
         }
       
         public Object Xpath(String value)
         {
             sBrowser=Thread.currentThread().getName();
             try{
                 System.out.println("Finding Object using Xpath="+value);
                 return driver_temp.findElement(By.xpath(value));
             }catch(Throwable  t)
               {
                 ParallelRunning.APPLICATION_LOGS.debug("Unable to find the object");  // Log error in Log File  http://catchbug.blogspot.in/2014/05/applicationlog-seleniumlog-and.html */
               
                 System.out.println("---Finding Object using Xpath Failed");   //Log error in Report
                   verificationErrors.append(t.getMessage());
                   Reporter.log("(object not found) Xpath="+value+"<br>");  

                   String sError=misc.timestamp();                 //Take screen shot attach it to the error in Report
                   misc.take_screenshot(driver_temp,"C:\\save_here.jpg" );
                   Reporter.log("<a href=\"" +"file:///"+ error_screen_path.replace("\\", "/")+".jpg" + "\">Screenshot</a>");
                  
                   clearVerificationErrors(); // Fail test case move on
                   if (!"".equals(verificationErrors.toString()))
                   fail(verificationErrors.toString());
                   return null;
             }          
         }
       
         public Object ID(String value)  // You add the above enhancements for ID or any other locator as well
         {
             try{
                 System.out.println("Finding Object using ID="+value);
                 return driver_temp.findElement(By.id(value));
             }catch(Throwable  t)
               {
                 System.out.println("---Finding Object using ID Failed");
                   verificationErrors.append(t.getMessage());
                   Reporter.log("object not found--"+"<br>");  
                   clearVerificationErrors();
                   if (!"".equals(verificationErrors.toString()))
                   fail(verificationErrors.toString());
                   return null;
             }          
         }
     }


 static void take_screenshot(WebDriver driver,String sFilename){
         File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
         try {
            FileUtils.copyFile(screenshot, new File(sFilename+".jpg"));
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            System.out.print("failed to create a Screen shot");
        }
     }

Usage

library.Findele FindEle=new library.Findele(driver);       //Declaration 
        ((WebElement) FindEle.ID("dsfdsfdsf")).sendKeys("User"); //usage


Monday, May 5, 2014

Application.log , Selenium.log and log4j.properties files





Application.log , Selenium.log and log4jproperties


Log4j.properties file in our framework, logs all Selenium related information into “Selenium.log” file and application related information into “Application.log” file.
a.       Download “log4j.jar” from http://www.java2s.com/Code/Jar/l/Downloadlog4jjar.htm and add to your build path of your project.
b.      Create “Application.log” ,”Selenium.log” and “log4j.properties” file in your Project, package as shown in screenshot.
c.       Add the contents in screen shot into the “log4j.properties” file and change the path of selenium and application log files .
d.      Application.log and Selenium.log remains empty.
e.      Add the following lines in your main code .
Now after execution, click on Project rt clk >Refresh . To see updated logs .
Note : To update your application.log , use below code :
your_class.APPLICATION_LOGS.debug("message");


//----------------------log4j.properties--------------------------------------
#Root logger option
log4j.rootLogger=debug,file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\USA Today\\Sigma_Selenium\\src\\src\\Selenium.log
log4j.appender.file.maxFileSize=5000KB
log4j.appender.file.maxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
#do not append the old file. Create a new log file everytime
log4j.appender.file.Append=false

#Application Logs
log4j.logger.devpinoyLogger=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=D:\\USA Today\\Sigma_Selenium\\src\\src\\Application.log
#do not append the old file. Create a new log file everytime
log4j.appender.dest1.Append=false
//---------------------------------------------------------------------------