Thursday, August 2, 2012

By Pass ssl security pages

Certificates are of mainly two types
1) Self signed
2) Signed by root certificate authority.

In the case of all browsers, security certificate warning page will only be shown for pages with self signed certificate(or if certificate signed by root authority has expired).

For firefox to by pass this page we can follow two methods
1) Use a profile in which the certificate has already been installed.
2) Create a new profile and use the functions
    a) setAcceptUntrustedCertificates(Boolean value)
    b) setAssumeUntrustedCertificateIssuer(Boolean value)
      
   setAssumeUntrustedCertificateIssuer will have boolean value true or false based on the whether it is self signed or not.
        If it is self signed certicate use setAssumeUntrustedCertificateIssuer(true)
        If it the certificate has expired use setAssumeUntrustedCertificateIssuer(false) and in both of above cases setAcceptUntrustedCertificates(true) should be used.


For IE
 1) Install the certificate and run tests. If that case is failing go for second option.
 2) Use driver.navigate().to("javascript:document.getElementById('overridelink').click()"); to bypass security certificate page.

I haven't tried it for Chrome.

Thursday, June 28, 2012

InternetExplorerDriver Issues in webdriver

I am really confused by the way InternetExplorerDriver driver works. What all are the issues. In what all OS/Versions it works. What all api's work etc. Are all api's using native events.

Why is click() failing and sendKeys() working?
Why is test failing for InternetExplorerDriver when browser is minimized, but for remotewebdriver it works?

Will click() work if ie window is having focus? I think so





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)


Wednesday, April 11, 2012

xpath locators

xpath=(//a[@class='addthis_button'])[last()-2]
xpath=(//a[@class='addthis_button'])[last()]
xpath=(//a[@class='addthis_button'])[position()=2]
//a[contains(@class, concat("addthis_button_compact", " at300m"))]

More reference : http://shanmugavelc.blogspot.com/2011/11/selenium-css-locators.html

Tuesday, February 14, 2012

Flash with selenium

Selenium/Webdriver cannot click on the flash application. Only thing it can do is invoke the functions defined in as3 scripts using javascript.  For functions to be accessible to javascript it should be added to ExternalInterface. ExternalInterface is used to call javascript function from/to flash.

ExternalInterface.addCallback("setText", setText) makes setText method invokable from javascript

        WebDriver driver = new FirefoxDriver();
        WebDriverBackedSelenium selenium = new WebDriverBackedSelenium(driver, "");
        driver.get("http://sitestress.webmetrics.com/test/flashtest.html");
        selenium.getEval("var movie = window.document.extinterfaceexample; movie.jsToFlash('water in water');");

        driver.get("http://bowser.effectgames.com/~jhuckaby/zeroclipboard/");
//        selenium.type("fe_text", "bla bla bla");
        selenium.getEval("var playerid = window.document.ZeroClipboardMovie_1; playerid.setText('james bond')");

For above example  'ZeroClipboardMovie_1' is the object id of the flash movie. It is used to create a variable for accessing the as3 functions.

For more details checkout Flash Selenium

Tuesday, January 17, 2012

Auto it basics for entering text

Press escape key : Send("{ESCAPE}")
Press enter key : Send("{ENTER}")
Press tab key : Send("{TAB}")

Enter some content and press tab key : Send("water{TAB}")
Enter some content and press enter key : Send("water{ENTER}")

Autoit for File upload

Firefox

WinWaitActive("File Upload")
if WinExists("File Upload") Then
ControlSetText("File Upload", "", "Edit1", "C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg")
Sleep(1000)
ControlClick("File Upload", "", "Button2")
EndIf

IE

WinWaitActive("Choose file")
if WinExists("Choose file") Then
ControlSetText("Choose file", "", "Edit1", "C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg")
Sleep(1000)
ControlClick("Choose file" ,"", "Button2")
EndIf

Chrome

WinWaitActive("Open")
if WinExists("Open") Then
ControlSetText("Open", "", "Edit1", "C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg")
Sleep(2000)
ControlClick("Open", "", "Button2")
EndIf

For more reference follow these links. These guys have given nice example
http://qtp-help.blogspot.com/2009/07/selenium-handle-dialogs.html
http://automationtricks.blogspot.com/2010/09/how-to-upload-file-in-selenium-with.html
http://iautomateit.wordpress.com/2011/07/15/working-around-file-upload-dialog-issues-with-selenium-2/
http://bharath-marrivada.blogspot.com/2011/02/selenium-autoitv3-file-upload-download.html

Thursday, January 12, 2012

FirefoxDriver with custom profile

Use profile manager to create profiles. In Windows machine profiles will be stored in the path

C:\Documents and Settings\user\Application Data\Mozilla\Firefox\Profiles\

FirefoxProfile profile = new ProfilesIni().getProfile("profileName");
FirefoxDriver driver = new FirefoxDriver(profile);

Once firefox window opens check that addon's, bookmark etc are appearing in the newly opened firefox window.

Simulate click using javascript for webdriver

        driver.get("http://www.google.com");
        JavascriptExecutor js =  (JavascriptExecutor)driver;

        WebElement upload = driver.findElement(By.name("btnI"));
        ((JavascriptExecutor)driver).executeScript("arguments[0].click();", upload);

By pass certificate validation failure in IE for https pages

if (driver instanceof InternetExplorerDriver)
    driver.navigate().to("javascript:document.getElementById('overridelink').click()");

Wednesday, January 4, 2012

ISuiteListener and ITestListener

Sample usage

public class TestReporter implements ITestListener {

    static int count;

    public void onFinish(ITestContext arg0) {

        System.out.println("Test Finished !!!!!!!!");
    }

    public void onStart(ITestContext arg0) {
        ISuite suite = arg0.getSuite();
        System.out.println("Driver is : ");
        ITestNGMethod[] value = arg0.getAllTestMethods();
        System.out.println("Method Number : "+value.length);
        count = value.length;

    }

    @Override
    public void onTestFailure(ITestResult arg0) {
//    System.out.println("Finished Executing Test: "+arg0.getName()+" Status: Failed"+"\n Reason:"+arg0.getThrowable());
    }

    @Override
    public void onTestSkipped(ITestResult arg0) {
//    System.out.println("Skipped test: "+arg0.getName()+".Reason"+arg0.getThrowable());
    }

    @Override
    public void onTestStart(ITestResult arg0) {
//    System.out.println("Starting Test: "+arg0.getName());
//    System.out.println("\n Starting Test: "+count--);

    }

    @Override
    public void onTestSuccess(ITestResult arg0) {
    System.out.println("Finished Executing Test: "+arg0.getName()+" Status: Success.");
    System.out.println("Class Name : "+arg0.getTestClass());

    Object[] ab = arg0.getParameters();
    System.out.println("Param Set : "+ab.length);
    for(int i = 0 ; i < ab.length ; i++)
        System.out.print(ab[i]+" ");

//    System.out.println("Method Name : "+arg0.getMethod().getMethodName());
    }

    public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
//    System.out.println("Test failed but within success percentage");
    }
}


public class SuiteReporter implements ISuiteListener {

    @Override
    public void onFinish(ISuite arg0) {
    System.out.println("Finished executing the suite");
    System.out.println("********Results*******");

    }

    @Override
    public void onStart(ISuite arg0) {
    System.out.println("Starting Execution");
    //Print suiteName
    System.out.println("Suite Name:"+arg0.getName());
    //Print HostName
//    System.out.println("Host Name:"+arg0.getHost());
    //Returns null if it runs locally

    }
}





 <suite name="Sample Suite">
<!--
    <listeners>
    <listener class-name="com.clearspring.qa.tellurium.SuiteReporter" />
    <listener class-name="com.clearspring.qa.tellurium.TestReporter" />
   </listeners>
<test>
</test>
</suite>