Saturday, November 9, 2013

Delete Cookies

Methods related to cookies:
  • WebUtil.Addcookie
  • WebUtil.Deletecookie
  • WebUtil.Deletecookies 'deletes all cookies in the system
  • WebUtil.Getcookies

Delete cookies using Windows shell object:

SysUserName=Environment.Value("UserName")
Set ShellObj=CreateObject("WScript.shell")
ShellObj.run("cmd /C cd C:\Documents and Settings\" & SysUserName & "\Cookies & del *.txt")
Set ShellObj=nothing

The above two methods works only with IE browsers.

Saturday, September 7, 2013

Dynamic Descriptive Programming

Entering Objects Information directly into the test script is called descriptive programming. In DP, we will be "manually" specifying the set of properties and values by which the relevant object will be identified. This way QTP won’t search for the properties data in the Object Repository, but will take it from the DP statement directly.

Object Spy is used to get the properties and their values to uniquely identify the objects in the application. If we know such properties and their unique values that can identify the required object without ambiguity, we need not use Object Spy.

Two ways of descriptive programming:

1. Static Programming: We provide the set of properties and values that describe the object directly in a VBScript statement.


2. Dynamic Programming: We add a collection of properties and values to a Description object, and then enter the description object name in the statement.



'Dynamic Descriptive Programming
'*************** Dynamic descriptive Programing **************
'**************** Page Used: Google - Products****************

'Launch Google - Products
Systemutil.Run "iexplore.exe","http://www.google.com/intl/en/about/products/"

'Descriptive object to identify  Browser  with a particular title
Set  Dbrowser=Description.Create
Dbrowser("micclass").Value="Browser"
Dbrowser("name").Value="Google - Products"

'Descriptive object to identify  Web page with a particular title
Set  Dpage=Description.Create
Dpage("micclass").Value="Page"
Dpage("title").Value= "Google - Products"

Browser(Dbrowser).Page(Dpage).Sync  'wait till browser sync

'Descriptive object to identify a  particular Link
Set  DLink=Description.Create
'DLink("micclass").Value="Link"
DLink("html tag").Value="A"

Set objLinkCount=Browser(Dbrowser).Page(Dpage).ChildObjects(DLink) 'Returns the childobjects having 'Linkobject' description.
vrDLinkCount = objLinkCount.Count  'Returns number of links on webpage
MsgBox vrDLinkCount

For i=0 to vrDLinkCount-1
                vrTag = objLinkCount(i).GetROProperty("name")
                vrHREF = objLinkCount(i).GetROProperty("url")
                msgbox vrTag & ": " &vrHREF

Next

Thursday, August 15, 2013

COM or 'Component Object Model'

COM or 'Component Object Model' is a method by which an application exposes its functionalities to other applications & programming languages using a set of methods and functions.

As an example consider Microsoft Outlook Application. You can open Outlook and then send mails, manage appointments & do many other things. Now what if you want to do all these tasks through code ( i.e. without manually opening Outlook). This is the situation where you would need COM. 

Microsoft Outlook exposes all its functionalities in form of certain methods and properties. You can access these methods using any programming language like C#, VBA, VBScript etc and directly interact with MS Outlook. 

Check out the below code to send mail using MS Outlook.
'Create an object of type Outlook
Set objOutlook = CreateObject("Outlook.Application")
Set myMail = objOutlook.CreateItem(0)
 
'Set the email properties
myMail.To = "some_m...@gmail.com"
myMail.Subject = "Sending mail from MS Outlook using QTP"
myMail.Body= "Test Mail Contents"

'Send the mail
myMail.Send

Wednesday, August 14, 2013

Working With MS Excel

'Create a new excel, insert data into Cell, rename the sheet, Save and Close
Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Add
Set NewSheet = objExcel.Sheets.Item(1)
NewSheet.Name = "New"
NewSheet.Cells(2,2) = "USER"
objExcel.ActiveWorkbook.SaveAs "D:\ENCRYPTED\LearningQTP\CreateExcel.xlsx"
objExcel.Quit
Set objExcel = Nothing
Set objWorkBook = Nothing

Set objWorkSheet = Nothing

'Excel Search String Color Text and Bold and FontSize

Dim vrSearchString

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("D:\ENCRYPTED\Learning_QTP\Data_Files\Test.xls")
Set objWorkSheet = objExcel.Worksheets("Sheet3")
objExcel.Application.Visible = True

With objWorkSheet.UsedRange 'select the used range in particular sheet
Set vrSearchString = .Find (hardeep) ' data to find
For each vrSearchString in objWorkSheet.UsedRange' Loop through the used range
If vrSearchString="hardeep" then '’ compare with the expected data
   vrSearchString.Interior.ColorIndex = 40' make the yellow color if it finds the data
   vrSearchString.Font.FontStyle = "Bold"
   vrSearchString.Font.ColorIndex = 5
   vrSearchString.Font.Size = 14
CellAddress =vrSearchString.address
msgbox CellAddress
End If


Set vrSearchString = .FindNext(vrSearchString) ' next search

Next
End With

objExcel.ActiveWorkbook.Save
objExcel.Quit
Set objExcel = Nothing
Set objWorkBook = Nothing
Set objWorkSheet = Nothing

'Open an existing excel, Active sheet2, insert data into Cells, Save and Close

Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Open("D:\ENCRYPTED\LearningQTP\Test.xlsx")
objExcel.Application.Visible = True
Set objWorkSheet = objWorkBook.Worksheets("Sheet2")
objExcel.Worksheets("Sheet2").Select

objWorkSheet.Cells(1,1) = "This"
objWorkSheet.Cells(2,1) = "is"
objWorkSheet.Cells(3,1) = "for"
objWorkSheet.Cells(4,1) = "QTP"
objWorkSheet.Cells(5,1) = "TEST"

objExcel.ActiveWorkbook.Save

objExcel.Quit
Set objExcel = Nothing
Set objWorkBook = Nothing
Set objWorkSheet = Nothing



'Open an existing excel, Insert a new sheet, insert data into Cells, Save and Close

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("D:\ENCRYPTED\LearningQTP\Test.xlsx")
Set objWorkSheet = objExcel.Worksheets("Sheet3")
objExcel.Application.Visible = True

objExcel.Worksheets.Add
Set NewSheet = objExcel.Sheets.Item(1)
NewSheet.Name = "New Worksheet"
NewSheet.Cells(2,2) = "USER"

objExcel.ActiveWorkbook.Save
objExcel.Quit
Set objExcel = Nothing
Set objWorkBook = Nothing
Set objWorkSheet = Nothing




'Open an existing excel, Rename a worksheet, Save and Close

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("D:\LearningQTP\Test.xlsx")
Set objWorkSheet = objExcel.Worksheets("HS")
objExcel.Application.Visible = True

objExcel.Sheets("Sheet5").Select
objExcel.Sheets("Sheet5").Name = "ABCDE"

objExcel.ActiveWorkbook.Save
objExcel.Quit
Set objExcel = Nothing
Set objWorkBook = Nothing
Set objWorkSheet = Nothing



'Open an existing excel, Search for a word, Highlight it, Save and Close

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("D:\ENCRYPTED\LearningQTP\Test.xlsx")
Set objWorkSheet = objExcel.Worksheets("Sheet3")
objExcel.Application.Visible = True

With objWorkSheet.UsedRange 'select the used range in particular sheet
Set c = .Find ("hardeep") ' data to find
For each c in objWorkSheet.UsedRange' Loop through the used range
If c="hardeep" then '’ compare with the expected data
c.Interior.ColorIndex = 40' make the yellow color if it finds the data

CellAddress =c.address
msgbox CellAddress

End If
Set c = .FindNext(c) ' next search

next
End With

objExcel.ActiveWorkbook.Save
objExcel.Quit
Set objExcel = Nothing
Set objWorkBook = Nothing
Set objWorkSheet = Nothing

Monday, July 15, 2013

Utility Objects

QTP provides several utility objects to enhance the power of scripting.
Below is a list of all QTP utility objects.

Crypt, DataTable, Description, DTParameter, DTSheet, Environment, Extern, OptionalStep, Parameter, PathFinder, Properties(Collection), QCUtil, Random Number, Recovery, Reporter, Services, Setting, TextUtil, TSLTest, XMLUtil

  •   Crypt Object
  •   OptionalStep Object
  •   PathFinder Object
  •   RandomNumber Object
  •   Setting Object
  •   Add Method
  •   Exists Method
  •   Remove Method
  •   WebUtil Object
  •   SystemUtil Object
  •   RegisterUserFunc Object


Saturday, July 13, 2013

Working With RegExp


The Regular Expression object provides simple regular expression support.

Properties

Global Property
IgnoreCase Property
Pattern Property

Methods

Execute Method
Replace Method

Test Method

'RegExp

Set regEx = New RegExp   ' Create a regular expression.
   regEx.Pattern = "[a-zA-Z0-9]"   ' Set pattern.
   regEx.IgnoreCase = True   ' Set case insensitivity.
   regEx.Global = True   ' Set global applicability.

'RegExp

lovePoem = "How do I love thee? Let me count the ways."
lovePoem = lovePoem & "I love thee to the depth and breadth and height"
lovePoem = lovePoem & "My soul can reach, when feeling out of sight"
lovePoem = lovePoem & "For the ends of Being and ideal Grace."
lovePoem = lovePoem & "I love thee to the level of everydays"
lovePoem = lovePoem & "Most quiet need, by sun and candle-light."
lovePoem = lovePoem & "I love thee freely, as men strive for Right;"
lovePoem = lovePoem & "I love thee purely, as they turn from Praise."
lovePoem = lovePoem & "I love thee with a passion put to use"
lovePoem = lovePoem & "In my old griefs, and with my childhoods faith."
lovePoem = lovePoem & "I love thee with a love I seemed to lose"
lovePoem = lovePoem & "With my lost saints, — I love thee with the breath,"
lovePoem = lovePoem & "Smiles, tears, of all my life! — and, if God choose,"
lovePoem = lovePoem & "I shall but love thee better after death."

'===============================================================
'Using RegExp — How to count the number of times the word “love” appears in the poem:
'
'To count the number of times a word (or any pattern) appears in a string, you can use QTP with VBScript’s RegExp object, along with the Pattern property and Execute method.
'
'The Pattern property can set or return any regular expression pattern you wish to search for.
'=============================================================
'The Execute method is used to run a search using a regular expression:
'=============================================================
Set re = New RegExp
 re.Global = True
 re.Pattern = "love"
 Set loveMatch = re.Execute(lovePoem)
 MsgBox loveMatch.Count

'==============================================================
'Replace Method
'
'You can also use the Replace method to count the appearances of a word or pattern.
'This method replaces the text found in a search using a regular expression.
'To replace all the occurrences of the word thee with you in the poem you can do the following:
'===============================================================

 Set re = New RegExp
 re.Global = True
 re.Pattern = "thee"
 MsgBox re.Replace(lovePoem,"you")


Function ReplaceTest(patrn, replStr)
  Dim regEx, str1               ' Create variables.
  str1 = "The quick brown fox jumped over the lazy dog."
  Set regEx = New RegExp            ' Create regular expression.
  regEx.Pattern = patrn            ' Set pattern.
  regEx.IgnoreCase = True            ' Make case insensitive.
  ReplaceTest = regEx.Replace(str1, replStr)   ' Make replacement.
End Function

MsgBox(ReplaceTest("fox", "cat"))      ' Replace 'fox' with 'cat'.

'In addition, the Replace method can replace subexpressions in the pattern. The following call to the function shown in the previous example swaps each pair of words in the original string: 

Monday, July 8, 2013

Working with WSCRIPT

Work with command prompt using QTP(vbscript) 
We can use Windows Shell object to start a command prompt and execute the command.

In the following i want to list all files\folders in C drive:
Set wscriptObj=createobject("WScript.Shell")
wscriptObj.Run "cmd /K cd c:\ & dir"

When i execute the above statement, it opens the command prompt and execute dir command.

You are free to use any command you want as per your needs.


Invoke Browser


Set WShelObj=Createobject("WScript.Shell")
WShelObj.Run Chr(34) & "C:\Program Files\Internet Explorer\iexplore.exe" & Chr(34)&" "&"www.yahoo.com"
or
Set WShelObj=Createobject("WScript.Shell")
WShelObj.Run Chr(34) & "C:\Program Files\Internet Explorer\iexplore.exe" & Chr(34)
Browser("name:=.*").Navigate "www.yahoo.com"
Char(34) is used to append double quotes to the IE application path.





Working with Web Links

'***************************** Dynamic descriptive Programing **********************************
'***************************** Page Used: Google - Products*************************************
'**************To Count all the Links on Web Page and Display their Names with URL**************

'Launch Google - Products
Systemutil.Run "iexplore.exe","http://www.google.com/intl/en/about/products/"

'Descriptive object to identify  Browser  with a particular title
Set  Dbrowser=Description.Create
Dbrowser("micclass").Value="Browser"
Dbrowser("name").Value="Google - Products"

'Descriptive object to identify  Web page with a particular title
Set  Dpage=Description.Create
Dpage("micclass").Value="Page"
Dpage("title").Value= "Google - Products"

'Descriptive object to identify a  particular Link
Set  DLink=Description.Create
'DLink("micclass").Value="Link"
DLink("html tag").Value="A"

'wait till browser sync
Browser(Dbrowser).Page(Dpage).Sync

Set objLinkCount=Browser(Dbrowser).Page(Dpage).ChildObjects(DLink) 'Returnz the childobjects having 'Linkobject' description.
vrDLinkCount = objLinkCount.Count  'Returns number of links on webpage
MsgBox vrDLinkCount

For i=0 to vrDLinkCount-1
vrTag = objLinkCount(i).GetROProperty("name")
vrHREF = objLinkCount(i).GetROProperty("url")
msgbox vrTag & ": " &vrHREF
Next

'*=================Static descriptive Programing ================
'====================With HTMLTag  ==========================

Set ObjDes = Description.Create() 'Creates a new Empty Description Object
ObjDes("html tag").Value = "A" 'Adding Properties and Values to Descript Object

Systemutil.Run "iexplore.exe","http://www.google.com/intl/en/about/products/"

Set ChildObjCount = Browser("name:=Google - Products").Page("title:=Google - Products").ChildObjects (ObjDes) 'Gets the count of all Child Objects based on added description
NumCounts = ChildObjCount.Count() ' Gets the count of Descript values
Reporter.ReportEvent micPass, "The Number of Links on this page is", "Links Count = "&NumCounts ' Prints the Count of Links of the Page in Test Results
For i = 0 to NumCounts - 1 ' Making a For Loop to get all Similar Descript Values
Htag = ChildObjCount(i).GetROProperty("innertext") ' Gets the inner text of the value
Href =ChildObjCount(i).GetROProperty("href") 'Gets the Href of the inner text
Reporter.ReportEvent micPass, "The Name of the Link with URL", "Name: "& Htag&" and Url:" & Href ' reports the Tag and Href values to Test Results
Next


'*=================Static descriptive Programing ================
'==================== With MicClass ==========================

Systemutil.Run "iexplore.exe","http://www.google.com/intl/en/about/products/"

set linkobject=Description.Create 'This line is used to create description object
linkobject("Micclass").value="link" 'This line is used to identify the property.( In our case its link)
set linkcount=Browser("name:=Google - Products").Page("title:=Google - Products").ChildObjects(linkobject) 'This line is used to return the childobjects having 'Linkobject' description.
a= linkcount.Count  'This line is used get number of links on a webpage
MsgBox a

For i=0 to a-1
tag = linkcount(i).GetROProperty("name")
href = linkcount(i).GetROProperty("url")
msgbox tag & ": " &href
Next

'==============Dynmic  Descriptive Programing ===================
' To Count  Number of Links with a Particular Name on a Web Page
'=============================================================


SystemUtil.Run "iexplore", "http://youngistaancafe.blogspot.com/2013/07/student-registration-formhtml.html"

'Descriptive object to identify  Browser  with a particular title

Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
oBrowser("name").Value = "Youngistaan Cafe: Student Registration Form.html"

Set oPage=Description.Create
oPage("micclass").Value="Page"
oPage("title").Value="Youngistaan Cafe: Student Registration Form.html"

Browser(oBrowser).Page(oPage).Sync

'Descriptive object to identify a  particular WebLink
Set oLink = Description.Create
oLink("micclass").Value = "Link"

Set oWebLinkCount = Browser(oBrowser).Page(oPage).ChildObjects(oLink)
vrCount = oWebLinkCount.Count

Counter = 0

'To Count the Number of Links with Name as "Home"

For i=0 to vrCount-1
vrLinkName = oWebLinkCount(i).GetROProperty("name")
       
If vrLinkName = "Home" Then
Counter = Counter +1
End If

Next

msgbox  "Number of lInks with name Home are: " &Counter

Friday, July 5, 2013

Working with WebList

'============= Ways to select value from WebList =======================

Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:=lr").Select "#3"
Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:=lr").Select (1)
Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:=lr").Select "English"


'========== To Count Number of WebList in a Page Using Mic Class =================

Set oWebList=Description.Create
oWebList("micclass").value="WebList"
set objList=Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").ChildObjects(oWebList)
vrCount = objList.Count

For i=0 to vrCount-1
msgbox objlist(i).getroproperty("name")
Next

'=========== To Count Number of WebList in a Page Using HTMLTag ==============

Set oWebList=Description.Create
oWebList("html tag").Value = "SELECT"
Set objList=Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").ChildObjects(oWebList)
vrCount = objList.Count

For i=0 to vrCount-1
msgbox objlist(i).getroproperty("name")
Next

'================================ To Get Values of  all items present in any particular WebList  ============================================

    vrItemCount = Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:=as_filetype").GetROProperty("items count")

For j=1 to vrItemCount
vrValue = Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:=as_filetype").GetItem(j)
msgbox vrValue
Next

'============== To Get All the Values of  all WebList  in a WebPAge===================

Set oWebList=Description.Create
oWebList("micclass").value="WebList"
set objList=Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").ChildObjects(oWebList)
vrCount = objList.Count

For i=0 to vrCount-1
vrWebListName = objlist(i).getroproperty("name")
vrItemCount = Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:="&vrWebListName).GetROProperty("items count")
msgbox vrItemCount
For j=1 to vrItemCount
vrValue = Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:="&vrWebListName).GetItem(j)
msgbox vrValue
Next
Next

'===========  To Check Existence of Item in Web List ======================

Function fnWebLIstItemExistence(vrSearchItem)

vrItemCount = Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:=as_filetype").GetROProperty("items count")
msgbox vrItemCount


For j=1 to vrItemCount
vrWebItem = Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebList("name:=as_filetype").GetItem(j)
If vrSearchItem = vrWebItem Then
Reporter.ReportEvent micPass, "Result", "vrSearchItem Exist in the Web List"
Else
Reporter.ReportEvent micFail, "Result", "vrSearchItem not Found in the Web List"
End If
Next

End Function


Call fnWebLIstItemExistence("Shockwave Flash (.swf)")


' ======= To Select more than one Item in a WebList ==============================

'The following example uses the ExtendSelect method to select two additional items from a WebList object and then checks
'if the items were actually selected. The results of the
'check are sent to the Test Results.

Browser("Find a Flight: Mercury").Page("Fill-Out Form Example").WebList("what-to-wear").Select "Rugby Shirt"
Browser("Find a Flight: Mercury").Page("Fill-Out Form Example").WebList("what-to-wear").ExtendSelect "Leather Jacket"
Browser("Find a Flight: Mercury").Page("Fill-Out Form Example").WebList("what-to-wear").ExtendSelect "Boots"

'Check if all items that were selected in the previous steps are
'actually selected in the list and send

CurrentSelection = Browser("Find a Flight: Mercury").Page("Fill-Out Form Example").WebList("what-to-wear").GetROProperty("selection")
If CurrentSelection <> "Rugby Shirt;Leather Jacket;Boots" Then
    Reporter.ReportEvent micFail, "ExtendSelect", "The list does not contain all of the selected items."
Else
   Reporter.ReportEvent micPass, "ExtendSelect", "The list contains all selected items."
End If

'============= To check if Items in a WebList are sorted or not=================



Working with WebCheckBox

'============= Ways to select value from WebCheckBox=======================

Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebCheckBox("name:=lr").Set"ON"
Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").WebCheckBox("name:=lr").Set "OFF"

'========== To Count Number of WebCheckBox in a Page Using Mic Class =================

Set oWebCheckBox=Description.Create
oWebCheckBox("micclass").value="WebCheckBox"
set objCheckBox=Browser("name:=Google Advanced Search").Page("title:=Google Advanced Search").ChildObjects(oWebCheckBox)
vrCount = objCheckBox.Count

For i=0 to vrCount-1
msgbox objCheckBox(i).GetROProperty("name")
Next

Thursday, July 4, 2013

Working with WebButton

'Working With WebButton

SystemUtil.Run "iexplore", "http://youngistaancafe.blogspot.com/2013/07/student-registration-formhtml.html"

Set oWebButton = Description.Create 'This line is used to create description object
oWebButton("micclass").Value = "WebButton"  'This line is used to identify the property.( In our case its link)
Set oWebButtonCount = Browser("name:=Youngistaan Cafe: Student Registration Form.html").Page("title:=Youngistaan Cafe: Student Registration Form.html").ChildObjects(oWebButton)  'This line is used to return the childobjects having 'WebButton object' description.
vrCount = oWebButtonCount.Count 'This line is used get number of buttons on a webpage
MsgBox vrCount

For i=0 to vrCount-1
                Button_Name = oWebButtonCount(i).GetROProperty("name")
    MsgBox  "Button: " &Button_Name 

Next

Tuesday, July 2, 2013

Working with WebEdit

'Working with Web Edit

'======== To Count Number of WebEdit in a Page Using MicClass ===============================

Set oWebEdit=Description.Create
oWebEdit("micclass").value="WebEdit"
Set oWebEditCount = Browser("name:=Youngistaan Cafe: Student Registration Form.html").Page("title:=Youngistaan Cafe: Student Registration Form.html").ChildObjects(oWebEdit)
vrCount = oWebEditCount.Count
msgbox vrCount

For i=0 to vrCount-1
print oWebEditCount(i).getroproperty("Name")

Next

Friday, June 14, 2013

Working with WebRadioGroup

QTP WebRadioGroup means a radio button on the web page. Identifying and working with them can be easy or difficult. Sometimes they works out fine and at times executing the same code gives you error. 

If you have two radio buttons on the screen for example Gender selection options the code below might give problem.

Browser("name:=Youngistaan Cafe: Student Registration Form.html").Page("title:=Youngistaan Cafe: Student Registration Form.html").WebRadioGroup("name:=Gender").Select "Male"
Where "Male" can be the id or the value of the radio button (Spy the object). So what is the problem in the code above? As there are two radio buttons QTP identifies them as same, so we need to differentiate between them. Index is a property by which you can differentiate, it tells the position of the object. So if we write the same code below with an additional index property it will work fine.
Browser("name:=Youngistaan Cafe: Student Registration Form.html").Page("title:=Youngistaan Cafe: Student Registration Form.html").WebRadioGroup("name:=Gender", "index:= 1").Select "Female"
This code is intended to select a radio button among two, what if you have a list of radio buttons let’s say 5-6 or more, than the above code won’t help. For that you need to create description of a radiogroup i.e. we will instruct everything to QTP.

''''''=====Initialize variables
Dim oWebRadio
Dim oWebRadioCount
Dim RadioToSelect_Val 

''''''Create description using Description.Create build-in method
Set oWebRadio = Description.Create
oWebRadio ("micclass").value = "WebRadioGroup"
oWebRadio ("type").value = "radio"
oWebRadio ("name").value="Gender"

''''''Pass the description in another variable using ChildObjects method
Set oWebRadioCount = Browser("name:=Youngistaan Cafe: QTP Web Table").Page("title:=Youngistaan Cafe: QTP Web Table").ChildObjects(oWebRadio)
''''''Loop to select desired value
For i = 0 to oWebRadioCount
RadioToSelect = oWebRadioCount (i).GetROProperty("value")
oWebRadioCount (i).Select RadioToSelect
Next

''''''Pass Child count in a variable
allItems = oChild.Count

''''''Loop & Use items count property to get Total items
For j = 0 to allItems-1
   itemsCount =oChild.Item(j).GetRoProperty("items count")

      If (itemsCount = 5) Then
          Print "Found 5 radio " 
      else
          Print "More than 5 radio listed"
      End If

Next

So there are two ways to deal with descriptive programming, either pass the properties directly or create your descriptions and pass or select your values.


'============= Ways to select value from WebList =======================

Browser("name:=Youngistaan Cafe: QTP Web Table").Page("title:=Youngistaan Cafe: QTP Web Table").WebTable("name:=Passenger 1").WebRadioGroup("name:=rnd_pnr").Select "#3"
Browser("name:=Youngistaan Cafe: QTP Web Table").Page("title:=Youngistaan Cafe: QTP Web Table").WebTable("name:=Passenger 1").WebRadioGroup("name:=rnd_pnr").Select "2218866589&15-5-2013"


Browser("name:=Youngistaan Cafe: Student Registration Form.html").Page("title:=Youngistaan Cafe: Student Registration Form.html").WebRadioGroup("name:=Gender").Select "#0"
Browser("name:=Youngistaan Cafe: Student Registration Form.html").Page("title:=Youngistaan Cafe: Student Registration Form.html").WebRadioGroup("name:=Gender").Select "Female"


'========== To Count Number and Name of WebRadioGrouppresent on a Page Using MicClass ======

'Example: 1  This page has One Radio Group

SystemUtil.Run "iexplore", "http://youngistaancafe.blogspot.com/2013/07/qtp-web-table_5925.html"
Set oWebRadio = Description.Create
oWebRadio("micclass").value="WebRadioGroup"
Set oWebRadioCount = Browser("name:=Youngistaan Cafe: QTP Web Table").Page("title:=Youngistaan Cafe: QTP Web Table").ChildObjects(oWebRadio)
vrCount = oWebRadioCount.Count
msgbox vrCount

For i=0 to vrCount-1
msgbox oWebRadioCount(i).GetROProperty("name")
Next

'Example: 2 This page has Two Radio Groups

SystemUtil.Run "iexplore", "http://youngistaancafe.blogspot.com/2013/07/student-registration-formhtml.html"

Set oWebRadio = Description.Create
oWebRadio("micclass").value="WebRadioGroup"
Set oWebRadioCount = Browser("name:=Youngistaan Cafe: Student Registration Form.html").Page("title:=Youngistaan Cafe: Student Registration Form.html").ChildObjects(oWebRadio)
vrCount = oWebRadioCount.Count
msgbox vrCount

For i=0 to vrCount-1
msgbox oWebRadioCount(i).GetROProperty("name")
Next


'To find Number of Radio Buttons present in particular Group along with its value

With Browser("name:=Youngistaan Cafe: QTP Web Table").Page("title:=Youngistaan Cafe: QTP Web Table").WebTable("name:=Passenger 1").WebRadioGroup("name:=rnd_pnr")

vrAllItem = .GetROProperty("all items")
msgbox vrAllItem

vrArr = Split(vrAllItem, ";", -1, 1)

For i=0 to UBound(vrArr)
          msgbox vrArr(i)
          vrLeftPNR = Left(vrArr(i),10)
          msgbox vrLeftPNR
          If vrPNR = vrLeftPNR Then
                   vrIndex = i
        .Select "#"&vrIndex
                   Exit For
          End If
Next
End With


'=========Select  WebRadio button where PNR# is 5018866589================

vrPNR = "5018866589"
With Browser("name:=Youngistaan Cafe: QTP Web Table").Page("title:=Youngistaan Cafe: QTP Web Table").WebTable("name:=Passenger 1").WebRadioGroup("name:=rnd_pnr")

vrAllItem = .GetROProperty("all items")
msgbox vrAllItem

vrArr = Split(vrAllItem, ";", -1, 1)

For i=0 to UBound(vrArr)
          msgbox vrArr(i)
          vrLeftPNR = Left(vrArr(i),10)
          msgbox vrLeftPNR
          If vrPNR = vrLeftPNR Then
                   vrIndex = i
        .Select "#"&vrIndex
                   Exit For
          End If
Next
End With


Saturday, June 8, 2013

Repositories - Dynamic Management

One of the new feature of QTP 9.2 is Dynamic Management of OR.

>>ADD
RepositoriesCollection.Add("D:\google.tsr")
-- it will add the 'test.tsr' file during the run time

>>FIND
Pos = RepositoriesCollection.Find("D:\google.tsr")
-- it will return a numeric value to the variable 'Pos' this
is nothing but the index value of the specified file

>>MOVETOPOS
RepositoriesCollection.MoveToPos(2,5)
-- here 2 is the current index and 5 is the new index
position. In this case it will move 2nd item to 5th position

>>REMOVE
RepositoriesCollection.Remove(5)
--it removes the 5th object repository file from the OR

>>REMOVEALL
RepositoriesCollection.RemoveAll
--it removes the full items from OR. Makes object repository
empty

>>COUNT
no = RepositoriesCollection.Count
--stores the number of repository items to 'no'

>>ITEM
desc = RepositoriesCollection.Item(4)
--returns the path of the 4th object repository file.

Dim qtApp
    Dim qtRepositories
    Set qtApp = CreateObject("QuickTest.Application")
    Set qtRepositories = qtApp.Test.Actions("ActionName").ObjectRepositories
   
qtRepositories.Add "D:\Documents\sharedRepository.tsr

Friday, June 7, 2013

Returning a value from a Function in QTP

To return a value from a function, we need to take care of the following two things:
 1) To return a value from a function, you need to use the statement functionName = ReturnValue, where functionName is the actual name of the function and ReturnValue is the value you want to return.
 2) To capture the returned value, you need to use the statement someVariable =functionName(parameters) while calling the function.
Let us understand this with the help of an example.

Returning value from a Function


'==========================================================
'  Function Name:   fnSum(var1, var2)
'  Function Scope:   Public
'  Parameters:   var1 and var2- Enter a number , result will display Sum
'  Description:   To find addition of two numbers
'  Author      :   Hardeep
'==========================================================

Function fnSum(var1, var2)
vrSum = var1 + var2   'return the result
 fnSum = vrSum
'This Statement Returns the value from Function i.e. functionName = ReturnValue
End Function

'Calling the Function and capturing the return value in variable "vrResult"

Dim vrResult
vrResult =  fnSum(25,10
'parameters should be passed using parenthesis when the function returns a value
msgbox vrResult


Wednesday, June 5, 2013

Handle Pop Up Dialog Window in Browser

' *************************************************************************
' Function  fnGetPopUpText() 
' This function Get the lable text message from Popup Dialog window in Browser page and enter the label text in Result Excel Sheet
' Note Dialog Window Must be child of  Parent oect
' Input Parameters   := None
' Output(ReturnType) := None
' *************************************************************************

Call fnGetPopUpText()

Public function fnGetPopUpText()

     Set oStaticText =Description.Create()
oStaticText("nativeclass").value ="Static"
oStaticText("text").value =".*[a-z].*"
     Set oWinButton =Description.Create()
oWinButton("micclass").value ="WinButton"

With Window("regexpwndtitle:=Windows Internet Explorer","regexpwndclass:=IEFrame").Dialog("regexpwndtitle:=Windows Internet Explorer","regexpwndclass:=#32770?")

    If .Exist(2) then
.Activate
    Set oStaticText = .ChildObjects(oStaticText)
For i=0 to oStaticText.Count-1
vrDescription =oStaticText(i).GetVisibleText(-1,-1,-1,-1)
Next

    Set oWinbutton = .ChildObjects(oWinbutton)
For i=0 to oWinButton.count-1
oWinButton(i).Click
Exit for
Next
     fnGetPopUpText = vrDescription
End if

End With

End Function

'**********************************************************************************

Public function fnGetPopUpText()
    Set oStaticText =Description.Create()
oStaticText("nativeclass").value ="Static"
oStaticText("text").value =".*[a-z].*"

Set oWinButton =Description.Create()
oWinButton("micclass").value ="WinButton"

With Browser("title:=.*(Page).*").Dialog("text:=Windows Internet Explorer","nativeclass:=#32770?")
If .Exist(2) then
.Activate
Set oStaticText = .ChildObjects(oStaticText)
For i=0 to oStaticText.count-1
vrDescription =oStaticText(i).GetVisibleText(-1,-1,-1,-1)
Next
Set oWinButton = .ChildObjects(oWinButton)
For i=0 to oWinButton.count-1
oWinButton(i).Click
Exit for
Next

fnGetPopUpText = vrDescription
End if
End With
End Function

What Test Cases To Automate

It is impossible to automate all testing; the first step to successful automation is to determine what test cases should be automated first.

The benefit of automated testing is correlated with how many times a given test can be repeated. Tests that are only performed a few times are better left for manual testing. Good test cases for automation are those that are run frequently and require large amounts of data to perform the same action.

You can get the most benefit out of your automated testing efforts by automating:
  • Ø  Repetitive tests that run for multiple builds
  • Ø  Tests that are highly subject to human error
  • Ø  Tests that require multiple data sets
  • Ø  Frequently-used functionality that introduces high risk conditions
  • Ø  Tests that run on several different hardware or software platforms and configurations
  • Ø  Tests that take a lot of effort and time when doing manual testing


Success in test automation requires careful planning and design work. Start out by creating an automation plan. This plan allows you to identify the initial set of tests to automate, and serve as a guide for future tests. First, you should define your goal for automated testing and determine which types of tests to automate. There are a few different types of testing, and each has its place in the testing process. For instance, unit testing is used to test a small part of the intended application. Load testing is performed when you need to know how a web service responds under a heavy workload. To test a certain piece of the application’s UI, you would use functional or GUI testing.

After determining your goal and which types of tests to automate, you should decide what actions your automated tests will perform. Don’t just create test steps that test various aspects of the application’s behaviour at one time. Large, complex automated tests are difficult to edit and debug. It is best to divide your tests into several logical, smaller tests. This structure makes your test environment more coherent and manageable and allows you to share test code, test data and processes. You will get more opportunities to update your automated tests just by adding small tests that address new functionality. Test the functionality of your application as you add it, rather than waiting until the whole feature is implemented.

When creating tests, try to keep them small and focused on one objective. For example, use separate tests for read-only versus read/write tests. This separation allows you to use these individual tests repeatedly without including them in every automated test.

Once you create several simple automated tests, you can group your tests into one, larger automated test. You can organize automated tests by the application’s functional area, major/minor division in the application, common functions or a base set of test data. If an automated test refers to other tests, you may need to create a test tree, where you can run tests in a specific order.