Sunday 30 December 2012

Handling Authentication Required pop up using Selenium

To handle the 'Authentication Required' pop up using selenium from Firefox web driver you can use the following web driver code:


baseUrl = "https://NXTest:Test123@apwms.qa.redbond.net/ui/";   
driver.get(baseUrl);


where 'NXTest' will be your user name and 'Test123' the password.


Hope this tip is of some help.  
 

Thursday 2 August 2012

TestNg Groups feature in Selenium Automation

In this blog, I would like to share with all of you on the usage of 'groups' feature of testNG in selenium automation.
TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a certain set of groups (or regular expressions) while excluding another set.  This gives you maximum flexibility in how you partition your tests and doesn't require you to recompile anything if you want to run two different sets of tests back to back.

Declaring a Group in your test:

public class Test {
  @Test
  public void testMethod1() {
  }
  @Test
  public void testMethod2() {
  }
  @Test
  public void testMethod3() {
  }
}
 Here you can see there are three methods declared inside the class namely testMethod1, testMethod2, testMethod3. Consider them as three scenarios (@Test in TestNg).
Now one may be only needed to run while a sanity testing is performed, the other only for a regression testing and another for both sanity and regression. In such a situvation Groups concept of testNg is very usefull.
We can define classify these tests on the basis of thier type of testing with the help of groups as follows:

public class Test {
  @Test(groups = { "sanity" })
  public void testMethod1() {
  }
  @Test(groups = {"regression"})
  public void testMethod2() {
  }
  @Test(groups = { "sanity", "regression" })
  public void testMethod3() {
  }
}
Notice the use of 'groups' inside the @Test annotation in the above example. So we have classified the three scenarios into diffrent groups.

Now to execute this scenarios on the basis of their specific groups we have two options availabe.

1) FROM THE SUITE XML [TESTNG XML]
2) FROM THE ANT XML [BUILD XML]

I shall explain in detail on these two options in my upcoming blogs.....
Please follow up with your comments in case of any suggestions or opinions.

Thursday 12 April 2012

Maximize browser window in Selenium Web Driver

From Selenium 2.21, we can now maximize the browser window, similar to Selenium RC.

 Direct way:

public static void main(String[] args) {
  WebDriver d = new FirefoxDriver();
  d.get("http://www.google.com");
  d.manage().window().maximize();
 
  System.out.println(d.getTitle());
  d.quit();
 }

Indirect way:

we can also maximize the browser window usingt the toolkit utility which query the native operating system directly and is platform independent. In addition to this, the code below will maximize the browser window according to your system's current resolution.

driver.manage().window().setPosition(new Point(0,0));
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Dimension dim = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setSize(dim);
Use the above script in your test setup method where you initiate the browser to get a fully maximized brwoser window that fits your monitor's screen size....
 

Tuesday 10 April 2012

How to handle frame pop ups using Selenium Webdriver

Frames are not exactly treated as pop ups or external windows in Selenium Web driver. There will be a frame id for each frame. We have to invoke this particular frame id to handle the actions related to frames when automationg using selenium 2.0

See the example provided below:

driver.switchTo().frame("companyFlyoutIFrame");  

where "companyFlyoutIFrame" is the id of the frame. To obtain the id, inspect the frame object using the firebug.

The above line is the script used to switch the control to the frame. once the control is switched, you can do the actions on the frame as normal selenium commands.

Once you are done with the frame, it is also important to switch the control back to the main window. To do this you can use the following script:

driver.switchTo().defaultContent();


willl switch the controll back to the main window by closing the frame.

Hope it is informative....
 

Wednesday 4 April 2012

Finding the Class name from Xpath of an Element in Selenium

Sometimes, we may require to find the Class name of an element whoes xpath we know.
We can use the "getAttribute()"  method of Selenium to handle this situvation.

consider the example below:

String Name=webDriver.findElement(By.xpath(//div[@class='hotelRoomCard'][5]/span[2]/button).getAttribute("class");
System.out.println("The class name is:"+Name);

The output will geive you the class name.
This in turn can be used to identify the object with a desired class name.
Hope it was helpfull.... :)

Tuesday 20 March 2012

Xpath Count in Selenium2 WebDriver

Selenium 1 uses 'getXpathCount' method to find the Xpath count of an atribute in the screen.
But in Selenium2 webdriver it is done by the following way:

int xpathCount= webDriver.findElements(By.xpath("//div[@id='billingProfiles']/div[@class='cardContainer']")).size();

please note that we are using 'findElements' instead of the usual 'findElement' method.

Monday 19 March 2012

TestNG Suite Set up and Tear Down

ackage selenium.src.com.ofb.supportClasses;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.events.WebDriverEventListener;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;

public class OfbTestSet{
   
    private WebDriver webDriver;
    private String testUrl, loginID, password;
   
    @BeforeMethod(alwaysRun = true)
    @Parameters({"browser", "testUrl", "loginID", "password"})
    public  void setUp(@Optional ("") String browser,
            @Optional ("") String testUrl,
            @Optional ("") String loginID,
            @Optional ("") String password) throws Exception{
       
        if (browser.contentEquals(""))
            browser = ReadProperty.commonValueProps.getProperty("browser");
        if (testUrl.contentEquals(""))
            testUrl = ReadProperty.commonValueProps.getProperty("testUrl");
        if (loginID.contentEquals(""))
            loginID = ReadProperty.commonValueProps.getProperty("LoginID");
        if (password.contentEquals(""))
            password = ReadProperty.commonValueProps.getProperty("Password");
       
        this.testUrl = testUrl; this.loginID = loginID; this.password = password;
       
        if (browser.contentEquals("firefox"))
        {
            //FirefoxProfile ofbFF = new FirefoxProfile(new File("OfbFirefoxProfile/data"));
            //ofbFF.setAcceptUntrustedCertificates(false);
            //ofbFF.setAssumeUntrustedCertificateIssuer(false);
            //ofbFF.setPreference("network.dns.disableIPv6", true);
            //ofbFF.setEnableNativeEvents(false);
           
            WebDriverEventListener eventListener = new CustomEventListener();
            webDriver = new EventFiringWebDriver(new FirefoxDriver()).register(eventListener);
        }
       
        if (browser.contentEquals("iexplorer"))
        {
            WebDriverEventListener eventListener = new CustomEventListener();
            webDriver = new EventFiringWebDriver(new InternetExplorerDriver()).register(eventListener);
        }
        webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
       
        webDriver.get(testUrl);
       
        //To maximize the browser window
        WebDriverBackedSelenium selenium = new WebDriverBackedSelenium(webDriver, "");
        selenium.windowMaximize();
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown() throws Exception {
        webDriver.quit();
    }
   
    public WebDriver getWebDriver() {
        return webDriver;
    }

    public String getTestUrl(){
        return testUrl;
    }
   
    public String getLoginID(){
        return loginID;
    }
   
    public String getPassword(){
        return password;
    }

}

Tuesday 13 March 2012

How to install ANT on LINUX

How to install ANT on LINUX

Apache Ant is a Java library and command-line tool that help building software.
How to install:
  • Create downloads directory if you dont have one
  • Download tar version from http://ant.apache.org/bindownload.cgi
  • Extract
  • Rename the new directory as ant
  • Insert the path into ANT_HOME
  • Update the global PATH variable to include ANT_HOME
  • Run the Ant script fetch.xml to install almost all the dependencies the optional Ant tasks need.
See actual commands:

bash ~]$ mkdir downloads
[bash ~]$ cd downloads/
[bash downloads]$
[bash downloads]$
[bash downloads]$ wget http://mirror.candidhosting.com/pub/
 apache//ant/binaries/apache-ant-1.8.2-bin.tar.gz
[bash downloads]$ tar -zxvf apache-ant-1.8.2-bin.tar.gz
[bash downloads]$ mv apache-ant-1.8.2 ant
[bash downloads]$ ANT_HOME=/home/nx/ls/downloads/ant
[bash downloads]$ PATH=$PATH:${ANT_HOME}/bin
[bash downloads]$ ant -f fetch.xml -Ddest=system

TestNG XSLT Report Generation

Reports are vital part of any automation testing and with Selenium+TestNG framework we have the default TestNG reports, which some consider to be a little out of date... to over come this, we have a add on report for TestNG know as TestNG-XSLT which gives good graphical representation of the generated report.

TestNG-xslt generates user friendly reports using the TestNG results output (testng-results.xml). Its uses the pure XSL for report generation and Saxon as an XSL2.0 implementation.


For generating testng-xslt report for your project do the following:
1. Download the testng-xslt from

     http://code.google.com/p/testng-xslt/
2. Unzip and copy the testng-results.xsl from the testng-xslt folder(testng-xslt-1.1\src\main\resources) to your own project folder.
3. Now copy the saxon library from (testng-xslt-1.1\lib\saxon-8.7.jar)to your project lib folder.
4. Modify your build.xml of ant and add the following target to it.


<project name="test" basedir=".">
    <property name="LIB" value="${basedir}/libs" />
    <property name="BIN" value="${basedir}/bin" />
    <path id="master-classpath">
            <pathelement location="${BIN}" />
            <fileset dir="${LIB}">
                <include name="**/*.jar" />
            </fileset>
        </path>
    <target name="testng-xslt-report">
        <delete dir="${basedir}/testng-xslt">
        </delete>
        <mkdir dir="${basedir}/testng-xslt">
        </mkdir>
        <xslt in="${basedir}/test-output/testng-results.xml" style="${basedir}/testng-results.xsl" out="${basedir}/testng-xslt/index.html">
            <param expression="${basedir}/testng-xslt/" name="testNgXslt.outputDir" />

            <param expression="true" name="testNgXslt.sortTestCaseLinks" />

            <param expression="FAIL,SKIP,PASS,CONF,BY_CLASS" name="testNgXslt.testDetailsFilter" />

            <param expression="true" name="testNgXslt.showRuntimeTotals" />

            <classpath refid="master-classpath">
            </classpath>
        </xslt>
    </target>
</project>

You need to provide the testng-xslt stylesheet the TestNG results xml(testng-results.xml) , the path to the style sheet testng-results.xsl and the output index.html path.

Also dont forget to add the saxon library to your target classpath else you will get an error. In my case it is the master-classpath.

Now run the ant target for report generation (in this case "testng-xslt-report
") and check the ouput folder configured by you for testng-xslt report.


Build XML for Selenium+TestNG+ANT framework

I have developed a build.xml that can handle the the build of a test suite and do the reporting. It even send the report as mail. For reporting we are using TestNG-XSLT

<project name="Automation" default="clean" basedir=".">
    <property name="build.dir" value="${basedir}/build"/>
    <property name="lib.dir" value="${basedir}/lib"/>
    <property name="src.dir" value="${basedir}/src"/>
    <property name="browser" value="/home/nxavier/Downloads/firefox/firefox"/>
    <target name="setClassPath">
        <path id="classpath_jars">
            <pathelement path="${basedir}/" />
            <fileset dir="${lib.dir}" includes="*.jar" />
        </path>
        <pathconvert pathsep=":" property="test.classpath" refid="classpath_jars" />
    </target>
    <target name="loadTestNG" depends="setClassPath">
        <taskdef resource="testngtasks" classpath="${test.classpath}"/>
    </target>
    <target name="init">
        <mkdir dir="${build.dir}"/>
        <tstamp>
            <format property="timestamp" pattern="dd-MM-yyyy_(HH-mm-ss)"/>
        </tstamp>
        <property name="build.log.dir" location="${basedir}/buildlogs"/>
        <mkdir dir="${build.log.dir}"/>
        <property name="build.log.filename" value="build_${timestamp}.log"/>
        <record name="${build.log.dir}/${build.log.filename}" loglevel="verbose" append="false"/>
        <echo message="build logged to ${build.log.filename}"/>
    </target>
    <target name="clean">
        <echo message="deleting existing build directory"/>
        <delete dir="${build.dir}"/>
    </target>
    <target name="compile" depends="clean,init,setClassPath,loadTestNG">
        <echo message="classpath:${test.classpath}"/>
        <echo message="compiling.........."/>
        <javac destdir="${build.dir}" srcdir="${src.dir}" classpath="${test.classpath}"/>
    </target>
    <target name="runTests" depends="compile">
        <testng classpath="${test.classpath}:${build.dir}">
            <xmlfileset dir="${basedir}" includes="Debug.xml"/>
        </testng>
    </target>
    <target name="report" depends="runTests">
        <delete dir="${basedir}/testng-xslt"/>
        <mkdir dir="${basedir}/testng-xslt"/>
        <xslt in="${basedir}/test-output/testng-results.xml"
        style="${basedir}/src/xslt/testng-results.xsl" out="${basedir}/testng-xslt/index.html" processor="SaxonLiaison">
            <param expression="${basedir}/testng-xslt/" name="testNgXslt.outputDir"/>
            <param expression="true" name="testNGXslt.sortTestCaseLinks"/>
            <param expression="FAIL,SKIP,PASS,BY_CLASS" name="testNgXslt.testDetailsFilter"/>
            <param expression="true" name="testNgXslt.showRuntimeTotals"/>
            <classpath refid="classpath_jars"/>
        </xslt>
    </target>
    <target name="RunAndViewReport" depends="report">
        <exec executable="${browser}" spawn="yes">
       <arg line="'${basedir}/testng-xslt/index.html'" />
      </exec>
     </target>
    <target name="sendMail" depends="RunAndViewReport">
        <zip destfile="${basedir}/testng-xslt/Report.zip" basedir="${basedir}/testng-xslt"/>
        <mail mailhost="smtp.gmail.com" mailport="465" subject="Notification of TESTNG build" ssl="false" user="tester@gmail.com" password="password">
            <from address="tester@gmail.com"/>
            <to address="tester@gmail.com"/>
            <message>The build has finished. A details report of this build is aatched</message>
            <attachments>
                <fileset dir="testng-xslt">
                    <include name="**/*.zip"/>
                </fileset>
            </attachments>
        </mail>
    </target>
</project>



Wednesday 15 February 2012

Selenium 2.0-The future of Selenium!!!

Selenium 2.0 is a major milestone in Selenium's automations landmark. Selenium 2.0 has many new exciting features and improvements over Selenium 1. The primary new feature is the integration of the WebDriver API. This addresses a number of limitations of Selenium 1 (RC) along with providing an alternative, and simpler, programming interface. The goal is to develop an object-oriented API that provides additional support for a larger number of browsers along with improved support for modern advanced web-app testing problems.

Rather than being a JavaScript application running within the browser, it uses whichever mechanism is most appropriate to control the browser. For Firefox, this means that WebDriver is implemented as an extension. For IE, WebDriver makes use of IE's Automation controls. By changing the mechanism used to control the browser, we can circumvent the restrictions placed on the browser by the JavaScript security model. In those cases where automation through the browser isn't enough, WebDriver can make use of facilities offered by the Operating System. For example, on Windows we simulate typing at the OS level, which means we are more closely modeling how the user interacts with the browser, and that we can type into "file" input elements.

So, what are the differences between Selenium WebDriver and Selenium RC and where innovation is?
The thing is in the way of interaction with the browser:
  • Selenium RC sends commands to the browser using JavaScript Selenium Core.
  • WebDriver works with the browser through native browser interface.


Selenium developers recommend to use Selenium webDriver, as Selenium RC was officially deprecated. 

Tuesday 14 February 2012

Selenium+TestNG+ANT (SAT) FrameWork

One of the descent framework for dynamic data driven testing using Selenium is by using Selenium along with TestNG and ANT as the build tool.
The flexibilty in this framework is that it allows you to execute the test suite either from an IDE like eclipse or from a batch file with the help of ANT.
This helps an external user who have little knwledge on Selenium to execute the test suite by double clicking on the batch file....
I shall post here further details of this framework if any of you would like to know more in details about this framework.