Tuesday 31 December 2013

Selenium Object Bank Services



Following are the services provided by SOB

  • Adding an Object
  • Removing an Object
  • Updating an Object
  • View Available Objects 



How to Use

Let’s start with an example by Testing WordPress Website for adding and deleting a post. 

Step 1: 
Download the sample Eclipse project for WordPress [SOB Sample Demo Download Link
Import the Project into Eclipse 
After importing you can see three Java Files 

  • atu.selenium.scripts.WithoutObjectBank
  • com.test.Testing
  • objects.mapper.com.test.HasTestingObjects

Download the latest Selenium Server Standalone jar file and add it to your Build Path

[Selenium Server Standalone Jar Link]

Download the SOB jar file and add it to your Build Path [SOB Jar File Download Link]
  • The first class atu.selenium.scripts.WithoutObjectBank is a sample Selenium WebDriver script without using SOB
  • The Second class com.test.Testing is the same Selenium WebDriver script with SOB features
  • The Third class objects.mapper.com.test.HasTestingObjects is generated automatically by SOB


Step 2: 
Right click on the com.test.Testing java and Select Selenium Object Bank Manager as shown in below figure  




Once you select, SOB window appears as shown below




  • From the SOB window you can see the available Objects in the left Pane
  • When you click on any Object from the left pane, you can see the Object details and the Element Tag type from the Properties table and the Select Box
  • To Add an Object, Enter a Unique Object Name in the field, Select the element tag type, enter the attribute and its value (you can add more than one locator)and click on Add button





  • To Remove an Object from the Available Objects, Select one of them and click on Remove button
  • To Update an Object Attribute or Value, Select any object from the left pane and edit values from the Properties table
  • The Clear Fields button is used when you want to clear the Properties and Object Name field. (While Adding an Object)



How does SOB work?
  • Create a WebDriver Script
  • Right Click on the Script and select Selenium Object Bank Manager, since it is a newly created script it pops up a message box like below as it does not have an Object Bank associated with it.
  • Click on Yes to Create an Object Bank for the Script





  • After clicking on Yes button, a Directory Named ObjectBank is created in the project folder. Under this ObjectBank directory, an XML file is generated that stores the Object details for the corresponding script
  •  The XML file name is same as the Script name and its directory structure is same as the Script package structure
  •  Along with this XML file, for each Script, a corresponding java file named Has[Script Name]Objects is generated under the objects.mapperpackage. The script’s directory structure is same as its package structure.
           NOTE:  Please refresh the Eclipse Project folder to see the newly created files 
  •  For example: if the script name is com.test.Registration.java then
  •  An XML file is generated in ObjectBank\com\test\Registration.xml
  •  A Java file is generated in objects\mapper\com\test\HasRegistrationObjects.java under src package






Future Scope for SOB


Well, we are using this approach for our Projects and will be continued in future :) 

A whole lot of new features will be introduced into SOB to the benefit of various Clients, Organizations, and Users including myself. Stay tuned :) 

We love WebDriver, as an Open Source tool, we love to keep its utilities Open Source. 
                                                                                              

Model Based Testing

A new paradigm for manual and automated functional testing.

 

Testing is an essential, but time and resource consuming activity 
in the software development process.Generating a short, 
but effective test suite usually needs a lot of manual work 
and expert knowledge.In a model-based process, among other sub-tasks
test construction and test execution can be automated.

What is Model Based Testing?

Model based testing is a black box testing technique where run time behavior 
of a software under test is checked against predictions made by a formal 
specification or model. In other means, it describes how system behaves 
in response to an action ( determined by a model). Supply action ,and see,
if the system responds as per the expectation.

Testers construct mental models anyway during their testing.
Those mental models can be transformed to models on paper. 
This helps testers to achieve readability and re-usability.

What are the advantages of Model based Testing?

  • Easy test case/suite maintenance
  • Reduction in Cost
  • Improved Test Coverage
  • Can run different tests on n number  of machines
  • Early defect detection
  • Increase in defect count
  • Time savings
  • Improved tester job satisfaction

Monday 30 December 2013

Automation Testing Utilities!!

Selenium Object Bank - SOB

Google’s Selenium Web Driver has took a pace where automating a web application has made easier than ever. With very few methods exposed by the API, almost all the actions can be achieved that are necessary for working with a web application.

In automation script where all the application Objects are given within, maintaining these Objects can be tiresome. Readability of the Script is not as easy as it looks. Understanding the code at later point of time can be real painful. Addressing these issues users including myself had followed various approaches for minimizing the complexity, one such is implementing the Page Object Pattern, or may be storing all the Objects in an external property file, Providing detailed comments for the Objects, or any other user defined approach.

Keeping these in mind, I wondered how we could deal with all these cumbersome tasks using one single solution. There took the birth of Selenium Object Bank (SOB) that can address the following questions. 
·                     Storing all the Objects in a central location
·                     Changing Object properties without any modification on the Script
·                     Readability and clear understanding of the automation steps performed by just looking into the Script
·                     Minimizing the Script code by Object notation
·                     Creating Robust Scripts
·                     Re usability of the Objects
·                     Identifying the Objects with different locators other than those provided by Web Driver (id, name, xpath, css, class, tagName) 

Sample Code

A Sample code for automating WordPress website using regular approach

driver.findElement(By.id("user_login")).sendKeys("admin");
driver.findElement(By.id("user_pass")).sendKeys("demo123"); 
driver.findElement(By.id("wp-submit")).click();
driver.findElement(By.linkText("Posts")).click();
driver.findElement(By.linkText("Add New")).click();
driver.findElement(By.id("title")).sendKeys("Sample");
driver.findElement(By.id("publish")).click();
driver.findElement(By.linkText("All Posts")).click();
driver.findElement(By.id("post-search-input")).sendKeys("Sample");
driver.findElement(By.id("search-submit")).click();
driver.findElement(By.xpath("/html/body/div/div[3]/div[2]/div/div[4]/form/table/thead/tr/th/input")).click();
WebElement selectBulkOption = driver.findElement(By.name("action"));
Select select = new Select(selectBulkOption);
select.selectByVisibleText("Move to Trash");
driver.findElement(By.id("doaction")).click();


Same code when used with SOB

setWebDriverObject(driver); 
uname().sendKeys("admin");
pass().sendKeys("demo123");
login().click();
posts().click();
addNew().click();
postTitle().sendKeys("Demo Post");
publish().click();
allPosts().click();
searchBox().sendKeys("Demo Post");
searchPostsButton().click();
tickAllCheckbox().click();  
postActions().selectByVisibleText("Move to Trash");
applyButton().click(); 

using SOB, it makes easier for a person to read the program. It hides the Object details keeping them separately.

Installing the Plug-In


Selenium Object Bank is available as a Plugin for Eclipse IDE. Follow the below steps for downloading and installing the plugin

Step 1:
Download the plugin
  • Open the link [ Plugin Link ]
  • Click on “File” menu and select “Download” option as shown in figure.
  • Save the zip file to your local drive and extract the folder now this directory contains the SOB plugin files.





Step 2:
Open eclipse application. Go to “help” and select “Install New Software…”
 

Step 3:
A window gets opened, now click on Add button, this time a small window appears as shown in figure




Step 4:
Click on local button and browse for the plugin directory as shown in figure and then click on OK button





Step 5:
Once the plugin directory is selected, the path is shown in the small window. Click on Ok button, you can also give the name it’s optional.

Once after clicking the Ok button you will see “Selenium Object Bank” category. Tick the checkbox and click on Next button as shown in figure. 




  • After clicking “Next” button, here it takes some time for calculating requirements and dependencies.
  • After the process is done click on “Next” button
  • Next accept the license agreement by selecting the “Accept” radio and then Click on “Finish” button.
  • During the installation it might give a Warning message. Click on OK button.



  • After the installation restart the eclipse application.
  • Done here you go … SOB is now ready to use 












Wednesday 27 November 2013

Calling multipe QTP scripts using VB file:

Well, Sometimes there comes a situation where we have to call multiple test files at a glance.
It would be cumbersome to call/open test one by one and run. Yet there are many alternative methods to achieve the same, but i love the way using array collection.
To make fully automated code/script you could even write a function to call all the tests from your test folder into the array collection dynamically and then executing the following code.Here, although, i have manually inserted every test into the array.

Function LoadNrun()
arrColl = Array(“C:\filename1″, “C:\filename2″,”C:\filename3″)
For each arrTest in arrColl
qtApp.Open arrTest
set qtTest = qtApp.Test
set objResultsOptions = CreateObject(“QuickTest.RunResultsOptions”) objResultsOptions.ResultsLocation = arrTest & “\Res1″ qtTest.Run objResultsOptions qtTest.Close
Next
End Function




*************************************************
How to close QTP Application through Code/Script/Descriptive Programming?
*************************************************

Close QTP Application:
Well,Question is simple but answer is little bit  complex. Here you need to search the desired application process on Win32_Process list.Microsoft MSDN has a good source of information on this topic. I am going to show the code without giving much explanation; Hope the code itself serves as a source of explanation
Please have a quick look on the above topic:
The Win32_Process:Win32 classes, such as Win32_NetworkAdapter or Win32_Process, monitor and manage system hardware and features. Generally, these classes are located in the root\cimv2 WMI namespace. The following table lists the Win32 class categories.WMI class represents a process on an operating system.
Source: http://msdn.microsoft.com/en-us/library/aa394084(v=VS.85).aspx

Code:
Function ClosemyApp()
Dim iCount iCount=0
Set oMyobj=GetObject(“winmgmts:\\.\root\CIMV2″)Set sCollectedProcess=oMyobj.ExecQuery(“select * from Win32_Process
where name=’QTPro.exe’ “)
For each iCount in sCollectedProcess iCount.Terminate()Next
Set sCollectedProcess=NothingSet oMyobj=Nothingmsgbox “Hurray!”
End Function


Wednesday 20 November 2013

Managing automated build dependencies with Maven and Hudson!!

One of the tricky parts of setting up a Continuous Integration build server is managing dependencies between build jobs. Many organisations have projects made up of tens or hundreds of different, interrelated modules, with complex dependencies between them. So when you change a module somewhere, you may need to rebuild and retest other modules that depend on this module.

One of the great features of Maven is the way it handles dependency management. Maven detractors may moan and groan about black magic and not being able to see what happens under the hood, but for me, declarative, transitive dependency management is a real life-saver.

Now, when you add Maven dependency management to Hudson automated builds, the result is nothing short of miraculous. Well, maybe I'm exagerating slightly, but it's certainly very cool. In short, if you use "Maven" build jobs in Hudson instead of the more frequently-used "free-style" build jobs, Hudson will figure out the correct build order all by itself - and rebuild all the other projects directly or indirectly affected by your changes.

Let's look at an example. Suppose my team is working on a Maven project called "core-api". We've already released one version of the core-api (version 1.0.0), which is available on the Maven enterprise repository for other teams. However, we are currently busy adding new features in the 1.0.1-SNAPSHOT version.

Now suppose we also have an application called "super-web-app", which we are building in conjunction with the core-api module. Now these two modules are essentially part of the same project, so we make the super-web-app depend on a snapshot release of core-api (1.0.1-SNAPSHOT). That way, I can make any changes in the core-api immediately available in the super-web-app application.

We are using Hudson as our CI server, using the "Maven" build jobs in Hudson to automatically build both these projects whenever a change goes to Subversion. Since they are intimately related, we would like the super-web-app build job to kick off whenever the core-api changes. Traditionally, you would do this by creating a post-build goal in your core-api build job to kick of the super-web-app job. But what if there are twenty other modules that depend, directly or indirectly, on the core-api? Do you have to add (and maintain) all of these post-build triggers by hand? And what if some of these other modules depend on older versions of my API, and don't give a hoot if I release a new snapshot version?

For example, across the hall, some colleages are working on the killer-web-app project. Their application still depends on core-api version 1.0.0. They are free to upgrade their version of the core-api when they need to, but it's pretty much up to them as to when they do so. So, as long as their dependency is on core-api version 1.0.0, the rebuilds of core-api-1.0.1-SNAPSHOT on Hudson should not trigger a build of their project.

The Hudson Maven projects handle this sort of build depencency management beautifully. When you kick off a build for a Maven project, it will automatically look at the other Maven build jobs on your server. If any of these depend on the Maven project currently being built, they in turn will be scheduled to be rebuilt. Note that Hudson takes into account the version number in the dependency - if core-api 1.0.1-SNAPSHOT is rebuilt, then only the modules depending on core-api-1.0.1-SNAPSHOT will be scheduled to be rebuilt - the modules depending on the older core-api-1.0.0 version will be left alone.


Note that this also works transitively, as you would imagine - if a change in project A causes Hudson to rebuild project B, and project C depends on project B, then project C will be rebuilt as well. This is a very elegent solution to a quite complex problem, and one that requires no specific configuration or maintenance in the Hudson build jobs - it relies entirely on the Maven dependencies to get the job done.

Sunday 3 November 2013

Small Example for Data Driven(Reading data from xl files)In QT P !!!!!!!!!!!!!!!!!!

Step 1) Lets Create these functions First(These functions are independent we can use these functions  for any application)

Function No1:-getRowCount
Function getRowCount(filePath,sheetName)
          '  all the cells for all the cols are empty
          ' know total cols in the sheet
Dim cols,isRowPresent,rows,isLastRow
cols = getColumnCount(filePath,sheetName)
rows=1 '  assuming there is one row
isRowPresent = true
isLastRow= false
     While isRowPresent
' check to see if all the cells are empty or not
Dim colNum
For colNum=1 to cols
If  readData(filePath,sheetName,rows,colNum) <> ""  Then
' this is not the last row
rows=rows+1
Exit for
End If
'    if you have just read the last cell
If  colNum = cols Then
' this is the last row
isLastRow = true
Exit for
End If
Next

' check if  its the last row
If  isLastRow Then
isRowPresent=false
End If
Wend

getRowCount=  (rows-2)

End Function

Function No2:- getColumnCount

'return total cols in a sheet
Function getColumnCount(filePath,sheetName)
Dim colCount
colCount=0 '  assume no cols
While trim(readData(filePath,sheetName,1,(colCount+1))) <> ""
colCount = colCount+1
Wend
getColumnCount= colCount


End Function

Function No3 :readData

Function readData(filePath, sheetName, row,col)
   Set objXls = createobject("Excel.application")  '' microsoft  xl
   objXls.Visible= false
   objXls.DisplayAlerts=false
   ' exit the function if file is not present
If NOT isFilePresent(filePath) Then
msgbox "FILE NOT PRESENT " & filePath
Exit function
End If

Set myXls = objXls.Workbooks.Open (filePath)
Set sheet = myXls.Sheets(sheetName)
readData = sheet.cells(row,col).value
' close everything
    myXls.Close
objXls.Quit

' destroy object
  Set objXls=nothing
  Set myXls=nothing
  Set sheet=nothing
End Function

Function No4:closeAllBrowsers

Function closeAllBrowsers
Dim desc,allBrowsers,i
   Set desc = description.Create
desc("micclass").value="Browser"
Set allBrowsers = desktop.ChildObjects(desc)
For i=0 to allBrowsers.count-1
   Browser("creationtime:="&i).close
Next

Set desc=Nothing
Set allBrowsers =Nothing
End Function


Function No5: isFilePresent

' function returns true if  file is present and false if not present
Function isFilePresent(filePath)
Set fso = createobject("Scripting.FileSystemObject")
If  fso.FileExists(filePath)  Then
isFilePresent = true
else
       isFilePresent=false
End If
' destroy object
Set fso= nothing

End Function



Step 2)Add these functions into your Action

Step 3)And follows The script 

Dim Login,Pwd,cnt
cnt=getRowCount("c:\abc.xls","Login")
'c:\abc.xls=path of your xls file 
'Login=sheet name 
msgbox cnt
For i=2 to cnt+1
closeAllBrowsers
Systemutil.Run  "http://www.salesforce.com","firefox"
set a=Browser("title:=.*").Page("title:=.*")
'a.Sync
a.link("name:=Login").Click
Login=readData ("c:\abc.xls","Login",i,1)
'msgbox Login
pwd=readData ("c:\abc.xls","Login",i,2)
'msgbox pwd
a.webedit("name:=username").Set Login
a.webedit("name:=pw").Set Pwd
a.webbutton("name:=Log in to Salesforce").Click
a.Sync
next

*******************************************************



Thursday 31 October 2013

Working with Regular Expression (RegExp) Object in QTP

Function 

Function FindPatternMatches(str,pat)
Set regEx = New RegExp
regEx.pattern=pat
regEx.ignorecase=true
regEx.global=true

msgbox "Patterne found-"&regEx.test(str)
Set matches=regEx.execute(str)
msgbox "Total Matchec found-"&matches.count
For i = 0 To matches.count-1
Set match=matches(i)
msgbox "Value found at index-"&match.firstindex&"..Match value---"&match.value
Next

End Function

Examples

s="Welcome Sudhakar you have 88 Unread Mails"
p="[a-zA-Z0-9]+"
p="^Welcome[a-zA-Z]+[.]\s you have[0-9]+Unread Mails[.]"
p="([a-zA-Z]+)([.])|([0-9]+)"
FindPatternMatches s,p


s="HCQ9D-TVCWX-X9QR1-J4B2Y-2GR2T"
p="[A-Z0-9]{5}-{0,1}"
FindPatternMatches s,p


s="Email id is mg_sudha06@yahoo.co.in or mgsudha09@rediffmail.com or sudhakar8871@gmail.com"
p="[a-zA-Z0-9]{3,}@[a-zA-Z]{1,}[.][a-zA-Z]{1,}"
FindPatternMatches s,p


s="dates are 21/01/2012 01/11/2013 01/01/2014 23/01/2014"
p="((0[0-9])|(1[0-9])|(2[0-9])|(3[0-9]))/((0[1-9])|(1[0-2]))/[0-9]{4}"

FindPatternMatches s,p

***********************************************************************************

Monday 28 October 2013

Working with DotNetFactory in QTP!!!!

'create the .net screen
Set screen=DotNetFactory("System.Windows.Forms.Screen")

Set allscreens=screen.AllScreens

'msgbox "Total Availble screens---"& allscreens.length
'Get the enumerator for current array
Set enumScreen=allscreens.GetEnumerator()

While enumScreen.Movenext
Set oscreen=enumScreen.current
msgbox "Device Name--"+oscreen.devicename
msgbox "Bound---"&oscreen.Bounds.tostring()
msgbox "Type---"&oscreen.gettype().tostring()
msgbox "Working Area---"&oscreen.workingarea.tostring()
msgbox "Primary Screen---"&oscreen.primary.tostring()
msgbox vbnewline
Wend

**********************************************************************************
'Create .net audio object
Set obj=DotNetFactory("Microsoft.VisualBasic.Devices.Audio","Microsoft.VisualBasic")
'play the wav file
obj.play "C:\WINDOWS\Media\Windows XP Shutdown.wav"
set obj=nothing

Handling Java script..in Selenium

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class check_box {

@SuppressWarnings("unchecked")
@Test
public void testDefaultSelectedCheckbox() {

WebDriver driver=new FirefoxDriver();
driver.get("http://dl.dropbox.com/u/55228056/Locators.html");
//Expected list of selected Checkbox
List<String> checked = Arrays.asList(new
String[]{"user1_admin", "user3_browser"});
//Create an instance of JavaScript Executor from driver
JavascriptExecutor js = (JavascriptExecutor) driver;
//Locate all the Checkbox which are checked by calling jQuery
//find() method.
//find() method returns elements in array
List<WebElement> elements = (List<WebElement>)
js.executeScript("return jQuery.find(':checked')");
//Verify two Checkbox are selected

assertEquals(elements.size(),2);
//Verify correct Checkbox are selected
for (WebElement element : elements)
assertTrue(checked.contains(element.getAttribute("id")));
driver.close();



}

}

Sunday 27 October 2013

What is the difference between RD and REQM?

Requirements Management, or "REQM," is all about maintaining the set of requirements that you have, and the process of accepting new ones. In the CMMI world, that includes understanding them, committing to them, managing changes to them, maintaining the appropriate degree of traceability, and understanding how they relate to the actual work being performed by the team.

Requirement Development, or "RD," is about the transformation of customer needs into requirements that can then evolve into a design and/or code. This includes eliciting the customer needs (JAD sessions, interviews, et al), transforming those needs into requirements, evolving them into product requirements, allocating the requirements across releases, teams, developers, or modules, validating them, and ensuring that they fit within the customer constraints and assumptions.

I am not aware of one single tool that does all of this, but parts can be supported by Borland's CaliberRM, IBM's ReqPro, or Doors. My preference is CaliberRM, but they all pretty much do the same thing. They are also all parts of a larger "development framework" that these companies market.

Monday 30 September 2013

Checking for Broken images on Web Page

'Function to check for broken images on Page

public function checkbrokenimages(opage)
pgtitle=opage.getroproperty("title")
set allimages=opage.object.images
icount=allimages.length-1
for i =0 to icount
set curimg=allimages.item(i)
shtml="HTML="&curimg.outerHTML
if curimg.filesize=-1 then
'the image didnt load
reporter.reportevent micfail,pgtitle& "Broken Image",shtml
else
reporter.reportevent micpass,pgtitle& "Valid Image",shtml
end if
next
end function

checkbrokenimages  browser("micclass:=browser","index:=0").page("micclass:=page")

Note:We have used the DOM in this example given above because QTP child objects function will not search in side the web table objects. Some of the images the web table might get ignored while using the childobjects method



Thursday 19 September 2013

Selenium Grid Installations

Download Required

1) selenium-server-standalone-ver.jar : All client machines and Server Machine


Steps :

Step 1 : Start the hub : Start hub on the Server machine with below command

java -jar selenium-server-standalone-2.28.0.jar -role hub

The hub will automatically start-up using port 4444 by default. To change the default port, you can add the optional parameter -port when you run the command. You can view the status of the hub by opening a browser window and navigating to: http://localhost:4444/grid/console

Step 2: Start the nodes : Regardless on whether you want to run a grid with new WebDriver functionality, or a grid with Selenium 1 RC functionality, or both at the same time, you use the same selenium-server-standalone jar file to start the nodes.

java -jar selenium-server-standalone-2.14.0.jar -role node  -hub http://localhost:4444/grid/register

-browser  browserName=firefox,version=3.6,maxInstances=5,platform=LINUX : This can be supplied .
For Windows : platform=WINDOWS
Note: The port defaults to 5555 if not specified whenever the "-role" option is provided and is not hub.

Using grid to run tests

 For WebDriver nodes, you will need to use the RemoteWebDriver and the DesiredCapabilities object to define which browser, version and platform you wish to use. Create the target browser capabilities you want to run the tests against:

 

DesiredCapabilities capability = DesiredCapabilities.firefox();

 

Pass that into the RemoteWebDriver object:
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
The hub will then assign the test to a matching node.
A node matches if all the requested capabilities are met. To request specific capabilities on the grid, specify them before passing it into the WebDriver object.
capability.setBrowserName();
capability.setPlatform();
capability.setVersion()
capability.setCapability(,);
Example: A node registered with the setting:
 -browser  browserName=firefox,version=3.6,platform=LINUX
will be a match for:
capability.setBrowserName(“firefox ); 
capability.setPlatform(“LINUX”);  
capability.setVersion(“3.6”);
and would also be a match for
capability.setBrowserName(“firefox ); 
capability.setVersion(“3.6”);

Code Snippet : 

import java.net.MalformedURLException;
import java.net.URL;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;


public class testremote {

    @Test
    public void test1() throws MalformedURLException{
  
    DesiredCapabilities capability = DesiredCapabilities.firefox();
    capability.setBrowserName("firefox");
    capability.setVersion("18.0.2");
    WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
    driver.get("http://google.com");
  
  
}
  
}