1 Write a program to find the x and y coordinates of a button
2 Write a program to Read items in a list box
3 Write a program to Read items on a desktop
intCount=Window("title:=Program Manager").WinListView("object
class:=SysListView32").GetItemsCount
msgbox intCount
4 Write a program to Capture Desktop Screen shot
Desktop.CaptureBitmap "C:\test.bmp"
5 Write a program to Read tab names from a tabbed window
'Open a new Browser
SystemUtil.Run "iexplore.exe", "http://www.google.com"
'Browser Sync
Browser("CreationTime:=0").Sync
'Find total number of tabs in the browser window
iTabs = Browser("CreationTime:=0").GetROProperty("number of tabs")
msgbox iTabs 'Displays the value 1
'Open a new tab within the same browser
Browser("CreationTime:=0").OpenNewTab()
'Sync for new tab
Browser("CreationTime:=1").Sync
'Load some web page in the new tab
Browser("CreationTime:=1").Navigate "http://www.yahoo.com"
'Find total number of tabs in the browser window
iTabs = Browser("CreationTime:=0").GetROProperty("number of tabs")
msgbox iTabs 'Displays the value 2
'Close all the tabs in the browser window
Browser("CreationTime:=0").CloseAllTabs()
'OR ->Browser("CreationTime:=1").CloseAllTabs()
6 Write a program to Check whether scrollbars exists inside a editor
IF (Browser(Obj).Page(Obj).WebEdit(Obj).FireEvent (OnMouseOver, ,,0) ) then
Msgbox Exists Scrollbar in the Web Editor
Else
Browser(Obj).Page(Obj).WebEdit(Obj).Exist
Msgbox No Scrollbar in the Web editor
End if
(Or)
MyString = Browser(Obj).Page(Obj).WebEdit(Obj).GoRoPerperties (Visible items)
Mystring1 = Browser(Obj).Page(Obj).WebEdit(Obj).GoRoPerperties (itemscount)
IF (MyString = MyString1 ) then
Msgbox Is Scrollbar is visible
Else
Msgbox Is Scrollbar is not visible
End if
7 Write a program to check whether edit box is enabled or writable
MyString = Browser(Obj).Page(Obj).WebEdit(Obj).GetRoPerperty(Visible)
IF (MyString = 1 or True) then
Msgbox & WedEdit is Visible: & Mystring
Else
Msgbox & WedEdit is not visible: & Mystring
End if
8 Write a program to Check whether dialog is middle of the window
9 Write a program to Check whether country contains all the states
10 Write a program to Check whether edit box is focused
11 Write a program to Check default selection in a list box
FunctionRegexSelectQTP(Object, sPattern)
Dim oRegExp, arrAllItems, ix
'Create RegExp Object
Set oRegExp = New RegExp
oRegExp.IgnoreCase = False
oRegExp.Pattern = sPattern
'Split Object's all_items property
arrAllItems = Split(Object.GetROProperty("all items"), ";")
For ix = LBound(arrAllItems) ToUBound(arrAllItems)
'If RegExp pattern matches list item, we're done!
IfoRegExp.Test(arrAllItems(ix)) Then
Object.Select"#"& ix
Set oRegExp = Nothing
ExitFunction
EndIf
Next
'Select Item #1 by default
Object.Select"#0"
EndFunction
RegisterUserFunc "WebList", "RegexSelectQTP", "RegexSelectQTP"
Or
Dim a,i
'Getting list box count
a=Browser().Page().Weblist(WebListName).GetItemsCount
'getting list box values
For i=0 to a-1
msgbox Browser().Page().Weblist(WebListName).GetItem
(i),4,"States"
Next
12 Write a program to Capture webbutton image
Dlgname=Dialog("nativeclass:=#32770").GetROProperty("text")
msgbox Dlgname
lsbtnstatus=Dialog("text:="&Dlgname).winbutton("text:=OK").getroproperty("enabled")
If lsbtnstatus Then
msgbox "PASS"
End if
Or
13 Write a program to List all links in the web page
Set oDesc = Description.Create()
oDesc("micclass").Value = "Link"
Set Links = Browser("Google Labs").Page("Google Labs").ChildObjects(oDesc)
Msgbox "Total links: " & Links.Count
Or
set linkObj=description.create
linkObj("micclass")="link"
set linkChildObj=B().p().childobjects(linkObj)
childCount=linkChildObj.count
for i=0 to childCount-1
linkName=linkChildObj(i).getROProperty("innertext")
msgbox linkName
next
14 Write a program to Check whether given link exists or not
If Browser("Browser").Page("Page").Link("Link).Exist(0) Then
Reporter.ReportEvent micPass "Link Found", "YES"
End If
15 Write a program to Find image width and Height
imgCount = 0
Set obj = Browser("Software Quality Assurance").Page("micClass:=Page").Object.Images
cnt = obj.length
For i = 0 To cnt-1
'imgCount=imgCount+1
fn=Browser("Software Quality
Assurance").Page("micClass:=Page").Image("index:="&i).GetROProperty("file name")
fh=Browser("Software Quality
Assurance").Page("micClass:=Page").Image("index:="&i).GetROProperty("height")
fw=Browser("Software Quality
Assurance").Page("micClass:=Page").Image("index:="&i).GetROProperty("width")
Reporter.ReportEvent micGeneral, "Image Name: "&fn ,"Height "&fh&" Width "&fw
Next
Reporter.ReportEvent micGeneral, "Image Count",cnt-1
orFunction ScreenWidth()
ScreenWidth =Window("object class:=Shell_TrayWnd").GetROProperty("width")
EndFunction
FunctionScreenHeight()
ScreenHeight =Window("object class:=Shell_TrayWnd").GetROProperty("height")+
Window("object class:=Shell_TrayWnd").GetROProperty("y")
EndFunction
16 Write a program to Print URL displayed in the address bar
Browser("B").Navigate DataTable("A", dtGlobalSheet)
Or
SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE","","", "open".
Temp=datatable.getsheet(1).getparameter("Url")
17 Write a program to Check whether webpage downloaded completely
set objReadyState = Browser("").Page("").Object
While objReadyState.readyState = "Completed"
Wend
Set Object=nothing
Set Object=Browser("").object
While Object.Busy=True
Wend
Set Object=nothing
orBrowser("title:=.*").Page("title:=.*").Sync
18 Write a program to Refresh a web page
Set objIE = CreateObject("InternetExplorer.Application") ' creating the object for the ie
explorer
objIE.visible = True ' visible the ie
objIE.Navigate "www.gmail.com" ' navigating the ie browser
wait(5)
objIE.Refresh
19 Write a program to Verify page title is displayed correctly
'Check if the left 13 charecters of the browser title is "Gmail - Inbox"
If left(browser("title:=.*").Page("title:=.*").getROProperty("title"),13)
="Gmail - Inbox"Then
msgbox("Signed in Successfully")
Else
msgbox("Login Unsuccessful")
End If
'Close the IE browser
systemutil.CloseProcessByName "iexplore.exe"
20 Write a program to Verify whether page contains frames
if Bowser("browser name").page("page name").frame("frame
name").exits then
reporter.reportevent 0,"frame","frame exists"
else
reporter.reportevent 1,"frame","frame doesn't exists"
end if
21 Write a program to Find page load time
lTime=Browser("Google").Page("Google").GetROProperty("load time")
lCount=Browser("Google").Page("Google").GetROProperty("number of
links")
iCount=Browser("Google").Page("Google").GetROProperty("number of
images")
Msgbox"Page Load Time="&lTime
Msgbox"Number of Links in Page="&lCount
Msgbox"Number of Images in Page="&iCount
22 Write a program to Check given text is displayed on the web page
If Browser("title:=HRnet"). Page("title:=HRnet").WebElement("innertext:=No news to
display.").Exist Then
Msgbox "Text found"
Else
Msgbox "Text not found"
23 Write a program to Find whether image contains tool tip
Dim descImage, listImages, attrAltText, attrSrcText
Browser("Main Page - Wikipedia,").Sync
Browser("Main Page - Wikipedia,").Page("Main Page - Wikipedia,").Sync
' Create description for all images on a Web page.
' For that we use "html tag" property and its value "IMG"
Set descImage = Description.Create
descImage("html tag").value = "IMG"
' Get all images which match the above description
Set listImages = Browser("Main Page - Wikipedia,").Page("Main Page -
Wikipedia,").ChildObjects(descImage)
' Check tool tips of images
For i = 0 To listImages.Count - 1
attrAltText = listImages(i).GetROProperty("alt")
attrSrcText = listImages(i).GetROProperty("src")
If attrAltText <> "" Then
MsgBox "Image src: " & attrSrcText & vbNewLine & "Tool tip: " & attrAltText
End If
Next
24 Write a program to Invoke the Browser with specified URL
Set IE CreateObject("InternetExplorer.Application")
IE.Visible True
IE.Navigate http://www.google.com
25 Write a program to Import an excel file to a Data table
Datatable.import(C:\Amar.txt)
26 Write a program to Read data from first parameter of Global sheet
'Parameterization Block:
WithBrowser("title:=Welcome: Mercury Tours", "index:=0")
'Step 2
'Parameter 1: UserName
.WebEdit("name:=userName").Set Datatable("UserName", dtLocalSheet)
'Parameter 2: Password
.WebEdit("name:=password").Set Datatable("Password", dtLocalSheet)
.Image("name:=login").Click
EndWith
'Step 3
'If Find a Flight page appears, go back to Home
IfBrowser("title:=Find a Flight: Mercury Tours:", "index:=0").Exist(10) Then
'Step 4
Reporter.ReportEvent micPass, "Iteration "&
DataTable.LocalSheet.GetCurrentRow, _
"UserName: "& Datatable("UserName", dtLocalSheet) &" is valid"
Browser("title:=Find a Flight: Mercury Tours:",
"index:=0").Link("text:=Home").Click
Else
'Step 5
'Else, fail the iteration and return to the Home page
Reporter.ReportEvent micFail, "Iteration "&
DataTable.LocalSheet.GetCurrentRow, _
"UserName: "& Datatable("UserName", dtLocalSheet) &" is invalid"
Browser("title:=Sign-on: Mercury Tours", "index:=0").Link("text:=Home").Click
EndIf
27 Write a program to Read data from all sheets and all parameters of the
excel file
Dim objexcel, objWorkbook, objDriverSheet, columncount, rowcount
set objexcel = Createobject(Excel.Application)
Set objWorkbook = objExcel.WorkBooks.Open(path of the file.xls)
Set objDriverSheet = objWorkbook.Worksheets(name of the sheet / Id of the sheet)
columncount = objDriverSheet.usedrange.columns.count
rowcount = objDriverSheet.usedrange.rows.count
for i = 1 to colunmcount
columnname = objDriversheet.cells(i,1)
if columnname = knowncolumnname then
for j = 1 to rowcount
fieldvalue = objdriversheet.cells(j,i)
next
end if
next
28 Write a program to place data in a specific sheet in the excel file
Set excel=createobject("excel.application")
excel.Visible=True
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get the Control on Specific Sheet
Set worksheet1=excel.Worksheets.Item("Sheet1")
' Display the Values
Msgbox worksheet1.cells(1,1).value
workbook.Close
excel.Quit
Set worksheet1=Nothing
Set workbook=Nothing
Set excel=Nothing
Or
Set myxl = createobject("excel.application")
'Make sure that you have created an excel file before executing
the script .
'Use the path of excel file in the below code.
'Also make sure that your excel file is in Closed state.
myxl.Workbooks.Open "D:\parameter.xls"
myxl.Application.Visible = true
'"Sheet1" is the name of Sheet in Excel file "qtp.xls" where
data needs to be entered .
set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1")
'contents of sheet1
'Uname Pwd
'------------ ------------
'qtpworld.com qtp
'admin qtp
' qtp
'admin
'abcd abcd
'Launch Gmail
Systemutil.Run "iexplore.exe","http:\\www.gmail.com"
Browser("title:=Gmail: Email from Google").Page("title:=Gmail:
Email from Google").Sync
'Get the max row occupied in the excel file
Row=mysheet.UsedRange.Rows.Count
'To read the data from the entire Excel file
For i= 2 to Row
Username=mysheet.cells(i,1).value
Password=mysheet.cells(i,2).value
' Enter Email id in Username Field
Browser("title:=Gmail: Email from Google").Page("title:=Gmail:
Email from Google").WebEdit("name:=Email").Set Username
'Enter password in Passowrd Field
Browser("title:=Gmail: Email from Google").Page("title:=Gmail:
Email from Google").WebEdit("name:= Passwd").Set Password
wait 1
Next
'Close the Workbook
myxl.ActiveWorkbook.Close
'Close Excel
myxl.Application.Quit
'Release the objects
Set mysheet =nothing
Set myxl = nothing
29 Write a program to Import data to data table from a database
Function GetDataFromDB (strFileName, strSQLStatement)
Dim objAdCon, objAdRs
Set objAdCon = CreateObject(ADODB.Connection)
objAdCon.Open DRIVER={Microsoft Excel Driver (*.xls)};DBQ=&strFileName
& ;Readonly=True
If Err <> 0 Then
Reporter.ReportEvent micFail,Create Connection, [Connection] Error has occured.
Error : & Err
Set obj_UDF_getRecordset = Nothing
Exit Function
End If
Set objAdRs = CreateObject(ADODB.Recordset)
objAdRs.CursorLocation=3 set the cursor to use adUseClient
disconnected recordset
objAdRs.Open strSQLStatement, objAdCon, 1, 3
MsgBox objAdRs.fields(4).name
While objAdRs.EOF=false
For i=0 to objAdRs.Fields.count
Msgbox objAdRs.fields(i)
Next
objAdRs.moveNext
Wend
If Err<>0 Then
Reporter.ReportEvent micFail,Open Recordset, Error has occured.Error Code :
& Err
Set obj_UDF_getRecordset = Nothing
Exit Function
End If
Set objAdRs.ActiveConnection = Nothing
objAdCon.Close
Set objAdCon = Nothing
End Function
30 Write a program to Read and display data from CSV file
Function ReadCSV(Filepath,Row,Occurrence)
Set fso = CreateObject("Scripting.FileSystemObject")
Set tso = fso.OpenTextFile(Filepath,1,false,0)
'For Reaching the desired ROW
If Row <> 1 Then
For i =1 to (Row-1)
tso.SkipLine
Next
End If
'Capturing the entire desired ROW and its width
RequiredLine = tso.ReadLine
Width = tso.Column
z=1
'Loop for finding start and end position
For i=1 to (Occurrence+1)
y = Instr(z, RequiredLine , "," , 1)
'Special handling if the comma is last
If y = 0 Then
y = Width
End If
'Capturing Start Position
If i = Occurrence Then
StartPosition=y+1
End If
z=y+1
Next
'Special Handling of Condtion of Zero Occourence
If Occurrence = 0 Then
StartPosition = 1
End If
EndPosition = (y-StartPosition)
'The logic to read file without double quotes
ReadCSV = mid(RequiredLine,StartPosition+1,EndPosition-2)
Set tso = Nothing
Set fso = Nothing
End Function
31 Write a program to Find number of rows and columns in a web table
What is a web table object?
Tables are one of the primary design tools for HTML documents. Tables allow for greater control over
page layout, allowing creation of more visually interesting pages. Tables are also used to set apart sections
of documents, such as in sidebars, navigation bars, or framing images and their titles and captions. Tables
have literally changed the look of the Web page. Originally, tables let people present data in a column
format. Designers quickly figured out ways to improve the layout of their pages using tables.
QTP Web Tables
A Table containing a number of rows and columns
A Table containing any kind of information in cells in combinations of rows and columns.
Keywords for Web Table are:
Rows
Columns
Cell
Cell Data
RowCount
ColumnCount
GetCellData
Getting Web Table Column headers
Purpose:
To get the Column headers of a table so as to write these headers as Column Names to a excel sheet
Script:
DataTable.AddSheet "MySheet"
Set oTable=Browser("Gmail: Email from Google").Page("Gmail - Inbox").WebTable(t")
RC=oTable.RowCount
CC=oTable.ColumnCount(1)
Print "RC " & RC
Print "CC " & CC
For i=1 to CC
ColName=oTable.GetCellData(1,i)
Print "ColName "& ColName
DataTable.GetSheet("MySheet").AddParameter ColName,""
Next
Web Table RowCount & ColumnCount
Purpose:
To get the number of rows and number of columns of a table from a page
Script:
Set MyTable=Browser("Gmail: Email from Google").Page("Gmail - Inbox").WebTable("html
tag:=TABLE","name:=t")
RC=MyTable.RowCount
CC=MyTable.ColumnCount(1)
Print "RC " & RC
Print "CC " & CC
Getting Cell Data from a Web Table
Purpose:
To get the cell data of a table from a page
Method used is GetCellData(Row#,Col#)
Script:
Set Text = Browser("").Page("").WebTable("").GetCellData(1, 1)
MsgBox "text contains" & Text
Example:
Set oTable=Browser("").Page("").WebTable("")
For i=1 to RC
CC=oTable.ColumnCount(i)
For j=1 to CC
CData=oTable.GetCellData(i,j)
Print "CData " & CData
Next
Next
Getting Cell Data From Web Tables and writing to an excel
Purpose:
To the required cell data from a web table and write these values to an excel sheet
Script:
For i=1 to RC
Datatable.GetSheet("MySheet").SetCurrentRow(i)
CC=oTable.ColumnCount(i)
For j=1 to CC
CData=oTable.GetCellData(i,j)
DataTable.GetSheet("MySheet").GetParameter(j).value=CData
Print "CData " & CData
Next
Next
Working Gmail Web Table - Demo
Set oTable=Browser("Gmail: Email from Google").Page("Gmail - Inbox").WebTable(t")
RC=oTable.RowCount
CC=oTable.ColumnCount(1)
Print "RC " & RC
Print "CC " & CC
For i=1 to CC
ColName=oTable.GetCellData(1,i)
Print "ColName "& ColName
DataTable.GetSheet("MySheet").AddParameter ColName,""
Next
For i=1 to RC
Datatable.GetSheet("MySheet").SetCurrentRow(i)
CC=oTable.ColumnCount(i)
For j=1 to CC
CData=oTable.GetCellData(i,j)
DataTable.GetSheet("MySheet").GetParameter(j).value=CData
Print "CData " & CData
Next
Next
Reading an excel sheet and passing cell data as a link
PCMySheet=DataTable.GetSheet("MySheet").GetParameterCount
RCMySheet=DataTable.GetSheet("MySheet").GetRowCount
For j=1 to RCMySheet
For i=1 to PCMySheet
CValue=DataTable.GetSheet("MySheet").GetParameter(i).ValueByRow(j)
'RCValue=DataTable.GetSheet("MySheet").GetParameter(3).ValueByRow(j)
Print "CValue "& CValue
Next
Next
For j=1 to RCMySheet
'For i=1 to PCMySheet
'CValue=DataTable.GetSheet("MySheet").GetParameter(i).ValueByRow(j)
RCValue=DataTable.GetSheet("MySheet").GetParameter(3).ValueByRow(j)
Print "RCValue "& RCValue
'Next
Next
To get the no# of web tables existing on page
Purpose:
To get the number of web tables existing on a page
To the get all web tables names, text, rowcount, columncount
Script:
Set ObjTable=Description.Create
ObjTable("html tag").value="TABLE"
ObjTable("text").value=".*"
Set TotObjTable=Browser("Gmail: Email from Google").Page("Gmail - Inbox").ChildObjects(ObjTable)
NoOfTables=TotObjTable.count
Print "NoOfTables "& NoOfTables
For i=0 to NoOfTables-1
TabName=TotObjTable(i).GetROProperty("name")
TabCols=TotObjTable(i).GetROProperty("cols")
TabRows=TotObjTable(i).GetROProperty("rows")
TabText=TotObjTable(i).GetROProperty("text")
Print "TabName "& TabName
Print "TabCols "& TabCols
Print "TabRows "& TabRows
Print "TabText "& TabText
Next
Working on a particular Web Table
Purpose:
Getting all the information from a known table (like RowCount, ColumnCount, CellData and so on)
Why this script is for:
This script helps to work on particular table to get all the info of that table so as to write data into an excel
or passing particular cell data as parameter to the running test script or Verifying the table data if it is as
per the requirements.
Script:
Set MyTable=Browser("Gmail: Email from Google").Page("Gmail - Inbox").WebTable("html
tag:=TABLE","name:=t")
RC=MyTable.RowCount
CC=MyTable.ColumnCount(1)
Print "RC " & RC
Print "CC " & CC
RC=Browser("Gmail: Email from Google").Page("Gmail - Inbox").WebTable("html
tag:=TABLE","name:=t").RowCount
CC=Browser("Gmail: Email from Google").Page("Gmail - Inbox").WebTable("html
tag:=TABLE","name:=t").ColumnCount(1)
Print "RC " & RC
Print "CC " & CC
DataTable.AddSheet "WebTable"
For i=1 to CC
CName=MyTable.GetCellData(1,i)
DataTable.GetSheet("WebTable").AddParameter CName,""
Next
For i=1 to RC
CC=MyTable.ColumnCount(i)
For j=1 to CC
MyData=MyTable.GetCellData(i,j)
Print "MyData " & MyData
Next
Next
Finding no# child objects of a web table in a page
Set ObjTable=Description.Create
ObjTable("html tag").value="TABLE"
ObjTable("text").value=".*"
Set TotObjTable=Browser("Gmail: Email from Google").Page("Gmail Inbox").ChildObjects(ObjTable)
NoOfTables=TotObjTable.count
Print "NoOfTables "& NoOfTables
QTP - Descriptive program with respect to a Web Table
Set ObjTable=Description.Create
ObjTable("html tag").value="TABLE"
ObjTable("text").value=".*"
Set TotObjTable=Browser("Gmail: Email from Google").Page("Gmail Inbox").ChildObjects(ObjTable)
NoOfTables=TotObjTable.count
Print "NoOfTables "& NoOfTables
For i=0 to NoOfTables-1
TabName=TotObjTable(i).GetROProperty("name")
TabCols=TotObjTable(i).GetROProperty("cols")
TabRows=TotObjTable(i).GetROProperty("rows")
TabText=TotObjTable(i).GetROProperty("text")
Print "TabName "& TabName
Print "TabCols "& TabCols
Print "TabRows "& TabRows
Print "TabText "& TabText
Next
Get Row no# with CellText
'Get the row number for defined text
Scenario : I want to get the row number where my name exists like Jackiechen
Explanation:
In my table , there are rows of data where my name could be seen. So wanted to get the number of a table
where my name exists. And thus this code works there.
Script:
RowNumber = Browser("").Page("").WebTable("").GetRowWithCellText("Jackiechen")
Simmilary, in Gmail, there is InBox and if we want to get the exact row number where a specific mail
(mail header) exists, then we could make use of the above code.
Retrieving all Web Table Names from a page
Purpose:
Retrieving all Web Table Names from a page
Script:
Set oTable =B().p().WebTable(html tag:=TABLE).ChildObjects
Msgbox oTable .count
For i=0 to oTable .count-1
Msgbox I && oTable (i).GetROProperty(name)
Next
32 Write a program to Display entire data in the web table
Set ObjTable=Description.Create
ObjTable("html tag").value="TABLE"
ObjTable("text").value=".*"
Set TotObjTable=Browser("Gmail: Email from Google").Page("Gmail Inbox").ChildObjects(ObjTable)
NoOfTables=TotObjTable.count
Print "NoOfTables "& NoOfTables
For i=0 to NoOfTables-1
TabName=TotObjTable(i).GetROProperty("name")
TabCols=TotObjTable(i).GetROProperty("cols")
TabRows=TotObjTable(i).GetROProperty("rows")
TabText=TotObjTable(i).GetROProperty("text")
Print "TabName "& TabName
Print "TabCols "& TabCols
Print "TabRows "& TabRows
Print "TabText "& TabText
Next
33 Write a program to Display all images in the webpage
Dim descImage, listImages
' Create description for all images on a Web page.
' For that we use "html tag" property and its value "IMG"
Set descImage = Description.Create
descImage("html tag").value = "IMG"
' Get all images which match the above description
Set listImages = Browser("Google Book Search").Page("Google Book Search").ChildObjects(descImage)
' Show the number of found images
MsgBox "Found images: " & listImages.Count
34 Write a program to Check whether table contains headers
DataTable.AddSheet "MySheet"
Set oTable=Browser("Gmail: Email from Google").Page("Gmail - Inbox").WebTable(t")
RC=oTable.RowCount
CC=oTable.ColumnCount(1)
Print "RC " & RC
Print "CC " & CC
For i=1 to CC
ColName=oTable.GetCellData(1,i)
Print "ColName "& ColName
DataTable.GetSheet("MySheet").AddParameter ColName,""
Next
35 Write a program to Find the background colour of a webobject
Dim ctrlWebEl, objWebEl
Set ctrlWebEl = Browser("Welcome to Gmail").Page("Welcome to
Gmail").WebElement("Welcome to Gmail")
Set objWebEl = ctrlWebEl.Object
sColor = objWebEl.currentStyle.color
sBackgrColor = objWebEl.currentStyle.backgroundColor
sFontSize = objWebEl.currentStyle.fontSize
sFontStyle = objWebEl.currentStyle.fontStyle
sFontFamily = objWebEl.currentStyle.fontFamily
sFontWeight = objWebEl.currentStyle.fontWeight
36 Write a program to Print results in a HTML format
Procedure to create the QTP results in
HTML format
Sunday, 15 March 2009 04:26
Here is the procedure to create the QTP results in HTML format:
Here is the procedure to create the QTP results in HTML format:
Little Reading...
By default, QTP does not create the results in HTML format. You might run into situation where you
might want to send the results in an email and html is the best format for that sort of communcations.
Procedure:
1. Open the system REGISTRY.
o Start > Run > regedit
o Click OK
2. Expand
o HKEY_LOCAL_MACHINE
SOFTWARE
Mercury Interactive
QuickTest Professional
Logger
Media
Log
3. Now, on the right hand side, you should see "Active"
4. Double click on "Active"
5. Change the value to "1" (Default value is 0)
6. Restart QTP if it is open.
7. Run a test.
8. Now, you should see "Log" folder inside the results folder with the HTML format results file.
37 Write a program to Select different radio buttons for different script
iterations
set rb = description.create()
rb("name").value = "rbselectitem"
rb("html tag").value = "INPUT"
set radiobtn =
browser(br).page(pg).webradiogroup(rb).GetROProperty("items count")
Print " total Radio buttons are" & radiobtn 'this gives me total
no of radio button as 9
For i = 1 to radiobtn
set fristrb = description.create()
firstrb("name").value = "rbselectitem"
firstrb("html tag").value = "INPUT"
firstrb("index").value = "0"
if radiobtn = 1 then ' if this is a
First Iteration
mypg.webradiogroup(firdtrb).select "0"
else if
radiobtn = 2 then ' if this is a
Second Iteration
mypg.webradiogroup(firdtrb).select "1"
else if
radiobtn = 3 then ' if this
is a Third Iteration
mypg.webradiogroup(firdtrb).select "2"
End if
set ig = description.create() 'this will click on image after
selecting radio button & just reload page
ig("name").value = "AU_tcpolicy_img"
ig("html tag").value = "INPUT"
mypg.image(ig).click
radiobtn = radiobtn +1
38 Write a program to Read all the items from a services window
From QTP point of view there are few tasks where WSH could be very handy:
Manipulating the Windows environment
Running other programs
Automating logon procedures
Sending key sequences to an application
Code sample to generate an auto close pop up dialog.
Set objShell = CreateObject("Wscript.Shell")
strMessage = "This is an auto close dialog . .!!"
objShell.popup strMessage, 4, "Shell object pop - up"
Code sample to run an exe file or Window based program.
Set objShell = CreateObject("Wscript.Shell")
objShell.exec ("C:\Program Files\HP\Quicktest
Professional\Samples\Flight\app\flight4a.exe")
objshell.Run "H:\WSH_QTP\test_1.vbs"
objShell.exec ("calc")
But WSH does not run the below statement, giving an error not a WIN32 application
objShell.Exec "H:\WSH_&_QTP\test1.vbs"
As per my understanding, RUN is used to run windows specific applications and EXEC to execute a
statement.
Code sample to send keyboard keys.
Set objShell = CreateObject("Wscript.Shell")
objShell.SendKeys ("{ENTER}")
objShell.SendKeys ("%+{F4}")
39 Write a program to Find screen resolution
Set objWMIService = GetObject("Winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_DesktopMonitor where DeviceID =
'DesktopMonitor1'",,0)
For Each objItem in colItems
intHorizontal = objItem.ScreenWidth
intVertical = objItem.ScreenHeight
Next
If intHorizontal = 1280 and intVertical = 800 Then
message_OK = "Your screen resolution is 1280 X 800." & vbcrlf & "This is the good screen resolution"
Reporter.ReportEvent micPass,"SCREEN RESOLUTION CHECK", message_OK
else
message_KO = "Your screen resolution is " & intHorizontal & " X " & intVertical & vbcrlf & "This is not
the good screen resolution, your PDF checkpoint may fail" & vbcrlf & "Please set it to 1280 X 800 and run
again your script."
Reporter.ReportEvent micWarning,"SCREEN RESOLUTION CHECK", message_KO
End If
Or
40 Write function to compare two bitmaps
Function CompareBitmap(ActualBmp, ExpectedBmp)
Set fCompare = CreateObject("Mercury.FileCompare")
If fCompare.IsEqualBin(ExpectedBmp, ActualBmp, 0, 1) Then
Reporter.ReportEvent micPass,"Bitmap Verification",ActualBmp&"and"&ExpectedBmp&"
are same"
CompareBitmap=True
Else
Reporter.ReportEvent micFail,"Bitmap Verification",ActualBmp&"and"&ExpectedBmp&" are
not same"
CompareBitmap=False
End If
End Function
Or
1. Dim pTitle
2.
3. '***************************************************
4. Function CompareBitmap(ActualBmp, ExpectedBmp)
5.
6.
7. Set fCompare = CreateObject("Mercury.FileCompare")
8.
9.
10. If fCompare.IsEqualBin(ExpectedBmp, ActualBmp, 0, 1) Then
11.
12. Reporter.ReportEvent micPass,"Bitmap Verification",ActualBmp&"and"&ExpectedBm
p&" are same"
13. CompareBitmap=True
14. Else
15. Reporter.ReportEvent micFail,"Bitmap Verification",ActualBmp&"and"&ExpectedBm
p&" are not same"
16. CompareBitmap=False
17. End If
18.
19.
20. End Function
21. '***************************************************
22. 'Calling the Function
41 Write a program to Add and Remove Repositories to the action
Adding Repository to an action
'*********************************************************************
Dim qtApp,qtRepositories, actName, RepPath
RepPath=".TRS File Path"
actName=Environment.Value("ActionName") 'Get Action Name
Set qtApp = CreateObject("QuickTest.Application") ' Create Application Object
Set qtRepositories = qtApp.Test.Actions(actName).ObjectRepositories ' Get Associated repositories list
If qtRepositories.Find(RepPath) = -1 Then
qtRepositories.Add RepPath, 1 ' Add the Object Repository to the current action
End If
qtApp= Nothing
qtRepositories= Nothing
'*********************************************************************
'*********************************************************************
'Remove repository from an action
Dim qtApp,qtRepositories, actName, RepPath, rPosition
RepPath=".TRS File Path"
actName=Environment.Value("ActionName") 'Get Action Name
Set qtApp = CreateObject("QuickTest.Application") ' Create Application Object
Set qtRepositories = qtApp.Test.Actions(actName).ObjectRepositories ' Get Associated repositories list
rPosition=qtRepositories.Find(RepPath) 'Find the Position of the Repository
If rPosition<>-1 then
qtRepositories.Remove rPosition ' Remove Repository From the Action
End if
qtApp= Nothing
qtRepositories= Nothing
42 Write a program to Load Library files
4 Different Ways to Associate Function Libraries to your QTP Scripts
September 22nd, 2011 | Posted by Anish Pillai in QTP Basic Stuff
0
inShare
Most of the times, when you are creating test scripts or are designing a new QTP
Framework, you would be trying to come up with reusable functions which you would have
to store in the function library. Now, in order to use this function library with multiple test
cases, you need to associate this function library with your scripts. This article explains
the 4 methods that will help you in associating the function libraries in QTP Test
Cases.
Based on the type of framework you are using, you can use any of the following methods to
associate function libraries to your QTP Script -
1) By using File > Settings > Resources > Associate Function Library option in
QTP.
2) By using Automation Object Model (AOM).
3) By using ExecuteFile method.
4) using LoadFunctionLibrary method.
Lets see in detail how each of these methods can be used to map function libraries to your
test scripts.
1. Using File > Settings > Resources > Associate Function Library option from the Menu bar
This is the most common method used to associate a function library to a test case. To use
this method, select File > Settings option from the Menu bar. This will display the Test
Settings window. Click on Resources from the left hand side pane. From the right hand side
pane, click on the + button and select the function library that needs to be associated with
the test case.
Associate function Library to QTP
2. Using AOM (Automation Object Model)
QTP AOM is a mechanism using which you can control various QTP operations from outside
QTP. Using QTP Automation Object Model, you can write a code which would open a QTP
test and associate a function library to that test.
Example: Using the below code, you can open QTP, then open any test case and associate a
required function library to that test case. To do so, copy paste the below code in a notepad
and save it with a .vbs extension.
1 'Open QTP
2 SetobjQTP = CreateObject("QuickTest.Application")
3 objQTP.Launch
4 objQTP.Visible = True
6 'Open a test and associate a function library to the test
7 objQTP.Open "C:\Automation\SampleTest", False, False
8 SetobjLib = objQTP.Test.Settings.Resources.Libraries
10 'If the library is not already associated with the test case, associate it..
11 IfobjLib.Find("C:\SampleFunctionLibrary.vbs") = -1 Then' If library is not already ad
12 objLib.Add "C:\SampleFunctionLibrary.vbs", 1 ' Associate the library to the test ca
End
13
3. Using ExecuteFile Method
ExecuteFile statement executes all the VBScript statements in a specified file. After the file
has been executed, all the functions, subroutines and other elements from the file (function
library) are available to the action as global entities. Simply put, once the file is executed,
its functions can be used by the action. You can use the below mentioned logic to use
ExecuteFile method to associate function libraries to your script.
1 'Action begins
2 ExecuteFile "C:\YourFunctionLibrary.vbs"
4 'Other logic for your action would come here
5 '.....
4. Using LoadFunctionLibrary Method
LoadFunctionLibrary, a new method introduced in QTP 11 allows you to load a function
library when a step runs. You can load multiple function libraries from a single line by using
a comma delimiter.
1 'Some code from the action
2 '.....
4 LoadFunctionLibrary "C:\YourFunctionLibrary_1.vbs"'Associate a single function library
5 LoadFunctionLibrary "C:\FuncLib_1.vbs", "C:\FuncLib_2.vbs"'Associate more than 1 funct
6
7 'Other logic for your action would come here
8 '.....
This was all about the different ways using which you can associate function libraries to QTP
Scripts. What are your views on this article? Can you think of any other points which I have
missed and can be added here? Please let us know your views using the comments section.
Happy Reading.. :)
43 Write a program to Enable and Disable Recovery scenarios
Programmatically
Working with Recovery Scenarios using Scripting
Precondition:-
To understand this topic you need to have knowledge on creating and using
recovery scenarios.
In this document I am discussing about how to add, remove recovery scenario files (.QRS)
to a test and after adding how to activate, deactivate and renumbering the order to
execute recovery scenarios.
For example I have a recovery scenario file with the name of sample .qrs. Assume that in
this recovery file I have two recoveries with the names loginPop, RunErr. (All of you know
that one file can have multiple recoveries). Now if i want to use that file in my test then I
have to use following script.
'*******************************************************************
' Create the Application object
Set qtApp = CreateObject("QuickTest.Application")
' Return the Recovery object for the current test
Set qtTestRecovery = qtApp.Test.Settings.Recovery
' Add the " loginPop " scenario as the first scenario
qtTestRecovery.Add "E:\Sudhakar\Recoveryfiles\sample.qrs", " loginPop ", 1
' Add the " RunErr " scenario as the second scenario
qtTestRecovery.Add "E:\Sudhakar\Recoveryfiles\sample.qrs", " RunErr ", 2
' Iterate the scenarios
For intIndex = 1 To qtTestRecovery.Count
' Enable each Recovery Scenario (Note: the 'Item' property is default and can be omitted)
qtTestRecovery.Item(intIndex).Enabled = True
Next
' Enable the recovery mechanism (with default, on errors, setting)
qtTestRecovery.Enabled = true
'Ensure that the recovery mechanism is set to be activated only after errors
qtTestRecovery.SetActivationMode "OnError"
Set qtApp = Nothing ' Release the Application object
Set qtTestRecovery = Nothing ' Release the Recovery object
'*******************************************************************
With the above code automatically the recovery scenarios will be added to the specified
test. After adding the scenarios if you want to control the scenario like changing the
scenario status, to get the scenario name, to activate or deactivate we have to use recovery
object (one of the Utility object).
Recovery Object
It is an utility object to control the recovery scenario mechanism programmatically during
the run session.
Its having some properties and methods to control the scenarios.
Associated Methods
1. Activate Method:
Explicitly activates the recovery scenario mechanism at a specific point in the run.
Note: The Activate method only works if the recovery mechanism is enabled, and only
activates those recovery scenarios that are currently enabled.
If the recovery mechanism is currently disabled, the Activate method does not activate
any recovery scenarios. You can use the Recovery object's Enabled property to change the
status of the recovery mechanism.
Ex:- Recovery.Activate
2. GetScenarioName Method:
Retrieves the name and source file of a recovery scenario, according to the specified
position in the list of recovery scenarios associated with the test.
Ex:- Recovery.GetScenarioName Position, out_ScenarioFile, out_ScenarioName
Msgbox(out_ScenarioFile)
Msgbox(out_ScenarioName)
3. GetScenarioPosition Method
Returns the index position of a recovery scenario in the list of recovery scenarios associated
with the test, according to the specified name and source file.
Ex:- Recovery.GetScenarioPosition (ScenarioFile, ScenarioName)
4. GetScenarioStatus Method
Returns the status of a recovery scenario (True = enabled or False = disabled), according to
the specified index position in the list of recovery scenarios associated with the test.
Ex:- Recovery.GetScenarioStatus Position
SetScenarioStatus Method
Enables or disables the specified recovery scenario, according to its index position in the list
of recovery scenarios associated with the test.
Ex:- Recovery.SetScenarioStatus Position, Status
Associated Properties
Count Property
Returns the number of recovery scenarios associated with the current test.
Ex:- msgbox Recovery.Count
Enabled Property
Recovery default property. Retrieves or sets the status of the recovery scenario mechanism
for the current test.
Ex:- Recovery.Enabled =Status
'********************************************************************
Sample Script
For Iter = 1 to Recovery.Count
Recovery.GetScenarioName Iter, ScenarioFile, ScenarioName
Position = Recovery.GetScenarioPosition( ScenarioFile, ScenarioName )
Status = Recovery.GetScenarioStatus( Position )
Scenario=scenario& ScenarioFile&:=& ScenarioName&,&position&,Status
Next
Msgbox Scenario
'********************************************************************
This code will show total scenarios in the QRS file, position and status of those scenarios.
44 Write a program to Report Results status to Results file
Function initOutExcel(sTablePath)
Datatable.addSheet "Results"
Datatable.importSheet sTablePath, "Results","Results"
iParamCount = Datatable.getSheet("Results").getParameterCount
if iParamCount = 0 Then
Datatable.getSheet("Results").addParameter "S.No",""
Datatable.getSheet("Results").addParameter "Status",""
Datatable.getSheet("Results").addParameter "Functionality",""
Datatable.getSheet("Results").addParameter "Description",""
End If
Datatable.ExportSheet sTablePath,"Results"
End Function
Function WriteResults(sTablePath,sStatus,sFunctionality,sDescription)
Datatable.addSheet "Results"
Datatable.importSheet sTablePath, "Results","Results"
iRowCount = Datatable.getSheet("Results").getRowCount
Datatable.getSheet("Results").setCurrentRow(iRowCount+1)
Datatable("S.No","Results") = iRowCount+1
Datatable("Status","Results") = sStatus
Datatable("Description","Results") = sDescription
Datatable("Functionality","Results") = sFunctionality
Datatable.ExportSheet sTablePath,"Results"
End Function
Or
qtResultsOpt.ResultsLocation = QTPResultspath
App.Test.Run qtResultsOpt
'App.Test.Run
'___________________CODE________________
MasterFolder = "C:\TestAutomation"
Dim App, qtResultsOpt, fso, f
Set App = CreateObject("QuickTest.Application")
If App.Launched = False Then
App.Launch
End If
App.Visible = True
App.Options.Run.ImageCaptureForTestResults = "Always"
App.Options.Run.RunMode = "Fast"
App.Options.Run.ViewResults = True
App.Open MasterFolder&"\Tests\EFiles",False,False
App.Test.Settings.Resources.Libraries.RemoveAll
App.Test.Settings.Resources.Libraries.Add MasterFolder&"\Business Functions\TestScripts.vbs"
'__________________ START of creating a result folder _________________
Temp = Now
Temp1 = Replace (Temp, "/","-")
Temp2 = Replace(Temp1," AM","")
Temp3 = Replace(Temp2," PM","")
Temp4 = Replace(Temp3,":","")
FolderName = Replace(Temp4," ","_")
'QTPResultspath = "C:\TestAutomation\QTPResults\"&FolderName
QTPResultspath = MasterFolder&"\QTPResults\"&FolderName
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(QTPResultspath) Then
Set f = fso.CreateFolder(QTPResultspath)
End If
Set f = nothing
Set fso = nothing
'__________________ END of creating a result folder _________________
Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions")
qtResultsOpt.ResultsLocation = QTPResultspath
App.Test.Run qtResultsOpt
'App.Test.Run
Set App = nothing
Set qtResultsOpt = Nothing
45 Write a program to Find the active window name
Var = Window("ForeGround:=True").GetROProperty("Title")
Msgbox Var
46 Write a program to List out the windows that are open
Option Explicit
Dim ObjBrow,ObjName,ObjBrowName
Set ObjBrow = Description.Create()
ObjBrow(micClass).values = "Browser"
ObjName = Desktop.ChildObject(ObjBrow)
msgbox = ObjName.count
for i = 0 to ObjName.count
ObjBrowName = ObjName(i).getROproperty("Name")
msgbox(ObjBrowName)
ObjName(i).close
Next
Or
Browser("creationtime:=0").Close
Loop
3)Set objWMIService =GetObject"winmgmts:\\.\root\cimv2")
Set colProcess = objWMIService.ExecQuery("SELECT * FROM
Win32_Process")
For Each objProcess In colProcess
If UCase(objProcess.Name) = "IEXPLORE.EXE"
objProcess.Terminate()
End If
Next
47 Write a program to Call reusable actions from different script
By default, if u create a Test in QTP, means u r creating
one action for that test. So if u call for another test
means u need to call the action on that test.
Here is the example : Say u have created "test1". So all
the steops for the test is created with "Action1".
Now u have created another test "test2" and want to call
the test1. Here u need to call by using,
RunAction "Action1[test1]",oneIteration.
By using this u can call the test1 script. There is no
other way than this.
48 Write your own standard checkpoint
49 Write your own synchronization function
SystemUtil.Run "iexplore.exe", "http://www.google.com"
Browser("Google").Page("Google").Sync
Browser("Google").Navigate "http://www.cnn.com"
Browser("Google").Page("CNN.com - Breaking News,").Sync
Wait 10 ' we can read the latest news
Browser("Google").Back
or
Browser("BMC Remedy Mid Tier 7.1").Page("Home Page
(Search)").WebElement("Logout").WaitProperty "visible", true, 20000
50 Write a program to Read menu names
Menu Object
Menu object applies only window based applications. Default Method For Menu is
"Select"
Ex:
Window("Notepad").WinMenu("Menu").Select "File;New Ctrl+N"
Can we do anything more with menu's?
1. Get Menu list from Application
2. Get Menu Items from Menu
'Get menu list from application
Dim cnt
Dim n
Dim iPath
cnt = Window("Notepad").WinMenu("Menu").GetItemProperty("", "SubMenuCount") 'Get total Menus
count From application
For n = 1 To cnt
iPath = Window("Notepad").WinMenu("Menu").BuildMenuPath(itemPath, n)
msgbox Window("Notepad").WinMenu("Menu").GetItemProperty(iPath, "Label")
Next
51 Write a program to Read menu items
'Get menu Items from menu
Dim cnt
Dim n
Dim iPath
cnt = Window("Notepad").WinMenu("Menu").GetItemProperty("File", "SubMenuCount") 'Get menu items
count in "File" Menu
For n = 1 To cnt
iPath = Window("Notepad").WinMenu("Menu").BuildMenuPath("File", n)
msgbox Window("Notepad").WinMenu("Menu").GetItemProperty(iPath, "Label")
Next
52 Write a program to Check whether a check button is selected or not
MyDescription("html tag").Value = "INPUT"
MyDescription("type").Value = "checkbox"
'Add another property to select only the desired checkbox through the drop-down options
Set objWebCheckBox = Window("A").WinButton("B").ChildObjects(MyDescription)
CheckBoxCnt = objWebCheckBox.Count
For i = 0 to (CheckBoxCnt - 1)
objWebCheckBox(i).Set "ON"
Next
53 Write a program to Check whether we can select multiple items in the
listbox
Dim a,i
'Getting list box count
a=Browser().Page().Weblist(WebListName).GetItemsCount
'getting list box values
For i=0 to a-1
msgbox Browser().Page().Weblist(WebListName).GetItem
(i),4,"States"
Next
54 Write a program to Check whether edit box allows exactly 15 characters
Browser("Register: Mercury Tours").Page("Register: Mercury Tours").Image("mast_register").Click
a = Browser("Register: Mercury Tours").Page("Register: Mercury
Tours").WebEdit("firstName").GetROProperty("max length")
If a=15 Then
print "Edit box allows exactly 15 characters"
else
print "Edit box not allows exactly 15 characters"
End If
55 Write a program to Check whether items in the page are aligned properly
56 Write a program to Check whether data in the webtable is left aligned
57 Write a program to Find which add-ins are loaded.
Dim a
Set a=createobject("Quicktest.application")
b=a.getassociatedaddinsfortest("D:\test4")
print "Addins enabled in that test are:"
For each c in b
print c
Next
or
TO FIND ADD-IN FOR CURRENT TEST
Dim a
Set a=createobject("Quicktest.application")
b=a.test.getassociatedaddins()
print "Addins enabled in current test are:"
For each c in b
print c
Next
58 Write a program to Find available add-ins in the tool
59 Write a program to Change window title
60 Write a program to Find whether specified window is there on the
desktop
Option Explicit
Dim ObjBrow,ObjName,ObjBrowName
Set ObjBrow = Description.Create()
ObjBrow(micClass).values = "Browser"
ObjName = Desktop.ChildObject(ObjBrow)
msgbox = ObjName.count
for i = 0 to ObjName.count
ObjBrowName = ObjName(i).getROproperty("Name")
msgbox(ObjBrowName)
ObjName(i).close
Next
Or
Browser("creationtime:=0").Close
Loop
61 Write a program to Check whether a window is in minimized or
maximized
a=window("Flight Reservation").GetROProperty("minimizable")
b=window("Flight Reservation").GetROProperty("maximizable")
If a=true Then
print "FR can be minimised"
else
print "FR cannot be minimised"
End If
If b=true Then
print "FR can be maximised"
else
print "FR cannot be maximised"
End If
62 Write a program to Check window is resizable
Window("Microsoft Word").Activate
a = Window("Microsoft Word").GetROProperty("width")
b = Window("Microsoft Word").GetROProperty("height")
a = a - 50
b = b - 50
Window("Microsoft Word").Resize a,b
reporter.ReportEvent micDone,"PASS","Window is Resizable"
63 Write a program to Read all elements in the XML file
Program
Set a=createobject("msxml2.domdocument")
a.load "D:\test.xml"
set child = a.documentelement.childnodes
childelength =child.length
For i=0 to childelength-1
x=child.item(i).text
print x
Next
64 Write a program to Read attributes of a particular element in the XML file
65 Write a program to Modify attribute value
66 Write a program to Display complete contents of an XML file
67 Write a program to Find font type.
Program
a = Browser("Register: Mercury Tours").Page("Welcome: Mercury Tours").Link("Business Travel @
About.com").GetROProperty("font")
print a
68 Write a program to Find Font size
Program
a = Browser("Register: Mercury Tours").Page("Welcome: Mercury Tours").Link("Business Travel @
About.com").GetROProperty("font Size")
69 Write a program to Check whether text is bold and underlined
70 Write a program to Find the memory utilized by a process
71 Write a program to Verify flash image
72 Write a program to Check pointed link is having different back ground
colour?
73 Write a program to Retrieve Action Parameters
74 Write a program to Disable active screen programmatically
75 Write a program to Modify Mandatory and Assistive properties
programmatically
Set app=createobject("QuickTest.Application")
set ident=app.Options.ObjectIdentification
set buttonprop= ident.item("WinButton")
a =buttonprop.MandatoryProperties.Find("text")
print a
buttonprop.MandatoryProperties.Add("y")
a1=buttonprop.MandatoryProperties.Find("y")
print a1
'buttonprop.MandatoryProperties.Remove("x")
a2=buttonprop.MandatoryProperties.Find("y")
print a2
c = buttonprop.AssistiveProperties.Find("window id")
print c
buttonprop.AssistiveProperties.Add("x")
d = buttonprop.AssistiveProperties.Find("x")
print d
76 Write a program to Configure Run options programmatically
Program
Set a=createobject("QuickTest.Application")
a.options.Run.RunMode="Normal"
a.options.Run.ViewResults="true"
a.options.Run.ImageCaptureForTestResults="OnError"
Before Execution
After Execution
77 Write a program to Define test results location through program
print browser("Browser").Page("Page").WebElement("Born to Lead the
World").GetROProperty("innertext")
reporter.ReportEvent micDone, "Pass","Marquee Captured"
reporter.ReportPath = "D:\"
78 Write a program to Disable Run settings
79 Write a program to Read and Update data from user defined
environmental variable
80 Write a program to Configure maximum timeout value for web page to
load
msgbox Environment("value")
Environment("value")=10
msgbox Environment("value")
81 Write a program to read and delete cookies
82 Write a program to Verify whether status indicator is moving as the
movie is playing
Set a=createobject("QuickTest.Application")
a.options.run.MovieCaptureForTestResults="OnWarning"
83 Write a program to Clear the cache in the webpage
webutil.DeleteCookies
84 Write a program to Check whether webpage is loaded from server or
from cache
85 Write a program to Configure web options programmatically
msgbox Environment("value")
Environment("value")=10
msgbox Environment("value")
86 Write a program to Check whether new items can be added to a listbox
87 Write a program to Check whether link s pointing to correct URL
88 Write a program to invoke the application
Set IE CreateObject("InternetExplorer.Application")
IE.Visible True
IE.Navigate http://www.google.com
89 Write a program to Read parameters in the data table
90 Write a program to List out the windows that are minimized
91 Write a program to add environmental variables during run time
92 Write a program to check whether tab order is left to right and top to
bottom
93 Write a program to find the maximum text length that can be entered in
a edit box
94 Write a program to verify min and max length constraints of text in an
edit box
95 Write a program to find the kind of data edit box accepts
96 Write a program to add objects to object repository file
97 Write a program to export object repository file to XML
98 Write a program to check whether a column in the database table is a
primary key
99 Write a program to display constraints of a column in the database table
100 Write a program to print all button object names in a page
http://www.wiziq.com/tutorial/53994-QTP-Scripting
51 Read and display data from CSV file
Program
Set a=createobject("scripting.filesystemobject")
set b=a.opentextfile("F:\test.csv")
p=1
While not b.atendofstream
x=b.readline
datatable.GetSheet(1).setcurrentrow(p)
datatable.Value("items",1)=x
p=p+1
wend
or
Set a=createobject("scripting.filesystemobject")
set readitems=a.opentextfile("F:\test.csv")
c=readitems.readall
print c
52 Display entire data in the web table
a = Browser("Register: Mercury Tours").Page("Welcome: Mercury Tours").WebTable("Atlanta to Las
Vegas").RowCount
For i = 1 to a
b = Browser("Register: Mercury Tours").Page("Welcome: Mercury
Tours").WebTable("Atlanta to Las Vegas").GetCellData(i,1)
c = Browser("Register: Mercury Tours").Page("Welcome: Mercury
Tours").WebTable("Atlanta to Las Vegas").GetCellData(i,2)
print b & " " &c
Next
Or
s=Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").WebTable("Atlanta to Las
Vegas").GetROProperty("text")
msgbox s
53 Find the background colour of a object
Program
a=Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Link("your
destination").getroproperty("background color")
print a
54 Find screen resolution
Program
a = Window("Program Manager").WinListView("SysListView32").GetROProperty("height")
b = Window("Program Manager").WinListView("SysListView32").GetROProperty("width")
print "The Scree Resolutuion is " & a & " x " & b
55 Write function to compare two bitmaps
Program
a = Browser("Welcome: Mercury Tours").Page("Sign-on: Mercury Tours").Image("sign-
on").GetROProperty("alt")
b = Browser("Welcome: Mercury Tours").Page("Sign-on: Mercury
Tours").Image("Register").GetROProperty("alt")
If a = b Then
print "Both Image Tooltip is Same"
else
print "Both Image Tooltip is Not Same"
End If
56 Add and Remove Repositories to the action
a="D:\open.tsr"
b="D:\insert.tsr"
c="D:\delete.tsr"
repositoriescollection.Add(a)
repositoriescollection.Add(b)
repositoriescollection.Add(c)
Window("Flight Reservation").WinObject("Date of Flight:").Type "121212"
Window("Flight Reservation").WinComboBox("Fly From:").Select "Frankfurt"
Window("Flight Reservation").WinComboBox("Fly To:").Select "London"
Window("Flight Reservation").WinButton("FLIGHT").Click
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
Window("Flight Reservation").WinEdit("Name:").Set "saravanan"
Window("Flight Reservation").WinButton("Insert Order").Click
repositoriescollection.Remove(1)
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "saravanan"
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
Window("Flight Reservation").Dialog("Open Order").Dialog("Search
Results").WinButton("OK").Click
57 Load Library files through program
Program
executefile ("D:\msg.vbs")
58 Enable and Disable Recovery scenarios programmatically
Window("Flight Reservation").Activate
Window("Flight Reservation").WinObject("Date of Flight:").Type "111111"
Window("Flight Reservation").WinComboBox("Fly From:").Select "Fr"
Window("Flight Reservation").WinComboBox("Fly To:").Select "Los Angeles"
Window("Flight Reservation").WinButton("FLIGHT").Click
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
Window("Flight Reservation").WinEdit("Name:").Set "sdf"
Window("Flight Reservation").WinButton("Insert Order").Click
msgbox "The recovery scenario mech is now:" &" "&Recovery.Enabled
MyCurrentStatus=Recovery.Enabled
If Not( MyCurrentStatus ) Then
Recovery.Enabled=True
End If
Recovery.enabled=False
Window("Flight Reservation").WinButton("Button_5").Click
Window("Flight Reservation").WinObject("Date of Flight:").Type "111111"
Window("Flight Reservation").WinComboBox("Fly From:").Select "Frank"
Window("Flight Reservation").WinComboBox("Fly To:").Select "Los Angeles"
Window("Flight Reservation").WinButton("FLIGHT").Click
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
Window("Flight Reservation").WinEdit("Name:").Set "sdf"
Window("Flight Reservation").WinButton("Insert Order").Click
59 Report Results status to Results file
Program
reporter.ReportEvent micDone,"test(Object)","Test Report(Details)"
60 Write your own standard checkpoint
Program
Window("Flight Reservation").WinComboBox("Fly From:").Select "Denver"
Window("Flight Reservation").WinComboBox("Fly To:").Select "London"
b = window("Flight Reservation").Winbutton(a).GetROProperty("Enable")
Window("Flight Reservation").WinButton(a).Click
Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select "20260 DEN 08:12
AM LON 03:23 PM AA $112.20"
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
print b
61 Check whether there is a memory leak in the process
62 Close all the dialogs open on a window
Program
s=Window("Flight Reservation").GetROProperty("hwnd")
window("hwnd:="&s).close
(or)
Window("Flight Reservation").close
63 Read menu names and items
Window("Flight Reservation").WinMenu("Menu").ExpandMenu = True
Window("Flight Reservation").Activate
GetNamesRec "", Window("Flight Reservation").WinMenu("Menu")
Function GetNamesRec(itemPath, menuObj)
ret = 0
lbl = menuObj.GetItemProperty(itemPath, "Label")
print lbl 'contains the label such as file, new etc
ret = menuObj.GetItemProperty(itemPath, "HasSubMenu")
'print ret 'returns boolean if menu is present
If ret Then
cnt = menuObj.GetItemProperty(itemPath, "SubMenuCount")
' print cnt 'returns integer value
For n = 1 To cnt
Path = menuObj.BuildMenuPath(itemPath, n)
GetNamesRec Path, menuObj
Next
End If
End Function
64 Check whether a check button is selected or not
Program
Window("Flight Reservation").Dialog("Open Order").Activate
status=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
No.").GetROProperty("checked")
msgbox status
65 Check whether we can select multiple items in the combo box
Program
a = Window("Flight Reservation").WinComboBox("Fly From:").GetROProperty("selection")
print a & "is Only Selected in ComboBox Selection"
66 Check whether edit box allows exactly 15 characters
Program
Browser("Register: Mercury Tours").Page("Register: Mercury Tours").Image("mast_register").Click
a = Browser("Register: Mercury Tours").Page("Register: Mercury
Tours").WebEdit("firstName").GetROProperty("max length")
If a=15 Then
print "Edit box allows exactly 15 characters"
else
print "Edit box not allows exactly 15 characters"
End If
67 Check whether items in the page are aligned properly
68 Find which add-ins are loaded.
Program
Dim a
Set a=createobject("Quicktest.application")
b=a.getassociatedaddinsfortest("D:\test4")
print "Addins enabled in that test are:"
For each c in b
print c
Next
or
TO FIND ADD-IN FOR CURRENT TEST
Dim a
Set a=createobject("Quicktest.application")
b=a.test.getassociatedaddins()
print "Addins enabled in current test are:"
For each c in b
print c
Next
69 Check whether a window is in minimized or maximized
Program
a=window("Flight Reservation").GetROProperty("minimizable")
b=window("Flight Reservation").GetROProperty("maximizable")
If a=true Then
print "FR can be minimised"
else
print "FR cannot be minimised"
End If
If b=true Then
print "FR can be maximised"
else
print "FR cannot be maximised"
End If
70 Check window resizable
Program
Window("Microsoft Word").Activate
a = Window("Microsoft Word").GetROProperty("width")
b = Window("Microsoft Word").GetROProperty("height")
a = a - 50
b = b - 50
Window("Microsoft Word").Resize a,b
reporter.ReportEvent micDone,"PASS","Window is Resizable"
71 Check whether logo displayed is correct?
72 Read all items in a tree
Program
a = Window("Local Disk (D:)").WinListView("SysListView32").GetItemsCount
For i = 0 to a-1
print Window("Local Disk (D:)").WinListView("SysListView32").GetItem(i)
Next
73 Read elements in the XML file
Program
Set a=createobject("msxml2.domdocument")
a.load "D:\test.xml"
set child = a.documentelement.childnodes
childelength =child.length
For i=0 to childelength-1
x=child.item(i).text
print x
Next
74 Find font type and size
Program
a = Browser("Register: Mercury Tours").Page("Welcome: Mercury Tours").Link("Business Travel @
About.com").GetROProperty("font")
print a
75 Check Marquee
Program
print browser("Browser").Page("Page").WebElement("Born to Lead the
World").GetROProperty("innertext")
76 Check whether selected tab is having different appearance?
77 Check whether a link contains image to its left side.
78 Check whether stock prices are updating an hourly basis
Program
Dim mytime
mytime = now
a = hour(mytime)
print "The Time Now " & a
For i = 1 to 24
If a = i Then
stack = stack + 1000 * i
print stack
End If
Next
79 Modify Mandatory and Assistive properties programmatically
Program
Set app=createobject("QuickTest.Application")
set ident=app.Options.ObjectIdentification
set buttonprop= ident.item("WinButton")
a =buttonprop.MandatoryProperties.Find("text")
print a
buttonprop.MandatoryProperties.Add("y")
a1=buttonprop.MandatoryProperties.Find("y")
print a1
'buttonprop.MandatoryProperties.Remove("x")
a2=buttonprop.MandatoryProperties.Find("y")
print a2
c = buttonprop.AssistiveProperties.Find("window id")
print c
buttonprop.AssistiveProperties.Add("x")
d = buttonprop.AssistiveProperties.Find("x")
print d
80 Configure Run options programmatically
Program
Set a=createobject("QuickTest.Application")
a.options.Run.RunMode="Normal"
a.options.Run.ViewResults="true"
a.options.Run.ImageCaptureForTestResults="OnError"
Before Execution
After Execution
81 Define test results location through program
Program
print browser("Browser").Page("Page").WebElement("Born to Lead the
World").GetROProperty("innertext")
reporter.ReportEvent micDone, "Pass","Marquee Captured"
reporter.ReportPath = "D:\"
82 Read and Update data from environmental variable
Program
MsgBox(environment("prak"))
environment("prak") = 20
MsgBox(environment("prak"))
83 Configure maximum timeout value for web page to load
Program
msgbox Environment("value")
Environment("value")=10
msgbox Environment("value")
84 Clear the cache in the webpage
webutil.DeleteCookies
85 Instruct Quicktest to Capture Movie Segments of Each Error and
Warning
Set a=createobject("QuickTest.Application")
a.options.run.MovieCaptureForTestResults="OnWarning"
VB QUESTIONS
86 Print arms strong number between 1 to 1000.
Program
Dim a, i
For i = 1 to 1000
If len(i) = 3 Then
a = ( i / 100)
a = int (a)
b = ( i / 10)
b = int (b)
c = ( b mod 10)
c = int (c)
d = i mod 10
d = int (d)
j = (a^3) + (c^3) + (d^3)
If i = j Then
print i
End If
End If
Next
87 Find whether the given string is Palindrome or not.
Program
MyStr=inputbox("Enter the string:")
reverse=strreverse(MyStr)
s=strcomp(MyStr,reverse)
If s=0 Then
print "palindrome"
else
print "not palindrome"
End If
88 Write a program to Reverse the string.
Program
a = InputBox("Enter the String to Reverse")
b = strreverse(a)
print "Reversed String is " & b
89 Write a program to print the numbers divisible by 3 and 5.
Program
a = int(InputBox("Enter the number to find whether it is Divisible by 3 and 5 "))
If ((a mod 3)= 0) and ((a mod 5) = 0) Then
Print a &" is Divisible by 3 & 5"
else
Print a &" is not Divisible by 3 & 5"
End If
90 Write a program to print the numbers divisible by 7.
Program
For i=1 to 50
If (i mod 7) =0 Then
print i
End If
Next
91 Print the list of ODD numbers.
Program
print "Odd Number are as follows"
For i=1 to 10
If (i mod 2) <> 0 Then
print i
End If
Next
92 Print the list of EVEN numbers.
Program
print "Even Number are as follows"
For i=1 to 10
If (i mod 2) = 0 Then
print i
End If
Next
Output
93 Print the super numbers between 1 t o 1000
Dim a,b,c,d,e,i
For j = 1 to 50
b=0
For i = 1 to J-1
a = J mod i
If a = 0 Then
b=b+i
End If
Next
If b = J Then
print J
End If
Next
94 Find number of characters in a given string
Program
a = InputBox("Enter the String")
b = len(a)
print "The Length of the string is " & b
95 Write a program to count only the alphabets.
Program
a=inputbox("Enter a string:")
b =len(str)
c=0
For i=1 to b
d=asc(mid(a,i,1))
If d>=65 and d<=90 or d>=97 and d<=122Then
c=c+1
End If
Next
print c
96 Check whether the given number is greater than 100 or not
Program
a = int(InputBox("Enter the Number"))
If a>100 Then
print a & " is greater than 100"
else
print a & " is not greater than 100"
End If
97 Find greatest among two numbers
Program
a = int(InputBox("Enter the First Number"))
b = int(InputBox("Enter the Second Number"))
If a>b Then
print a & " is greater than " & b
else
print b & " is greater than " & a
End If
98 Find greatest among three numbers
Program
a = int(InputBox("Enter the First Number"))
b = int(InputBox("Enter the Second Number"))
c = int(InputBox("Enter the Third Number"))
If a>b and a>c Then
print a &" is greater than " & b & "," & c
elseif b > a and b > c then
print b &" is greater than " & a & "," & c
else
print c &" is greater than " & a & "," & b
End If
99 Write a program to print the Fibonacci series.
Program
a=0
b=1
For i=1 to 10
t=a+b
a=b
b=t
print t
Next
100 Write a program to find whether the given string is equal or not.
Program
101 Write a program to add two matrix.
Program
Dim A(2,2), B(2,2), C(2,2)
For I = 0 to 2
For J = 0 to 2
A(I,J) = Int(InputBox("Enter the Value of of Array A"))
Next
Next
For I = 0 to 2
For J = 0 to 2
B(I,J) = Int(InputBox("Enter the Value of of Array B"))
Next
Next
For I = 0 to 2
For J = 0 to 2
C(i,j) = A(i,j) + B(i,J)
Next
Next
For I = 0 to 2
For J = 0 to 2
MsgBox C(i,j)
Next
Next
Input
6
5
102 Write a program to subtract two matrix.
Program
Dim A(2,2), B(2,2), C(2,2)
For I = 0 to 2
For J = 0 to 2
A(I,J) = Int(InputBox("Enter the Value of of Array A"))
Next
Next
For I = 0 to 2
For J = 0 to 2
B(I,J) = Int(InputBox("Enter the Value of of Array B"))
Next
Next
For I = 0 to 2
For J = 0 to 2
C(i,j) = A(i,j) - B(i,J)
Next
Next
For I = 0 to 2
For J = 0 to 2
MsgBox C(i,j)
Next
Next
Input
2
1
103 Write a program to multiply two matrix
Program
Dim A(1,1), B(1,1), C(1,1)
For I = 0 to 1
For J = 0 to 1
A(I,J) = Int(InputBox(Enter the Value of A(,I,,,J,))
Next
Next
For I = 0 to 1
For J = 0 to 1
B(I,J) = Int(InputBox(Enter the Value of B(,I,,,J,))
Next
Next
For I = 0 to 1
For J = 0 to 1
Sum = 0
For K = 0 to 0
Sum = Sum + A(I,K) + B(K,J)
C(I,J) = Sum
Next
Print C(I,J)
Next
Next
Input
1
104 Input to the Function is Window Name. The Function
should
Check Whether the Window exists or not. If exists activate it or else
exit.
Program
Function windowname(wname)
If a="Flight Reservation" Then
If window("Flight Reservation").Exist Then
Window("Flight Reservation").Activate
else
MsgBox "Window does not exist"
End If
End If
End Function
windowname("Flight Reservation")
105 (a.) First take 2 screens, FR and Open Order; In Argument
is
Screen Name.
(b.) Create 2 shared object repositories (.tsr) for 2 screens that
should be same with screen name.
(c.) Based on the screen name, that particular .tsr should be
loaded.
Program
fun = InputBox("Enter the Functionality Name")
Call tp(fun)
Function tp(fun1)
If fun1 = "Insert Order" Then
repositoriescollection.Add("D:\insert.tsr")
Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button_2").Click
Window("Flight Reservation").WinObject("Date of Flight:").Type "111111"
Window("Flight Reservation").WinComboBox("Fly From:").Select "Denver"
Window("Flight Reservation").WinComboBox("Fly To:").Select "London"
Window("Flight Reservation").WinButton("FLIGHT").Click
Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select "20260
DEN 08:12 AM LON 03:23 PM AA $112.20"
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
Window("Flight Reservation").WinEdit("Name:").Set "Prakash"
Window("Flight Reservation").WinButton("Insert Order").Click
repositoriescollection.RemoveAll
else
repositoriescollection.Add("D:\openorder.tsr")
Window("Flight Reservation").WinButton("Button").Click
Window("Flight Reservation").WinButton("Button_2").Click
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "5"
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
repositoriescollection.RemoveAll
End If
End Function
106 Identify the Total number of Objects in the Object Repository.
Divide objects into 2 arrays based on Data Entry objects and Non
Data Entry objects.
Program
Set a = CreateObject("Mercury.ObjectRepositoryUtil")
a.load "D:\insert.tsr"
print "All the Objects in the Repositories"
Set z = a.getallobjects(Window)
For k = 0 to z.count-1
Set y = z.item(k)
print a.GetLogicalName(y)
Next
Set z = nothing
Set y = nothing
Set k = nothing
Print "Data Entry Items in Repositories"
dataentry = Array("WinEdit","WinComboBox","WinRadioButton","WinCheckBox","WinList")
For j = 0 to ubound(dataentry)
Set b = a.getallobjectsbyClass(dataentry(j))
For i = 0 to b.count-1
Set c = b.item(i)
d = a.getlogicalname(c)
print d
Next
Set b = nothing
Set c = nothing
Set d = nothing
Set e = nothing
Next
107 From the popup message, get the text only and display the main
message only.
Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button").Click
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "55555"
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
If Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").Exist Then
a = window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").Static("Order
number [0-9]* does").GetROProperty("text")
print a
End If
Window("Flight Reservation").Dialog("Open Order").Dialog("Flight
Reservations").WinButton("OK").Click
Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click
108 From the frame error message, get the text and display only the
main message.
Program
a=Browser("Register: Mercury Tours").Page("Register: Mercury Tours").WebElement("Note: The
confirmed password").GetROProperty("innertext")
print a
109 What is the statement used for comparing 2 strings and print the
string is equal or not?
Strcomp is used to compare two string
Program
Dim A, B
A = InputBox("Enter First Name")
B = InputBox("Enter Second Name")
Result = strcomp(A , B)
If Result = 0 Then
print "strings are Equal"
else
print "strings are Not Equal"
End If