1.
Option explicit
2. Variables
Scalar Variables
Array Variables
Static Array and Dynamic Array
3. Object Repository
Local OR and Shared OR
4. Object Identification
0 Normal Identification
1 Mandatory Properties
2 Assistive properties
3 Ordinal Identifier
4 Smart Identification
5. OR Manager
6. Repository Association with Actions
Static Association and Dynamic Association (Utility Object: Repositories Collection)
Repositoriescollection.Add
Repositoriescollection.Find
Repositoriescollection.Item
Repositoriescollection.MoveToPos
Repositoriescollection.Remove
Repositoriescollection.RemoveAll
7. Object Spy & New Features of Object Spy
8. Conditional statements
9. Loops (do while, For- Next, For Each)
10. Merging-Repositories
Conflicts:
Resolutions:
11. Descriptive Programming
Inline Programmingdone through passing string arguments
Programmatic Descriptive Programming:--Collection Objects
Working with Edit Box:
Working with Combo Boxes:
Working with Check Boxes:
Working with Radio Group:
Working with Web Table:
Working with Web Links:
String Description Object Description
Uses less memory as strings are used Requires more memory as objects are created
Increases statement length in case more than one Increase lines of code due to object creation overhead
property is to be used and property assignment
Preferred when property value have regular expression
characters which needs to be treated literally
12. Functions:
String function (Instr, strlen, Split, IsArray, and is Numeric.)we can see the
Available functions on Step generator dialogue box (click F7)
Date Functions:
Math Functions:
5 Built-In functions
6 User defined Functions
Built-In Functions:
7 InStr(sString, sSubString) - Returns the position of the first occurrence of one string within another. The search
begins at the first character of the string
8 InStrRev(sString, sSubString) - Returns the position of the first occurrence of one string within another. The
search begins at the last character of the string
9 LCase(sString) - Converts a specified string to lowercase
10 Left(sString, iLen) - Returns a specified number of characters from the left side of a string
11 Len(sString) - Returns the number of characters in a string
12 LTrim(sString) - Removes spaces on the left side of a string
13 RTrim(sString) - Removes spaces on the right side of a string
14 Trim(sString) - Removes spaces on both the left and the right side of a string
15 Mid(sString, iStart, iLen) - Returns a specified number of characters from a string
16 Replace(sString, sOld, sNew) - Replaces a specified part of a string with another string a specified number of
times
17 Right(sString, iLen) - Returns a specified number of characters from the right side of a string
18 Space(iLen) - Returns a string that consists of a specified number of spaces
19 StrComp(sString1, sString2) - Compares two strings and returns a value that represents the result of the
comparison
20 String(iLen, sChar, iLen) - Returns a string that contains a repeating character of a specified length
21 StrReverse(sString) - Reverses a string
22 UCase(sString) - Converts a specified string to uppercase
23 Asc(sString) - Converts the first letter in a string to ANSI code
Note: What is the default, or initial, value of a variable after the declaration and before the first assignment?
The answer is: Empty.
There are 3 ways to check if a variable has the Empty value:
24 Using the IsEmpty(variable_name) function to return a Boolean value True.
25 Using the VarType(variable_name) function to return a predefined constant, vbEmpty.
26 Using the TypeName(variable_name) function to return a string, "Empty".
FAQ s on VB Scripts:
1. What are the data types Supported by VB SCRIPT.?
VB script has only one Data Type Called Variant It holds different categories of Information:
Empty ,Null ,Boolean,Byte,Integer,Long Single,Double,Date/Time ,Currency ,String, Object ,error
2. What is the use of ReDim statement in VBScript?
3.What are the major differences between Visual Basic and VBScript?
4. Why to use option explicit in vb script
5. How to open browser in vb script
set ie=createobject(internetexplorer.application)
ie.navigate(http://www.google.co.in/)
ie.visible=true
set ie = nothing
5. How to write functions and sub in vb script
function add(a,b)
sum=a+b
add=sum
end function
s=add(6,8)
msgbox s
sub add2(x,y)
sum=x+y
msgbox sum
end sub
call add2(6,8)
13. DB Connection
Algorithm:
1. Create an ADODB.Connection object (the database object).
2. Set the connection string for the database object.
3. Open the connection to the database.
4. Execute a SQL statement.
5. Close the database connection.
Eg:
Dim con, rs
Set con=createobject ("adodb.connection") /*****Ado Connection Object Creation)
Set rs=createobject ("adodb.recordset") /**Record set object used to hold a set of
Records from a database table)
Con.open"provider=sqloledb.1; server=server2008; uid=vijay; Pwd=vijay"
rs.open "select *from person, /******selecting from Person table
Do while not rs.eof
Msgbox rs.field.item (1)
rs.moveNext
Loop
con.close
ADODB Connection Object; Record set Object
Test Database Creation; Collecting Test Data
Databases Connections (Ms-Access, SQL Server and Oracle)
Data Driven Testing by fetching Data from a Database
Data Comparisons
14. File System Object. (Imp for product base companies)
Create Folder
Create Subfolder
Create file under folder/Subfolder
Move folder/File
Copy folder/File
Update file, Delete File, Delete folder
Create a file "test.txt" located in C:
Dim fso, file, file location
file location = "C:\file_location"
Set fso = Create Object (Scripting.FileSystemObject)
Set file = fso.CreateTextFile (file location, True)
// True--> file is to be overwritten if it already exists else false
Open a file?
Set file= fso.OpenTextFile("C:\file_location", ForWriting, True)
//2nd argument can be ForReading, ForWriting, ForAppending
//3rd argument is "True" if new file has to be created if the specified file doesnt exist else false,
blank signify false.
Read Content from a file?
Use ReadLine () method
for example:
Set file= fso.OpenTextFile ("C:\file_location", ForReading, True) //2nd argument should always be
"ForReading" in order to read contents from a file
Do while file.AtEndofStream <> True
data = file.ReadLine ()
msgbox data
Loop
Write Content to a file?
Set file= fso.OpenTextFile ("C:\file_location", ForWriting, True) //2nd argument should always be
"ForWriting" in order to write contents to a file
file. Write ("This is a place to get all your qtp")
file. Write ("questions and answers solved.")
//Output will be:
This is a place to get all your qtp questions and answers solved.
While
file.WriteLine ("This is a place to get all your qtp")
file. Write ("questions and answers solved.")
//Output will be:
This is a place to get all your qtp
questions and answers solved.
Delete Content?
File location = "C:\file_location"
Set fso = Create Object (Scripting.FileSystemObject)
fso.DeleteFile(file location)
15. Parameterization
Data Table (Global sheet, Action1, Action2...)
Excel Sheet
16. Error Handling
On Error Resume Next
On Error GOTO 0
Err. Number
Err. Description
17. Actions
27 Creating an Action
28 Splitting Actions
29 Renaming an Action
30 Deleting an Action
31 Making an Reusable/Non-Reusable
32 Calling an existing Action
33 Copying an Actions
34 Action Parameters
Dictionary:
Dictionary object is used with the index (key) being string. In the case of array, the index can be ONLY
numeric. Then of course we have some obvious advantages like referencing a value with a meaningful
keys etc.
Methods
Add Adds a new item to the
dictionary
Exists Verifies whether a given key
exists in the dictionary
Items Returns an array with all the
values in a dictionary
Keys Returns an array with all the
keys in a dictionary
Remove Removes the item identified by
the specified key
RemoveAll Removes all the items in the
dictionary
Properties
Count Returns the number of items in a
dictionary
Item Sets and returns an item for the
specified key
Key Changes an item's key
35 Dim dict Create a variable.
Set dict = CreateObject (Scripting. Dictionary)
Add Method:
dict.Add Company, HP Adding keys and corresponding items.
dict.Add Tool, Quickest Pro
dict.Add Website, LearnQTP
Exists Method:
If dict.Exists (Country) Then
msg = Specified key exists.
Else
msg = Specified key doesnt exist.
End If
Retrieve Keys and Items from dictionary:
i = dict.Items Get the items.
k = dict.Keys Get the keys.
For x = 0 to dict.Count-1 Iterate the array.
msgbox i(x) &: & k(x)
Next
Remove Key and Item from Dictionary:
dict.Remove (Website)
RemoveAll
dict.RemoveAll Clear the dictionary
Excel Object Model Samples
Create excel file and enter some data save it
'###############################################
'Create excel file and enter some data save it
'###############################################
'Create Excel Object
Set excel=createobject("excel. application")
'Make it Visible
Excel. Visible=True
'Add New Workbook
Set workbooks=excel.Workbooks.Add()
'Set the value in First row first column
excel.Cells(1,1).value="testing"
'Save Work Book
workbooks.saveas"D:\excel.xls"
'Close Work Book
Workbooks. Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set workbooks=Nothing
Set excel=Nothing
'###############################################
' Reading Values from a Specific excel Sheet
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open the Excel File
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
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet1=Nothing
Set workbook=Nothing
Set excel=Nothing
Deleting Rows from Excel Sheet
'###############################################
' Deleting Rows from Excel Sheet
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open the Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get the Control on Specific Sheet
Set worksheet1=excel.Worksheets.Item("Sheet1")
'Delete Row1
worksheet1.Rows("1:1").delete
'Save Excel
workbook.SaveAs("D:\excel.xls")
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet1=Nothing
Set workbook=Nothing
Set excel=Nothing
Add and Delete ExcelSheet
'###############################################
' Add and Delete ExcelSheet
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Existing Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Add New Sheet
Set newsheet=workbook.sheets.Add
'Assign a Name
newsheet.name="raj"
'Delete Sheet
Set delsheet=workbook.Sheets("raj")
delsheet.delete
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set newsheet=Nothing
Set delsheet=Nothing
Set workbook=Nothing
Set excel=Nothing
'###############################################
' Copy an Excel Sheet of one Excel File to another Excel File
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open First Excel File
Set workbook1=excel.Workbooks.Open("D:\excel1.xls")
'Open Second Excel File
Set workbook2=excel.Workbooks.Open("D:\excel2.xls")
'Copy data from first excel file sheet
workbook1.Worksheets("raj").usedrange.copy
'Paste Data to Second Excel File Sheet
workbook2.Worksheets("Sheet1").pastespecial
'Save Workbooks
workbook1.Save
workbook2.Save
'Close Workbooks
workbook1.Close
workbook2.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set workbook1=Nothing
Set workbook2=Nothing
Set excel=Nothing
Comapre Two Excel Sheets Cell By Cell for a specific Range
'###############################################
' Comapre Two Excel Sheets Cell By Cell for a specific Range
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get Control on First Sheet
Set sheet1=excel.Worksheets.Item("Sheet1")
'Get Control on Second Sheet
Set sheet2=excel.Worksheets.Item("Sheet2")
'Give the specific range for Comparision
CompareRangeStartRow=1
NoofRows2Compare=4
CompareRangeStartColumn=1
NoofColumns2Compare=4
'Loop through Rows
For r=CompareRangeStartRow to(CompareRangeStartRow+(NoofRows2Compare-1))
'Loop through columns
For c=CompareRangeStartColumn to(CompareRangeStartColumn+(NoofColumns2Compare-1))
'Get Value from the First Sheet
value1=Trim(sheet1.cells(r,c))
'Get Value from the Second Sheet
value2=Trim(sheet2.cells(r,c))
'Compare Values
If value1<>value2 Then
' If Values are not matched make the text with Red color
sheet2.cells(r,c).font.color=vbred
End If
Next
Next
'Save workbook
workbook.Save
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set sheet1=Nothing
Set sheet2=Nothing
Set workbook=Nothing
Set excel=Nothing
Reading complete data from excel file
'###############################################
' Reading complete data from excel file
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get Control on Sheet
Set worksheet=excel.Worksheets.Item("raj")
'Get the count of used columns
ColumnCount=worksheet.usedrange.columns.count
'Get the count of used Rows
RowCount=worksheet.usedrange.rows.count
'Get the Starting used Row and column
top=worksheet.usedrange.row
lft=worksheet.usedrange.column
'Get cell object to get the values cell by cell
Set cells=worksheet.cells
'Loop through Rows
For row=top to (RowCount-1)
rdata=""
'Loop through Columns
For col=lft to ColumnCount-1
'Get Cell Value
word=cells(row,col).value
'concatenate all row cell values into one variable
rdata=rdata&vbtab&word
Next
'Print complete Row Cell Values
print rdata
Next
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet=Nothing
Set workbook=Nothing
Set excel=Nothing
Read complete data from an Excel Sheet content
'###############################################
' Read complete data from an Excel Sheet content
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Excel File
Set workbook=excel.Workbooks.open("D:\excel.xlsx")
'Get Control on Sheet
Set worksheet=excel.Worksheets.Item("Sheet1")
'Get Used Row and Column Count
rc=worksheet.usedrange.rows.count
cc=worksheet.usedrange.columns.count
'Loop through Rows
For Row=1 to rc
'Loop through Columns
For Column=1 to cc
'Get Cell Data
RowData=RowData&worksheet.cells(Row,Column)&vbtab
Next
RowData=RowData&vbcrlf
Next
'Display complete Data
msgbox RowData
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet=Nothing
Set workbook=Nothing
Set excel=Nothing
Assign Colours to Excel Sheet Cells, Rows
###############################################
' Assign Colours to Excel Sheet Cells, Rows
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Add a New work book
Set workbook=excel.workbooks.add()
'Get the Excel Sheet
Set worksheet=excel.worksheets(1)
'Coloring Excell Sheet Rows
Set objrange=excel.activecell.entirerow
objrange.cells.interior.colorindex=37
'Coloring Excell Sheet Cell
worksheet.cells(2,1).interior.colorindex=36
'Save Excel
workbook.SaveAs("D:\excel.xls")
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set objrange=Nothing
Set worksheet=Nothing
Set workbook=Nothing
Set excel=Nothing
Script to get the Number of Edit Boxes Available on webpage.
Set Desc = Description. Create ()
Desc("micclass").Value = "WebEdit"
Set Edits = Browser("Google Sets").Page("Google Sets").ChildObjects(Desc)
MsgBox "Number of Edits: " & Edits. Count
Using functions how to get number of Objects on a webpage:
Function GetAllSpecificControls (Page, MicClass)
Set Desc = Description. Create()
Desc("micclass").Value = MicClass
Set GetAllSpecificControls = Page.ChildObjects(Desc)
End Function
Function GetAllEdits(Page)
Set GetAllEdits = GetAllSpecificControls(Page, "WebEdit")
End Function
Function GetAllButtons(Page)
Set GetAllButtons = GetAllSpecificControls(Page, "WebButton")
End Function
Function GetAllLinks(Page)
Set GetAllLinks = GetAllSpecificControls(Page, "Link")
End Function
Function GetAllImages(Page)
Set GetAllImages = GetAllSpecificControls(Page, "Image")
End Function
Set oPage = Browser("Google Sets").Page("Google Sets")
MsgBox "Number of Edits: " & GetAllEdits(oPage).Count
MsgBox "Number of Buttons: " & GetAllButtons(oPage).Count
MsgBox "Number of Links: " & GetAllLinks(oPage).Count
MsgBox "Number of Images: " & GetAllImages(oPage).Count
Frame work:
Structural arrangement of components in project is a Frame Work
Modular Driven (Functional Decomposition): Functions drives the script.
Data Driven: Data drives the script ---If we want to supply large Amount of Data then we can go for Data
Driven
Key word Driven: Key Word drives the script
Hybrid:
Key Word Driven:
In Key Word Driven Framework the script values will be written in Excel files and QTP will execute them
using Driver Script
There are majorly two approaches followed to make Keyword Driven Framework.
1. Specify Script Values Directly in the Excel
2. Write Global Functions for each and every application control and specify those functions as keywords in
Excel
Approach 1:
In the below table there are 4 columns
Object Class : - Class of the object on which we are going to perform the operation
Object Properties: - Properties of the object
Operation :- The method to perform on the object
Value :- Input Data
'Object Properties constants
Public Const Google Browser = "name: =Google"
Public Const Google Page = "title: =Google"
Public Const Search Edit = "name: =q"
Public Const Search Button = "name: =Google Search"
Why do we need to specify object properties as constants?
We can specify properties directly in place of constants. But when you get a failure in the script, you might
not able to identify where exactly the error occurs
Follow the below steps prior to write the driver script.
1. Create a Folder KeyWordDrivenSample in C:\ drive
36 In this folder create 3 subfolders with the names Scripts, Constants, Keywords
2. Prepare an excel like how it is available in above table Save the Excel file in
The C:\KeyWordDrivenSample\KeyWords folder with the name ScriptKeywords.xls
3. Copy above Object Description Constants in a VBS File and save it in
The C:\KeyWordDrivenSample\Coanstants with the name OR Constants.vbs
4. Open a new test in QTP and Save the test in C:\KeyWordDrivenSample\Scripts Folder with the
Name Driver Script Now you should have the Folder structure like specified below
Folder Structure:
Driver Script:
###################################################################
' Objective : This is a driver script for Sample Keyword Driven Framework
' Test Case : Driver Script
' Author : Vijay .Damaraju
' Date Created : 04/14/2011
' Date Updated : 04/14/2011
'Updated by : Sudhakar Kakunuri
'###################################################################
'##############Initialize Variables and Load Libraries#############################
Execute File "..\..\Constants\OR Constants.vbs"
'#####################Driver Script ######################################
'Add a new sheet and import keywords
Set dtKeyWords=DataTable.AddSheet("Keywords")
Datatable.ImportSheet "..\..\Keywords\ScriptKeywords.xls","Sheet1","Keywords"
'Get Row Count and Column Colunt of the databable
dtRowCount=dtKeyWords.GetRowCount
dtColumnCount=dtKeyWords.GetParameterCount
'Use for lop to get values row by row
For dtRow=1 to dtRowCount
dtKeyWords.SetCurrentRow (dtRow)
strObjClass = DataTable("ObjectClass","Keywords")
strObjProperties = DataTable("ObjectProperties","Keywords")
strOperation = DataTable("Operation","Keywords")
strValue = DataTable("Value","Keywords")
If strOperation="SetParent" Then
oParentObjectArray=Split(strObjClass,"/")
oParentObjectPropArray=Split(strObjProperties,"/")
For iParentCount=0 to ubound(oParentObjectArray)
iParent=oParentObjectArray(iParentCount)
iParentProps=oParentObjectPropArray(iParentCount)
If iParentCount=ubound(oParentObjectArray) Then
strParent=strParent&iParent&"("&""""&eval(iParentProps)&""""&")"
Exit For
End If
strParent=strParent&iParent&"("&""""&eval(iParentProps)&""""&")."
Next
ParentObject=strParent
Else
oStatement=ParentObject&"."&strObjClass&"("&""""& eval(strObjProperties) &""""&
")."& strOperation
If strValue<>"" Then
iStrInputDataArray=split(strValue,",")
For iInputValuesCount=0 to UBound(iStrInputDataArray)
If iInputValuesCount=UBound(iStrInputDataArray) Then
oStatement=oStatement&" "&""""& iStrInputDataArray(iInputValuesCount)
&""""
Exit for
End If
oStatement=oStatement&" "&""""& iStrInputDataArray(iInputValuesCount) &""""&","
Next
End If
Execute (oStatement)
End If
Next
'###################################################################
Recovery Scenarios in QTP:
What are Recover Scenarios?
While executing your scripts you may get some UNEXPECTED/UNPREDICTABLE errors. (like
printer out of paper). To "recover" the test (and continue running) from these unexpected
errors you use Recovery Scenarios.
When to use "on error resume next" or programmatic handling of errors VS Recovery
Scenarios?
If you can predict that a certain event may happen at a specific point in your test or
component, it is recommended to handle that event directly within your test or component
by adding steps such as If statements or optional steps or "on error resume next", rather
than depending on a recovery scenario. Using Recovery Scenarios may result in unusually
slow performance of your tests. They are designed to handle a more generic set of
unpredictable events which CANNOT be handled programmatically.
For Example:
A recovery scenario can handle a printer error by clicking the default button in the
Printer Error message box.
You cannot handle this error directly in your test or component, since you cannot know at
what point the network will return the printer error. You could try to handle this event
in your test or component by adding an If statement immediately after the step that sent a
file to the printer, but if the network takes time to return the printer error, your test
or component may have progressed several steps before the error is displayed. Therefore,
for this type of event, only a recovery scenario can handle it.
Trigger Event. The event that interrupts your run session. For example, a window that may
pop up on screen, or a QTP run error.
Recovery Operations. The operations to perform to enable QTP to continue running the test
after the trigger event interrupts the run session. For example, clicking an OK button in
a pop-up window, or restarting Microsoft Windows.
Post-Recovery Test Run Option. The instructions on how QTP should proceed after the
recovery operations have been performed, and from which point in the test QTP should
continue, if at all. For example, you may want to restart a test from the beginning, or
skip a step entirely and continue with the next step in the test.
Recovery scenarios are saved in recovery scenario files having the extension .rs. A
recovery scenario file is a logical collection of recovery scenarios, grouped according to
your own specific requirements.
1. Go to TOOLS -> Recovery scenario manager.
2. Select the trigger event that caused the error (it may be a pop up
window).
3. Identify the name of the window with the help of POINTING HAND.
4. Choose the operation type: KEYBOARD OR MOUSE OPERATION.
5. Select the action with the help of POINTING HAND. (E.g. Click on OK
button to close the window.)
6. If you want to add another action then keep "Add another recovery
scenario" check box selected else de select it.
7. In the "Post recovery test run option" select "Proceed to next test
iteration"
8. Give scenario name & description & click on finish button.
9. Save the scenario.
10. Go to TEST->SETTINGS->SCENARIO TAB....and add the saved scenario.
11. Click on APPLY & OK button......now your test run smoothly.
1.QTP Script for Combo box Control:
In combo box Item index start from 0(zero)
Eg: Script for selecting an item from combo box using its value.
Window(Flight Reservation).Wincombobox(Fly from :).selectFrankfurt
//Script for selecting an Item from combo box using its Index:
Window(fligh reservation).wincombobox(Fly From:).select1
//Script to get all Items one by one from combobox
Count= Window(Flight Reservation).Wincombobox(Fly from :).GetItemsCount
Msgbox Count
For i=0 to count-1
Item= Window(Flight Reservation).Wincombobox(Fly from :).getitem(i)
Msgbox item
//Output:single Item displayed one by one in a messagebox
//Total Items display in one shot:
Content= Window(Flight Reservation).Wincombobox(Fly from :).GetContent
Msgbox Content.
2. QTP Script for Edit Box:
Script to check whether particular text box exist or Not
If dialog(Login).winedit(agentName:).exists then
MsgboxThe text box exists
Else
msgbox textbox doesnot exists
QTP Script for checkbox:
Syntax:
Object Hierarchy.seton/off
Eg:
Window().checkbox(one).seton
To Uncheck:
Window().checkbox(one).setoff
QTP Script for Button:
Dialog(Login).winbutton(ok).click
//qtp script to check whether button is enabled or not
A=dialog(Login).winbutton(ok).GetROProperty(enabled)
If a=True then
Msgbox(Ok Button is enabled)
Else
Msgbox (Ok Button is disabled)
End if
Interview Questions:
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
4 Write a program to Capture Desktop Screen shot
5 Write a program to Read tab names from a tabbed window
6 Write a program to Check whether scrollbars exists inside a editor
7 Write a program to check whether edit box is enabled or writable
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
12 Write a program to capture web button image
13 Write a program to List all links in the web page
14 Write a program to Check whether given link exists or not
15 Write a program to find image width and Height
16 Write a program to Print URL displayed in the address bar
17 Write a program to check whether webpage downloaded completely
18 Write a program to refresh a web page
19 Write a program to Verify page title is displayed correctly
20 Write a program to Verify whether page contains frames
21 Write a program to find page load time
22 Write a program to Check given text is displayed on the web page
23 Write a program to find whether image contains tool tip
24 Write a program to invoke the Browser with specified URL
25 Write a program to Import an excel file to a Data table
26 Write a program to Read data from first parameter of Global sheet
27 Write a program to Read data from all sheets and all parameters of the excel file
28 Write a program to place data in a specific sheet in the excel file
29 Write a program to Import data to data table from a database
30 Write a program to Read and display data from CSV file
31 Write a program to Find number of rows and columns in a web table
32 Write a program to Display entire data in the web table
33 Write a program to Display all images in the webpage
34 Write a program to Check whether table contains headers
35 Write a program to find the background color of a web object
36 Write a program to print results in a HTML format
37 Write a program to select different radio buttons for different script iterations
38 Write a program to Read all the items from a services window
39 Write a program to Find screen resolution
40 Write function to compare two bitmaps
41 Write a program to Add and Remove Repositories to the action
42 Write a program to Load Library files
43 Write a program to enable and Disable Recovery scenarios programmatically
44 Write a program to Report Results status to Results file
45 Write a program to find the active window name
46 Write a program to List out the windows that are open
47 Write a program to call reusable actions from different script
48 Write your own standard checkpoint
49 Write your own synchronization function
50 Write a program to Read menu names
51 Write a program to Read menu items
52 Write a program to Check whether a check button is selected or not
53 Write a program to Check whether we can select multiple items in the listbox
54 Write a program to Check whether edit box allows exactly 15 characters
55 Write a program to Check whether items in the page are aligned properly
56 Write a program to Check whether data in the web table is left aligned
57 Write a program to Find which add-ins are loaded.
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
61 Write a program to Check whether a window is in minimized or maximized
62 Write a program to Check window is resizable
63 Write a program to Read all elements in the XML file
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.
68 Write a program to Find 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
76 Write a program to Configure Run options programmatically
77 Write a program to Define test results location through program
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
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
83 Write a program to Clear the cache in the webpage
84 Write a program to Check whether webpage is loaded from server or from cache
85 Write a program to Configure web options programmatically
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
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
HP (Bangalore) INTERVIEW QUESTIONS
What is S.D.L.C & S.T.L.C?
What is test case?
Explain Bug lifecycle?
What are the checkpoints available in QTP?
Diff b/w Bitmap & image Check point?
Explain Smart identification?
What is Recovery Scenario?
What are the triggers events are there in QTP?
What is the difference b/w Action & Function?
What is descriptive programming?
What are the types in descriptive programming?
How to create Excel Application?
Diff B/w function and procedure?
How do you send information to test results?
How to get contents of the excel application?
How to put colors in Excel application?
Explain Actions?
How many modules are there in QC?
How to map requirements to tests in QC?
Explain Regular Expressions?
My window name india1. It may get change to india12345. How to handle this situation?
Write a script to Read file?
What is File System Object?
Explain create object function?
Explain your framework?
What is the difference b/w Array and Dictionary object?
Cap Gemini (Bangalore) INTERVIEW QUESTIONS
What is the default recording mode?
Explain any 5 built-in functions of VBScript?
What is difference b/w Logical name and Physical name?
What are the default properties that Browser object use?
How many data types are there in VBScript?
How do you change the Data table sheet name?
What will you do if object spy is not showing any properties for an object?
How to read a particular cell value of a Data Sheet?
There are some buttons, edit boxes and Images in a browser. How to get one by one objects count by using
descriptive programming?
Write down the script for regular expressions?
Write a script to manage the recovery Scenarios?
NOUS (Bangalore) INTERVIEW QUESTIONS
Reverse the string without using strreverse function?
Write a program to create Pascal triangle?
What is lbound and ubound?
There are 10 webedits in a page. How do you set the same value in all webedits using descriptive
programming?
Write regular expression for mail id?
How do you get rows and columns count of a web table?
How do you convert a variable to an array?
What is mid function?
Explain split function?
How to edit reusable actions?
QTP Questions
VB Script Syntax (50 Examples)
1 Print Hello World
2 Find whether given number is a odd number
3 Print odd numbers between given range of numbers
4 Find the factorial of a given number
5 Find the factors of a given number
6 Print prime numbers between given range of numbers
7 Swap 2 numbers with out a temporary variable
8 Write a program to Perform specified Arithmetic Operation on two given numbers
9 Find the length of a given string
10 Reverse given string
11 Find how many alpha characters present in a string.
12 Find occurrences of a specific character in a string
13 Replace space with tab in between the words of a string.
14 Write a program to return ASCII value of a given character
15 Write a program to return character corresponding to the given ASCII value
16 Convert string to Upper Case
17 Convert string to lower case
18 Write a program to Replace a word in a string with another word
19 Check whether the string is a POLYNDROM
20 Verify whether given two strings are equal
21 Print all values from an Array
22 Sort Array elements
23 Add two 3X3 matrices
24 Multiply Two Matrices of size 2X2
25 Convert a String in to an array
26 Convert a String in to an array using I as delimiter
27 Find number of words in string
28 Write a program to reverse the words of a given string.
29 Print the data as a Pascal triangle
30 Join elements of an array as a string
31 Trim a given string from both sides
32 Write a program to insert 100values and to delete 50 values from an array
33 Write a program to force the declaration of variables
34 Write a program to raise an error and print the error number.
35 Finding whether a variable is an Array
36 Write a program to Convert value into a currency
37 Write a program to Convert an expression to a date
38 Display current date and Time
39 Find difference between two dates.
40 Add time interval to a date
41 Print current day of the week
42 Convert Date from Indian Format to US format
43 Find whether current month is a long month
44 Find whether given year is a leap year
45 Format Number to specified decimal places
46 Write a program to Generate a Random Number
47 Write a program to show difference between Fix and Int
48 Write a program to find subtype of a variable
49 Write a program to print the decimal part of a given number
50 Write a Function to return a random number
51 Write a Function to add and multiply two numbers
52 Write a Sub Procedure to print Hello World
53 Write a Sub Procedure to add and multiply two numbers
54 Write a program to list the Time zone offset from GMT
VB Script Advanced Programming (100 Examples)
1 Write a program to read data from a text file
2 Write a program to write data into a text file
3 Write a program to print all lines that contains a word either infics or solutions
4 Write a program to print the current folder name
5 Write a program to print files in a given folder
6 Write a program to print subfolders in a given folder
7 Write a program to print all drives in the file system
8 Write a program to print current drive name
9 Print the last modified and creation date of a given file
10 Print the size of the file and size on the disk.
11 Write a program to display files of a specific type
12 Write a program to print the free space in a given drive
13 Write a program to display all subfolders in a given folder
14 Write a program to find whether a given folder is a special folder
15 Write a program to remove all empty files in the folder
16 Write a program to Copy contents of one folder to other folder
17 Write a program to check whether a given path represents a file or a folder
18 Write a program to compress a folder
19 Write a program to rename a folder
20 Write program to display all folders created on a specific date
21 Write a Program to enable disk quotas
22 Write a program to create, modify and delete disk quota
23 Write a program to display all files containing demo in their name
24 Write a program to print all lines in a file that ends with world
25 Write a program to check whether string starts with Error
26 Write a program to Replace all words that contains demo in a file with the word infics
27 Write a program to check whether a string contains only alpha numeric
28 Write a program to check whether a string is in email format
29 Write a program to check whether given string is in date format
30 Write a program to print all the lines ending with '$'
31 Check whether middle three characters in a word contains alphanumeric
32 Check whether a given line is an empty
33 Write a program to Add elements to a dictionary
34 Write a program to display items in a dictionary
35 Write a program to check whether specified Key exists in a Dictionary
36 Write a program to Store dictionary items in an array
37 Write a program to delete Key Value pair in the dictionary
38 Write a program to monitor operating system performance
39 Write a program to monitor operating system objects
40 Write a program to monitor web server performance
41 Write a program to monitor browser service performance
42 Write a program to list the PID and PPID of a process
43 Write a program to create a registry key
44 Write a program to list registry files
45 Write a program to list registry value and types
46 Write a program to delete registry key
47 Write a program to Stop and Start alerter service
48 Write a program to list services running and their statuses.
49 Write a program to list services that can be stopped
50 Write a program to start auto start services that have stopped
51 Write a program to Invoke command prompt and execute dir command from the shell
52 Write a program to schedule a task
53 Write a program to list and delete scheduled tasks
54 Write a program to add a local user account
55 Write a program to disable and delete a local user account
56 Write a program to list all user accounts in the local computer
57 Write a program to display logged in user name
58 Write a program to list cache memory information
59 Write a program to list physical memory properties
60 Write a program to list memory devices
61 Write a program to find Hard Disk size
62 Write a program to find RAM size
63 Write a program to restart a computer
64 Write a program to shutdown a computer
65 Write a program to Execute Perl script from VB Script
66 Find the systems present in the LAN
67 Write a program to Print using remote printer
68 Verify whether IE enhanced security is enabled for logged on user
69 Write a program to add a website to a favorite menu
70 Write a program to list IE LAN settings
71 Write a program to list cache, connection and security zone settings
72 Find the arguments passed to a Windows Script Host
73 Write a program to Map a network drive
74 Write a program to Print to the local printer
75 Write a program to Print to remote printer
76 Write a program to Print Computer name
77 Write a program to Print free memory in the drive
78 Write a program to Print memory and CPU utilized by a process
79 Write a program to Find the padres of a local system
80 Write a program to find Network Drives
81 Write a program to find the Full path name of a shortcut
82 Write a program to Retrieve all the rows in a table
83 Write a program to find the name of columns in a table
84 Write a program to find number of rows in each column
85 Write a program to connect and print data from oracle database
86 Write a program to connect and print data from SQL Server database
87 Write a program to retrieve specific field from the database table
88 Write a program to check whether a column in the database is in ascending order
89 Write a program to insert a new row into the database table
90 Write a program to open the two record sets
91 Write a program to Update the specific field in the database table
92 Write a program to delete all records whose username starts with demo
93 Write a program to sort the record set
94 Write a program to find number of rows in a table
95 Write a program to Write simple text to windows word
96 Write a program to Write table to windows word
97 Write a program to apply style to a table in word document
98 Write a program to open and print a word document
99 Write a program to send an email using outlook
100 Write a program to print data present in all sheets of an excel files
QTP Scripting (100 Examples)
1 Write a program to enter data in login screen
2 Write a program to find the x and y coordinates of a button
3 Write a program to Read items in a list box
4 Write a program to Read items on a desktop
5 Write a program to Capture Desktop Screen shot
6 Write a program to Read tab names from a tabbed window
7 Write a program to Check whether scrollbars exists inside a editor
8 Write a program to check whether edit box is enabled or writable
MyString = Browser (Obj).Page (Obj).WebEdit (Obj).GetRoPerperty (enabled)
IF (MyString = 1 or True) then
Msgbox & Web Edit is Visible: & Mystring
Else
Msgbox & Web Edit is not visible: & Mystring
End if
9 Write a program to Check scroll bars in a web page
10 Write a program to Check whether dialog is middle of the window
11 Write a program to Check whether Window is middle of the screen
12 Write a program to Check whether country contains all the states
13 Write a program to Check whether edit box is focused
14 Write a program to Check default selection in a list box
15 Write a program to Capture web button image
16 Write a program to List all links in the web page
17 Write a program to Check whether given link exists
18 Write a program to Find image width and Height
19 Write a program to Print URL displayed in the address bar
20 Write a program to Check whether webpage downloaded completely
21 Write a program to Refresh a web page
22 Write a program to Verify page title is displayed correctly
23 Write a program to Verify whether page contains frames
24 Write a program to Find page load time
25 Write a program to Check given text is displayed on the web page
26 Write a program to Find whether image contains tool tip
27 Write a program to Invoke the Browser with specified URL
28 Write a program to Import an excel file to a Data table
29 Write a program to Read data from first parameter of Global sheet
30 Write a program to Read data from all sheets and all parameters of the excel file
31 Write a program to place data in a specific sheet in the excel file
32 Write a program to Import data to data table from a database
33 Write a program to Read and display data from CSV file
35 Write a program to Find number of rows and columns in a web table
36 Write a program to Display entire data in the web table
37 Write a program to Display all images in the webpage
38 Write a program to Check whether table contains headers
39 Write a program to Find the background color of a web object
40 Write a program to Print results in a HTML format
41 Write a program to Select different radio buttons for different script iterations
42 Write a program to Find the dialog Height whose window name is Appointments
43 Write a program to Read all the items from a services window
44 Write a program to Find screen resolution
45 Write function to compare two bitmaps
46 Write a program to Add and Remove Repositories to the action
47 Write a program to Load Library files
48 Write a program to Enable and Disable Recovery scenarios programmatically
49 Write a program to Report Results status to Results file
50 Write a program to Find the active window name
51 Write a program to List out the windows that are open
52 Write a program to Call reusable actions from different script
53 Write your own standard checkpoint
54 Write your own synchronization function
55 Write a program to Check whether there is a memory leak in the process
56 Write a program to Close all the dialogs open in a window
57 Write a program to Read menu names
58 Write a program to Read menu items
59 Write a program to Check whether a check button is selected or not
60 Write a program to Check whether we can select multiple items in the list box
61 Write a program to Check whether edit box allows exactly 15 characters
62 Write a program to Check whether items in the page are aligned properly
63 Write a program to Check whether data in the web table is left aligned
64 Write a program to Find which add-ins are loaded.
65 Write a program to Find available add-ins in the tool
66 Write a program to Change window title
67 Write a program to Find whether specified window is there on the desktop
68 Write a program to Check whether a window is in minimized or maximized
69 Write a program to Check window is resizable
70 Write a program to Check whether logo displayed is correct?
71 Write a program to Read all items in a tree
72 Write a program to Read all elements in the XML file
73 Write a program to Read attributes of a particular element in the XML file
74 Write a program to Modify attribute value
75 Write a program to Add one more elements to XML file
76 Write a program to Display complete contents of an XML file
77 Write a program to Find font type.
78 Write a program to Find Font size
79 Write a program to Check whether text is bold and underlined
80 Write a program to Find the memory utilized by a process
81 Write a program to Verify flash image
82 Write a program to Check pointed link is having different back ground color?
83 Write a program to Check Marquee
84 Write a program to Check whether selected tab is having different appearance?
85 Write a program to Check whether a link contains image to its left side.
86 Write a program to Check whether stock prices are updating an hourly basis
87 Write a program to Retrieve Action Parameters
88 Write a program to Disable active screen programmatically
89 Write a program to Modify Mandatory and Assistive properties programmatically
90 Write a program to Configure Run options programmatically
91 Write a program to Define test results location through program
92 Write a program to Disable Run settings
93 Write a program to Read and Update data from user defined environmental variable
94 Write a program to Configure maximum timeout value for web page to load
95 Write a program to read and delete cookies
96 Write a program to Verify whether status indicator is moving as the movie is playing
97 Write a program to Clear the cache in the webpage
98 Write a program to Check whether webpage is loaded from server or from cache
99 Write a program to Configure web options programmatically
100 Write a program to Instruct Quick test to Capture Movie Segments of Each Error and Warning
101 Write a program to Check whether new items can be added to a list box
102 Write a program to Check whether link s pointing to correct URL
103 Write a program to invoke the application
104 Write a program to Read parameters in the data table
105 Write a program to List out the windows that are minimized
106 Write a program to add environmental variables during run time
107 Write a program to check whether tab order is left to right and top to bottom
108 Write a program to find the maximum text length that can be entered in a edit box
109 Write a program to verify min and max length constraints of text in an edit box
110 Write a program to find the kind of data edit box accepts
111 Write a program to add objects to object repository file
112 Write a program to export object repository file to XML
113 Write a program to check whether a column in the database table is a primary key
114 Write a program to display constraints of a column in the database table
Scripting Assignments:
www.gmail.com
1. Open browser with www.google.com
2. Create a script to click on first search link
3. Write a script for gmail login
4. Write a script to find how many unread mails there in Inbox
5. Create a script to check new mails
6. Create a script to read latest mail
7. Create a script to send a mail
8.Create a script to send mail with an attachment
9. Create a script to assign a label to latest mail
Note: Practice these assignments for different Email providers (Yahoo, Hotmail.etc)
Ticket Booking:
Http://www.makemytrip.com
10.Write a script to find how many flights are available from Hyderabad to Delhi?
11.Write a script to find what is the cheapest price flight from Hyderabad to Delhi?
12.write a script to find how many buses are available from Hyderabad to Bangalore?
13.write a script to find the which is the earliest bus from Hyderabad to Bangalore?
14.write a script to find 27 seat No is occupied in earliest bus?
15.write a script to count how many seats are available?
16.write a script to find how many trains are available from Hyderabad to Tirupathi?
17.write a script to find which is the earliest train after 4 pm from Hyderabad to Tirupathi ?
18.write a script to find availability of berth in any of the train from Hyderabad to Tirupathi ?
http://www.kesinenitravels.com
19. Write a script to find how many ladies tickets are booked in a Bus?
Capture text of ToolTip
Place cursor over the link
Browser ("Yahoo!").Page ("Yahoo!").Web Element ("text: =My Yahoo!").Fire Event "onmouseover"
Wait 1
Grab tool tip
ToolTip = Window ("native class: =tooltips_class32").GetROProperty ("text")
Msgbox ToolTip
*******************************************************
Reference links:
QTP Descriptive Programming - How to get number of objects on a page
http://www.softwaretestingtimes.com/2010/04/qtp-descriptive-programming-how-to-get.html
QTP Questions:
http://www.scribd.com/doc/7092347/QTP-Questions-Revised
Reference:
SQL Queries Quality Center:
wop6957.tmpMicrosoft_Office_Word_97_-_2003_Document1.doc
Interview Questions:
VB
wop6A23.tmpMicrosoft_Office_Word_97_-_2003_Document2.doc
Scripts :
wop6A34.tmpMicrosoft_Office_Word_97_-_2003_Document3.doc
VB Script Features
Category Keywords
Array handling Array, Dim, Private, Public, ReDim, IsArray, Erase, LBound, UBound
Assignments Set
Comments Comments using ' or Rem
Constants/Literals Empty, Nothing, Null, True, False
Control flow Do...Loop, For...Next, For Each...Next, If...Then...Else, Select Case, While...Wend, With
Abs, Asc, AscB, AscW, Chr, ChrB, ChrW, CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CSng, CStr,
Conversions
DateSerial, DateValue, Hex, Oct, Fix, Int, Sgn, TimeSerial, TimeValue
Date, Time, DateAdd, DateDiff, DatePart, DateSerial, DateValue, Day, Month, MonthName, Weekday,
Dates/Times
WeekdayName, Year, Hour, Minute, Second, Now, TimeSerial, TimeValue
Declarations Class, Const, Dim, Private, Public, ReDim, Function, Sub, Property Get, Property Let, Property Set
Error Handling On Error, Err
Expressions Eval, Execute, RegExp, Replace, Test
Formatting Strings FormatCurrency, FormatDateTime, FormatNumber, FormatPercent
Input/Output InputBox, LoadPicture, MsgBox
Literals Empty, FALSE, Nothing, Null, TRUE
Math Atn, Cos, Sin, Tan, Exp, Log, Sqr, Randomize, Rnd
Miscellaneous Eval Function, Execute Statement, RGB Function
Objects CreateObject, Err Object, GetObject, RegExp
Addition (+), Subtraction (-), Exponentiation (^), Modulus arithmetic (Mod), Multiplication (*),
Division (/), Integer Division (\), Negation (-), String concatenation (&), Equality (=), Inequality (<>),
Operators
Less Than (<), Less Than or Equal To (<=), Greater Than (>), Greater Than or Equal To (>=), Is, And,
Or, Xor, Eqv, Imp
Options Option Explicit
Procedures Call, Function, Sub, Property Get, Property Let, Property Set
Rounding Abs, Int, Fix, Round, Sgn
Script Engine ID ScriptEngine, ScriptEngineBuildVersion, ScriptEngineMajorVersion, ScriptEngineMinorVersion
Asc, AscB, AscW, Chr, ChrB, ChrW, Filter, InStr, InStrB, InStrRev, Join, Len, LenB, LCase, UCase,
Strings Left, LeftB, Mid, MidB, Right, RightB, Replace, Space, Split, StrComp, String, StrReverse, LTrim,
RTrim, Trim
Variants IsArray, IsDate, IsEmpty, IsNull, IsNumeric, IsObject, TypeName, VarType
Vb script Practice examples:
'####################################################
'1 Print Hello World
Print "Hello World"
'####################################################
'2 Find whether given number is a odd number
Dim oNumber
oNumber=4
If oNumber mod 2 <>0 Then
Print "The Number "& oNumber &" is an Odd Number"
else
Print "The Number "& oNumber &" is not an Odd Number"
End If
'####################################################
'3 Print odd numbers between given range of numbers
Dim RangeStart
Dim RangeEnd
Dim iCounter
RangeStart=10
RangeEnd=20
For iCounter=RangeStart to RangeEnd
If iCounter mod 2 <>0 Then
Print oNumber
End If
Next
'####################################################
'4 Find the factorial of a given number
Dim oNumber
Dim iCounter
Dim fValue
oNumber=6
fValue=1
For iCounter=oNumber to 1 step-1
fValue=fValue*iCounter
Next
print fValue
'####################################################
'5 Find the factors of a given number
Dim oNumber
Dim iCounter
oNumber=10
For iCounter=1 to oNumber/2
If oNumber mod iCounter=0 Then
print iCounter
End If
Next
print oNumber
'####################################################
'6 Print prime numbers between given range of numbers
Dim RangeStart
Dim RangeEnd
Dim iCounter
RangeStart=1
RangeEnd=30
For iCounter=RangeStart to RangeEnd
For iCount=2 to round(iCounter/2)
If iCounter mod iCount=0 Then
Exit for
End If
Next
If iCount=round(iCounter/2)+1 or iCounter=1 Then
print iCounter
End If
Next
'####################################################
7 Swap 2 numbers with out a temporary variable
Dim oNum1
Dim oNum2
oNum1=1055
oNum2=155
oNum1=oNum1-oNum2
oNum2=oNum1+oNum2
oNum1=oNum2-oNum1
print oNum1
print oNum2
'####################################################
8 Write a program to Perform specified Arithmetic Operation on two given numbers
Dim oNum1
Dim oNum2
Dim oValue
oNum1=10
oNum2=20
OperationtoPerform="div"
Select Case lcase(OperationtoPerform)
Case "add"
oValue=oNum1+oNum2
Case "sub"
oValue=oNum1-oNum2
Case "mul"
oValue=oNum1*oNum2
Case "div"
oValue=oNum1/ oNum2
End Select
print oValue
'####################################################
9 Find the length of a given string
Dim oStr
Dim oLength
oStr="sudhakar"
oLength=len(oStr)
print oLength
'####################################################
10 Reverse given string
Dim oStr
Dim oLength
Dim oChar
Dim iCounter
oStr="sudhakar"
oLength=len(oStr)
For iCounter=oLength to 1 step-1
oChar=oChar&mid(oStr,iCounter,1)
Next
print oChar
'####################################################
11 Find how many alpha characters present in a string.
Dim oStr
Dim oLength
Dim oChar
Dim iCounter
oStr="su1h2kar"
oLength=len(oStr)
oAlphacounter=0
For iCounter=1 to oLength
If not isnumeric (mid(oStr,iCounter,1)) then
oAlphacounter=oAlphacounter+1
End if
Next
print oAlphacounter
'####################################################
12 Find occurrences of a specific character in a string
Dim oStr
Dim oArray
Dim ochr
oStr="sudhakar"
ochr="a"
oArray=split(oStr,ochr)
print ubound(oArray)
'####################################################
13 Replace space with tab in between the words of a string.
Dim oStr
Dim fStr
oStr="Quick Test Professional"
fStr=replace(oStr," ",vbtab)
print fStr
'####################################################
14 Write a program to return ASCII value of a given character
Dim ochr
Dim aVal
ochr="A"
aVal=asc(ochr)
print aVal
'####################################################
15 Write a program to return character corresponding to the given ASCII value
Dim ochr
Dim aVal
aVal=65
oChr=chr(aVal)
print oChr
'####################################################
16 Convert string to Upper Case
Dim oStr
Dim uStr
oStr="QuickTest Professional"
uStr=ucase(oStr)
print uStr
'####################################################
17 Convert string to lower case
Dim oStr
Dim lStr
oStr="QuickTest Professional"
lStr=lcase(oStr)
print lStr
'####################################################
18 Write a program to Replace a word in a string with another word
Dim oStr
Dim oWord1
Dim oWord2
Dim fStr
oStr="Mercury Quick Test Professional"
oWord1="Mercury"
oWord2="HP"
fStr=replace(oStr,oWord1,oWord2)
print fStr
'####################################################
19 Check whether the string is a POLYNDROM
Dim oStr
oStr="bob"
fStr=StrReverse(oStr)
If oStr=fStr Then
Print "The Given String "&oStr&" is a Palindrome"
else
Print "The Given String "&oStr&" is not a Palindrome"
End If
'####################################################
20 Verify whether given two strings are equal
Dim oStr1
Dim ostr2
oStr1="qtp"
oStr2="qtp"
If oStr1=oStr2 Then
Print "The Given Strings are Equal"
else
Print "The Given Strings are not Equal"
End If
'####################################################
21 Print all values from an Array
Dim oArray
Dim oCounter
oArray=array(1,2,3,4,"qtp","Testing")
For oCounter=lbound(oArray) to ubound(oArray)
print oArray(oCounter)
Next
'####################################################
22 Sort Array elements
Dim oArray
Dim oCounter1
Dim oCounter2
Dim tmp
oArray=array(8,3,4,2,7,1,6,9,5,0)
For oCounter1=lbound(oArray) to ubound(oArray)
For oCounter2=lbound(oArray) to ubound(oArray)-1
If oArray(oCounter2)>oArray(oCounter2+1) Then
tmp=oArray(oCounter2)
oArray(oCounter2)=oArray(oCounter2+1)
oArray(oCounter2+1)=tmp
End If
Next
Next
For oCounter1=lbound(oArray) to ubound(oArray)
print oArray(oCounter1)
Next
'####################################################
23 Add two 2X2 matrices
Dim oArray1(1,1)
Dim oArray2(1,1)
Dim tArray(1,1)
oArray1(0,0)=8
oArray1(0,1)=9
oArray1(1,0)=5
oArray1(1,1)=-1
oArray2(0,0)=-2
oArray2(0,1)=3
oArray2(1,0)=4
oArray2(1,1)=0
tArray(0,0)=oArray1(0,0)+ oArray2(0,0)
tArray(0,1)=oArray1(0,1)+oArray2(0,1)
tArray(1,0)=oArray1(1,0)+oArray2(1,0)
tArray(1,1)=oArray1(1,1)+oArray2(1,1)
'####################################################
24 Multiply Two Matrices of size 2X2
Dim oArray1(1,1)
Dim oArray2(1,1)
Dim tArray(1,1)
oArray1(0,0)=8
oArray1(0,1)=9
oArray1(1,0)=5
oArray1(1,1)=-1
oArray2(0,0)=-2
oArray2(0,1)=3
oArray2(1,0)=4
oArray2(1,1)=0
tArray(0,0)=oArray1(0,0)* oArray2(0,0)+ oArray1(0,1)* oArray2(1,0)
tArray(0,1)=oArray1(0,0)* oArray2(0,1)+ oArray1(0,1)* oArray2(1,1)
tArray(1,0)=oArray1(1,0)* oArray2(0,0)+ oArray1(1,1)* oArray2(1,0)
tArray(1,1)=oArray1(1,0)* oArray2(0,1)+ oArray1(1,1)* oArray2(1,1)
'####################################################
25 Convert a String in to an array
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr)
For iCounter=0 to ubound(StrArray)
print StrArray(iCounter)
Next
'####################################################
26 Convert a String in to an array using i as delimiter
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr,"i")
For iCounter=0 to ubound(StrArray)
print StrArray(iCounter)
Next
'####################################################
27 Find number of words in string
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr," ")
print "Theere are "&ubound(StrArray)+1&" words in the string"
'####################################################
28 Write a program to reverse the words of a given string.
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr," ")
For iCounter=0 to ubound(StrArray)
print strreverse(StrArray(iCounter))
Next
'####################################################
29 Print the data as a Pascal triangle
'The formulae for pascal triangle is nCr=n!/(n-r)!*r!
Dim PascalTriangleRows
Dim nCr
Dim NumCount
Dim RowCount
PascalTriangleRows = 10
For NumCount = 0 To PascalTriangleRows
toPrint= Space(PascalTriangleRows - NumCount)
For RowCount = 0 To NumCount
If (NumCount = RowCount) Then
nCr = 1
Else
nCr = Factorial(NumCount) / (Factorial(NumCount - RowCount) * Factorial(RowCount))
End If
toPrint=toPrint&nCr&" "
Next
print toPrint
Next
Function Factorial(num)
Dim iCounter
Factorial = 1
If num <> 0 Then
For iCounter = 2 To num
Factorial = Factorial * iCounter
Next
End If
End Function
'####################################################
30 Join elements of an array as a string
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr," ")
print join(StrArray," ")
'####################################################
31 Trim a given string from both sides
Dim oStr
oStr=" QTP "
print trim(oStr)
'####################################################
32 Write a program to insert 100values and to delete 50 values from an array
Dim oArray()
Dim iCounter
ReDim oArray(100)
For iCounter=0 to ubound(oArray)
oArray(iCounter)=iCounter
'Print total 100 Values
print(oArray(iCounter))
Next
print "******************************"
print "******************************"
ReDim preserve oArray(50)
For iCounter=0 to ubound(oArray)
'Print Values after deleting 50 values
print(oArray(iCounter))
Next
'####################################################
33 Write a program to force the declaration of variables
Option explicit ' this keyword will enforce us to declare variables
Dim x
x=10
'Here we get an error because i have not declared y,z
y=20
z=x+y
print z
'####################################################
34 Write a program to raise an error and print the error number.
On Error Resume Next
Err.Raise 6 ' Raise an overflow error.
print ("Error # " & CStr(Err.Number) & " " & Err.Description)
'####################################################
35 Finding whether a variable is an Array
Dim oArray()
if isarray(oArray) then
print "the given variable is an array"
else
print "the given variable is not an array"
End if
'####################################################
36 Write a program to list the Timezone offset from GMT
Dim objWMIService
Dim colTimeZone
Dim objTimeZone
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colTimeZone = objWMIService.ExecQuery("Select * from Win32_TimeZone")
For Each objTimeZone in colTimeZone
print "Offset: "& objTimeZone.Bias
Next
'####################################################
37 Retrieving Time Zone Information for a Computer
Dim objWMIService
Dim colTimeZone
Dim objTimeZone
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colTimeZone = objWMIService.ExecQuery("Select * from Win32_TimeZone")
For Each objItem in colTimeZone
print "Bias: " & objItem.Bias
print "Caption: " & objItem.Caption
print "Daylight Bias: " & objItem.DaylightBias
print "Daylight Day: " & objItem.DaylightDay
print "Daylight Day Of Week: " & objItem.DaylightDayOfWeek
print "Daylight Hour: " & objItem.DaylightHour
print "Daylight Millisecond: " & objItem.DaylightMillisecond
print "Daylight Minute: " & objItem.DaylightMinute
print "Daylight Month: " & objItem.DaylightMonth
print "Daylight Name: " & objItem.DaylightName
print "Daylight Second: " & objItem.DaylightSecond
print "Daylight Year: " & objItem.DaylightYear
print "Description: " & objItem.Description
print "Setting ID: " & objItem.SettingID
print "Standard Bias: " & objItem.StandardBias
print "Standard Day: " & objItem.StandardDay
print "Standard Day Of Week: " & objItem.StandardDayOfWeek
print "Standard Hour: " & objItem.StandardHour
print "Standard Millisecond: " & objItem.StandardMillisecond
print "Standard Minute: " & objItem.StandardMinute
print "Standard Month: " & objItem.StandardMonth
print "Standard Name: " & objItem.StandardName
print "Standard Second: " & objItem.StandardSecond
print "Standard Year: " & objItem.StandardYear
Next
'####################################################
38 Write a program to Convert an expression to a date
Dim StrDate
Dim actualDate
Dim StrTime
Dim actualTime
StrDate = "October 19, 1962" ' Define date.
actualDate = CDate(StrDate) ' Convert to Date data type.
print actualDate
StrTime = "4:35:47 PM" ' Define time.
actualTime = CDate(StrTime) ' Convert to Date data type.
print actualTime
'####################################################
39 Display current date and Time
print now
'####################################################
40 Find difference between two dates.
'Date difference in Years
print DateDiff("yyyy","12/31/2002",Date)
'Date difference in Months
print DateDiff("m","12/31/2002",Date)
'Date difference in Days
print DateDiff("d","12/31/2002",Date)
'####################################################
41 Add time interval to a date
print DateAdd("m", 1, "31-Jan-95")
'####################################################
42 Print current day of the week
Print day(date)
'####################################################
43 Find whether current month is a long month
Dim oCurrentMonth
Dim ocurrentYear
Dim oDaysinMonths
oCurrentMonth = Month(date)
ocurrentYear = Year(date)
oDaysinMonths=Day(DateSerial(ocurrentYear, oCurrentMonth + 1, 0))
print oDaysinMonths&" Days in Current Month"
If oDaysinMonths=31 Then
print "Current Month is a long month"
else
print "Current Month is not a long month"
End If
'####################################################
44 Find whether given year is a leap year
'1st Method
'The rules for leap year:
'1. Leap Year is divisible by 4 (This is mandotory Rule)
'2. Leap Year is not divisible by 100 (Optional)
'3. Leap Year divisble by 400 (Optional)
Dim oYear
oYear=1996
If ((oYear Mod 4 = 0) And (oYear Mod 100 <> 0) Or (oYear Mod 400 = 0)) then
print "Year "&oYear&" is a Leap Year"
else
print "Year "&oYear&" is not a Leap Year"
End If
'45. 2nd Method
' Checking 29 days for February month in specified year
Dim oYear
Dim tmpDate
oYear=1996
tmpDate = "1/31/" & oYear
DaysinFebMonth = DateAdd("m", 1, tmpDate)
If day(DaysinFebMonth )=29 then
print "Year "&oYear&" is a Leap Year"
else
print "Year "&oYear&" is not a Leap Year"
End If
'####################################################
46 Format Number to specified decimal places
Dim oNum
Dim DecimaPlacestobeFormat
oNum = 3.14159
DecimaPlacestobeFormat=2
print Round(oNum , DecimaPlacestobeFormat)
'####################################################
47 Write a program to Generate a Random Numbers
'This script will generate random numbers between 10 and 20
Dim rStartRange
Dim rEndRange
rStartRange=10
rEndRange=20
For iCounter=1 to 10
print Int((rEndRange - rStartRange + 1) * Rnd + rStartRange)
Next
'####################################################
48 Write a program to show difference between Fix and Int
'Both Int and Fix remove the fractional part of number and return the resulting integer value.
'The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than o
r equal to number,
'whereas Fix returns the first negative integer greater than or equal to number.
'For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.
print Int(99.8) ' Returns 99.
print Fix(99.2) ' Returns 99.
print Int(-99.8) ' Returns -100.
print Fix(-99.8) ' Returns -99.
print Int(-99.2) ' Returns -100.
print Fix(-99.2) ' Returns -99.
'####################################################
49 Write a program to find subtype of a variable
Dim oVar
Dim oDatatypes
oVar="QTP"
oVartype=Typename(oVar)
print oVartype
'####################################################
50 Write a program to print the decimal part of a given number
Dim oNum
oNum=3.123
oDecNum=oNum- int(oNum)
print oDecNum
'####################################################
Write a Script in QTP to count the unread emails of a gmail account.
'You need to be logged into the Gmail account
Browser("title:=Gmail.*").Page("title:=Gmail.*").Link("innertext:=Inbox.*").Click
Browser("title:=Gmail.*").Page("title:=Gmail.*").Sync
'To get the innertext of inbox link
inboxcount =
Browser("title:=Gmail.*").Page("title:=Gmail.*").Link("innertext:=Inbox.*").getroproperty("innertext")
If inboxcount = "Inbox" Then
Print "No Unread Emails."
ExitAction
Else
emailcount = replace(inboxcount, "Inbox","") 'replaces inbox with space
emailcount = Rtrim(ltrim(emailcount)) 'removes all the spaces
emailcount = replace(emailcount, "(","")
emailcount = replace(emailcount, ")","")
Print "You have "&emailcount& " unread emails in your inbox."
End If
Sort Values in an Array:
*******************************************
Dim a
A=Array(4,2,6,8,1)
For i=0 to Ubound(1)-1
Min =i
For j=i=1 to Ubound(a)
If a(j)<a(min) then
Min=j
End if
Next
If i<> min then
S=a(i)
a(i)=a(min)
a(min)=s
end if
************************************************
Script to login ,Check the first mail and delete logout close
Systemutil.run www.yahoomail.com
With browser(creation time:=0).Page(micclass:=Page)
.webedit(Name:=Login).setmindqtest
.webedit(name:=password).setmindq12345
.webbutton(name:=signin).click
.webcheckbox(index:=1).click
.webbutton(Name:=delete,index:=0).click
End with
Browser(creation time:=0).close
Get the List of links in google webpage and check spelling check:
Dim d
Dim mw
Set d=description.create()
D(micclass).value=link
Set mw=createobject(word.application)
Set I =browser(google).Page(google).childobjects(d)
For i=0 to I.count-1
S=I(i).getRoProperty(Innertext)
Mw.wordbasic.filenew
Mw.wordbasic.insert s
If MW .activedocument.spellingerrors.count>0 then
Reporter.reportevent 1,spelling,spelling is error:&S
Next
Mw.quit
Set mw.nothing
Purpose: Delete a mail
Description: Delete a mail and check the mail
Author:Vijay
Dim Prvmail ,aftermails
Browser (yahoo).Page (Inbox).link (Inbox).click
Wait(5)
Prvmail=Fn_countmails
Browser(yahoo).Page(Inbox).webcheckbox(mid).set ON
Browser(Yahoo).Page(Inbox).webbutton(Delete).click
Wait(5)
Aftermails=Fn_countmails
If cint(aftermails)=prvmail.-1 then
Reporter.reportevent 0,maildelete,The mail Is deleted
Else
Reporter.reportevent 1,Mail delete,The mail is not deleted
End if
Function Fn_Countmails
Dim msg ,n
Msg=browser(yahoo).Page(Inbox).webelement(Mailcount).
getROproperty(Innertext)
n=split(msg, )
fn_countmails=n(Ubound(n))
end function
******************************************************************8
Send XML request to a webservice and receive response
Set Req XML =XMLutil.createXML from file(d:\f1:xml)
StrXML=reqXML.Tostring()
Webservice(Convert Temparature Service).send requestConvert temp,strXML
X=webservice(convert Temparature Service)last response
Msgbox x
******************************************************************
Compare 2 Bit Maps:
F1=e:\b1.bmp
F2=e:\b2.bmp
Set bc=createobject(Mercury.filecompare)
If bc.isequalbin(F1,F2,0,1)then
Msgbox(they are the same)
Else
Msgbox(they are not same)
End if
Set bc=nothing