Tuesday, May 29, 2012

Sample Framework for testng based tests

This summary is not available. Please click here to view the post.

Use firefox in custom location for Grid

Start Node 

java -jar selenium-server-standalone-2.20.0.jar -role node -hub http://IP_Remote_Machine:4444/grid/register -port 5561 -nodeConfig config.txt

config.txt File Contents

{
"capabilities":
        [
                {
                        "browserName":"firefox",
                        "acceptSslCerts":true,
                        "javascriptEnabled":true,
                        "takesScreenshot":true,
                        "firefox_binary":"c:\\Program Files\\FF9\\firefox.exe",
                        "maxInstances":5,
                        "version":"9"
                },
                {
                        "browserName":"chrome",
                        "maxInstances":5
                },
                {
                        "browserName":"internet explorer",
                        "platform":WINDOWS
                }
        ],
"configuration":
        {
                "cleanUpCycle":2000,
                "proxy":"org.openqa.grid.selenium.proxy.WebDriverRemoteProxy",
                "maxSession":5,
                "port": 5561,
                "hubPort" : 4444
        }
}

The above script will assigned firefox 9 installed in custom location to grid hub.

Java Code For Assigning Browser

DesiredCapabilites caps = new DesiredCapabilites.firefox();
caps.setVersion("9");
caps.setBrowserName("firefox");
caps.setPlatform(Platform.ANY);
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:444/wd/hub"), caps);


Friday, May 25, 2012

JavascriptExecutor methods

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", 
 webElement);
 
((JavascriptExecutor) driver)
.executeScript("arguments[0].setAttribute('style', 'color: yellow; border: 2px solid yellow;
');", element); 
 
((JavascriptExecutor) driver).executeScript("arguments[0].click;", 
 webElement);
 
check image has loaded
 
List<WebElement> allImages = driver.findElements(By.tagName("img"));
for (WebElement image : allImages) {
  boolean loaded = ((JavaScriptExecutor) driver).executeScript(
      "return arguments[0].complete", image);
  if (!loaded) {
    // Your error handling here.
  }
}  

start remote webdriver node

java -jar selenium-server-standalone-2.20.0.jar -role webdriver -hub http://ip of machine:4444/grid/register -browser "browserName=internet explorer, platform=WINDOWS" -browser "browserName=firefox, platform=ANY" -port 5561

Grid with config file

config.txt for starting firefox in custom location

{
"capabilities":
        [
                {
                        "browserName":"firefox",
                        "acceptSslCerts":true,
                        "javascriptEnabled":true,
                        "takesScreenshot":true,
                        "firefox_binary":"c:\\Program Files\\FF9\\firefox.exe",
                        "maxInstances":5,
                       "version":"9"
                },
                {
                        "browserName":"chrome",
                        "maxInstances":5
                },
                {
                        "browserName":"internet explorer",
                        "platform":WINDOWS
                }
        ],
"configuration":
        {
                "cleanUpCycle":2000,
                "proxy":"org.openqa.grid.selenium.proxy.WebDriverRemoteProxy",
                "maxSession":5,
                "port": 5561,
                "hubPort" : 4444
        }
}

Sample node : java -jar selenium-server-standalone-2.20.0.jar -role node -hub http://ip of machine:4444/grid/register -port 5561 -nodeConfig config.txt




Java code to invoke it


DesiredCapabilities caps = DesiredCapabilites.firefox();
caps.setVersion("9.0");
caps.setBrowserName("firefox");

Wednesday, May 23, 2012

Execute a suite file using Ant

Suite file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
 <suite name="Suite1" verbose="1" >
  <test name="Regression1" preserve-order="true">
    <classes>
   <class name="mytests.First">
    </class>
    </classes>
    </test>
</suite>

Build.xml

<project name="selenium-demo" default="compile" basedir=".">

    <property name="build.dir" value="build" />
    <property name="src.dir" value="src"/>
    <property name="lib.dir" value="lib"/>
    <property name="reports.dir" value="report"/>
    <property name="xml" value="Sample.xml"/>

    <path id="classpath">
        <pathelement location="${build.dir}/classes"/>
        <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>

 <!--   <taskdef name="testng" classname="com.beust.testng.TestNGAntTask" classpathref="classpath"/>
-->    <taskdef resource="testngtasks" classpathref="classpath"/>

    <target name="compile">
        <delete dir="${build.dir}"/>
        <mkdir dir="${build.dir}/classes"/>
        <echo message="Compiling tests" />
        <javac srcdir="${src.dir}" destdir="${build.dir}/classes"  executable="javac" classpathref="classpath">
            <classpath refid="classpath"/>
        </javac>
    </target>

    <target name="run_tests" depends="compile">
       <echo message="running tests" />
       <testng classpathref="classpath" haltOnfailure="true">
               <xmlfileset file="${xml}" />
            <sysproperty key="env" value="${env}"/>
            <sysproperty key="driver" value="${driver}"/>
       </testng>
    </target>

</project>

Data providers for selenium

  There are different methods to provide data to selenium tests.

One of these is using the properties file. User can store the data in properties file and use its content for the selenium test

Here is a properties file with some content. Name it as datasuite.properties
     
      Directory = C:/prodFiles/
      NumberOfFiles = 25
      Extension = javaworld


and the corresponding java code to manipulate it


        InputStream is = this.getClass().getResourceAsStream("/conf/datasuite.properties");  
        Properties prop = new Properties();  
        prop.load(is); 
        String directory = prop.getProperty("Directory");  
        String numberOfFiles = prop.getProperty("NumberOfFiles");  
        String  fileExtension = prop.getProperty("Extension");  
        is.close(); 
        
        System.out.println(directory+" "+numberOfFiles+" "+fileExtension);

Below is the folder structure



Send Mail with html content

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
   public static void main(String [] args) throws IOException
   {
     //  http://www.tutorialspoint.com/java/java_sending_email.htm

        String host = "smtp.gmail.com";
        final String from = "xxxxx@gmail.com";
        final String pass = "xxxx";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        String to = "xxxx@xxxx.com";
     // Get the default Session object.
        Session session = Session.getInstance(props,
                  new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, pass);
                    }
                  });

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress("testwidgets11@gmail.com"));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");
         String header = "<HTML><BODY><table border=\"2\">";
         String footer = "</table></BODY></HTML>";

         BufferedReader br = new BufferedReader(
                 new FileReader("c:\\source.html"));
         String line;
         String htmlSource = "";
         while ((line=br.readLine())!=null) {
             htmlSource = htmlSource.concat(line);
//             System.out.println(line);
         }
         System.out.println(htmlSource);
         String table = "<table border=\"1\"><tr><td style=\"background-color:red;\">Failed</td><td>Class</td><td>Test</td><td>Reason</td></tr><tr><td style=\"background-color:yellow;\">Skipped</td><td>Class</td><td>Test</td><td>Reason</td></tr></table>";
         table = htmlSource;
         message.setContent(header+table+footer, "text/html" );
         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Using TestListenerAdapter Class

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

public class TestReporter extends TestListenerAdapter{
    File f;
    BufferedWriter bw;

    public void onStart(ITestContext testContext){
        System.out.println("ON START");
         f = new File("c:\\source.html");
         try{
             bw = new BufferedWriter(new FileWriter(f));
         }
         catch(Exception e){

         }
    }

    public void onFinish(ITestContext testContext){
        System.out.println("ON Finish");
         try{
             bw.close();
         }
         catch(Exception e){

         }
    }

    public void onTestFailure(ITestResult arg0) {
    System.out.println("Failed Test: "+arg0.getName()+" Reason:"+arg0.getThrowable()+" Class : "+arg0.getTestClass().getName());

     try{
         writeToFile(arg0.getName(), arg0.getThrowable().toString(), arg0.getTestClass().getName(), "red", "Failed");
     }
     catch(Exception e){
     }
    }

    public void onTestSkipped(ITestResult arg0) {
    System.out.println("Skipped test: "+arg0.getName()+" Reason"+arg0.getThrowable()+" Class : "+arg0.getTestClass().getName());
        System.out.println("Test skipped");

         try{
             writeToFile(arg0.getName(), arg0.getThrowable().toString(), arg0.getTestClass().getName(), "yellow", "Skipped");
         }
         catch(Exception e){
         }
    }

    public void onTestSuccess(ITestResult arg0) {
        System.out.println("Passed Test: "+arg0.getName());
    }

    public void writeToFile(String testName, String throwable, String className, String color, String status) throws IOException{
         bw.write("<tr><td style=\"background-color:" + color + ";\">" + status + "</td><td>" + className + "</td><td>" + testName + "</td><td>" + throwable + "</td></tr>");
         bw.newLine();
    }
}

Tuesday, May 22, 2012

Send mail with Authenticator Object to session property

 //  http://www.tutorialspoint.com/java/java_sending_email.htm

        String host = "smtp.gmail.com";
        final String from = "xxxxxx@gmail.com";
        final String pass = "xxxxxxx";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        String to = "xxxxxx@gmail.com";
     // Get the default Session object.
        Session session = Session.getInstance(props,
                  new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, pass);
                    }
                  });

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress("testwidgets11@gmail.com"));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }

Run tesng programatically

        XmlSuite xml = new XmlSuite();
        xml.setName("Test");

        XmlTest test = new XmlTest(xml);
        test.setName("Sample Test");
        List<XmlClass> classes = new ArrayList<XmlClass>();
        classes.add(new XmlClass("main.Sample"));
        test.setXmlClasses(classes);

        List<XmlSuite> suites = new ArrayList<XmlSuite>();
        suites.add(xml);
        TestNG tng = new TestNG();
        tng.setXmlSuites(suites);
        tng.run();

Send mail with smtps attached to Transport

        String host = "smtp.gmail.com";
        String from = "xxxxxx@gmail.com";
        String pass = "xxxxx";
        System.out.println("Water2");
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

            emailId = "mathew";

        String[] to = {emailId+"@cxxxx.com"};/*, emailId}; */ // added this line

        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i=0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i=0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject("Result of running "+testName);
//        message.setText("Check out the attached test report");
//        http://www.jguru.com/faq/view.jsp?EID=30251

        /* For Body Part */

        MimeBodyPart messageBodyPart =
          new MimeBodyPart();

        messageBodyPart.setText("Check out the attached test report");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        String fileAttachment = System.getProperty("user.dir")+"/test-output/emailable-report.html";
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileAttachment);
        messageBodyPart.setDataHandler( new DataHandler(source));
        messageBodyPart.setFileName("Test-Report");
        multipart.addBodyPart(messageBodyPart);
        // Put parts in message
        message.setContent(multipart);

        /*------*/

        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

Tuesday, May 15, 2012

Pass values from command line to java program/ant file

In order to pass values from command line to java program we can use "sysproperty"
Sample usage

   <target name="run_tests" depends="compile">
       <echo message="running tests" />
       <testng classpathref="classpath" haltOnfailure="true">
               <xmlfileset file="${xml}" />
            <sysproperty key="env" value="${env}"/>
            <sysproperty key="driver" value="${driver}"/>
       </testng>
    </target>

   @Test
    @Parameters ({"env","driver"})
    public void setUp(String env, String driver) {
           System.out.println(env+" success "+driver);
  }

 Execution : ant run_tests -Denv=test -Ddriver=ff


Wednesday, May 2, 2012

Configuration to make maven plugin work in eclipse

1. Update eclipse.ini file with the option
-vm
C:/Program Files/Java/jdk1.6.0_10/bin/javaw.exe

2.Configure eclipse to use jre in jdk definition from(Preference -> java -> installed jre)