Beruflich Dokumente
Kultur Dokumente
00
Visit:
www.pavanworld.net
for QTP Scripts and Documents
www.pavanworld.net 1
I) Basic features of QTP
www.pavanworld.net 2
Version History of QTP
Add-In Manager
QTP supports almost all industry leading technologies, but by default it does not
support, with respect to add in license it supports.
• Activex
• Visual basic
• Web.
Other available Add Ins are: .NET, Java, People soft, Siebel, TE (Terminal
Emulators), SAP for GUI, Sap for Web, Oracle Apps, Web Services etc.
During QTP launching it shows Add in manger dialog box, Add in Manger lists out all
available Add Ins in the company.
User needs to select appropriate Add Ins for his application or AUT.
One can select more than one Add Ins also; if we select unnecessary Add Ins QTP
performance will be reduced.
www.pavanworld.net 3
Launching QTP
We can launch QTP BY selecting desktop icon otherwise start > programs> QTP
Professional > QTP.
www.pavanworld.net 4
II) Key Elements of QTP Tool Window
1) Test Pane:
It is programming interface of QTP, used for creating, editing, viewing and deleting
test scripts.
www.pavanworld.net 5
Test: It is a set of statements or set of one or more actions. (It is a local concept)
www.pavanworld.net 6
QTP Test Pane-Keyword View
Note1: Here in test pane Test is same but views are different, if you perform any
modifications in one view those automatically reflects in another view.
Note 2: Technical users use expert view and business user use key word view.
Navigation: Tools Menu> view options> we can use font size and colors etc.
2) Active Screen
It has an optional element of QTP, it takes snap shots of every statement that user
performed action or operation on AUT.
www.pavanworld.net 7
It can be used for understanding and editing the test easily.
Note 1: Generally novice testers use this feature but it occupies lot of memory space
on QTP.
Active Screen
www.pavanworld.net 8
3) Data Table
It has an integrated spread sheet (Excel like), used for Data driven testing.
Navigation: View menu>Data table (for launching and closing)
Data driven Testing: Testing the same task(S) or same operation with multiple sets
of test data.
It can be used in two ways.
1. Global Sheet- for entire test /used for all actions in the test.
2. Action Sheets- for specific action only.
QTP has Data table methods for performing operations on data table.
www.pavanworld.net 9
QTP Tool window- Data Table
4) Debug Viewer
We use step into, step over and step out commands for debugging. (debug
commands)
www.pavanworld.net 10
Through Debug viewer user can watch variables and change values of variables
temporarily.
5) Missing Resources
It can be used for showing missing resources those attached to current test such as
(recovery scenarios, library files etc).
www.pavanworld.net 11
Navigation: View menu >missing resources (for launching and closing)
6) Information
This pane shows syntax errors automatically during saving the test.
7) QTP Commands
www.pavanworld.net 12
1. Menu options
2. Tool Bar options
3. Short cut keys (for Some important operations only)
File menu: Through file menu user can create, save tests, open existing tests,
export tests in zip format.
Edit Menu: It provides editing options and renaming, deleting and splitting actions.
View menu: Through this menu we can launch and close, active screen, Data Table,
Debug viewer, information, missing resources etc.
Insert Menu: Through this menu user can inserting check points, out put values,
synchronizing points.
In this menu step generator available, using this user can generate recordable and
non-recordable scripts.
Through insert menu user can insert VB Script conditional and loop statements and
transaction points (Start and End).
www.pavanworld.net 13
Through insert menu user can create new actions, call existing actions and copy
existing actions.
Automation Menu:
This menu provides Record, Run options and Run setting options
Through this menu we can start normal recording, analog recording and Low level
recording.
Through this menu we can stop recoding, running and also we run tests.
Resources Menu:
This menu provides object repository and recovery scenarios options.
Through this menu we can create /modify/delete objects information and we can
associate repositories.
Through this menu we can create, modify and delete recovery scenarios.
Debug Menu:
This menu provides debug commands for step by step execution.
Through this menu we can insert/remove/break points.
Tools Menu:
This menu provides Tools settings option, view options and object identification
configuration.
Through this menu we can set tool options as well as test pane view options.
In this menu object spy option available, through this we can get object’s
information.(Properties and values)
In this menu Virtual object option available; through this option we can create virtual
objects.
Window Menu:
This menu provides QTP tool window style settings.
Help Menu:
This menu provides QTP help as well as VB Script help.
Through this menu we can contact technical support people and we can send
feedback.
Through this menu we can check for updates and download or install directly.
www.pavanworld.net 14
III) QTP Testing Process
Planning
o Analyzing the AUT
o Generating/Selecting Test cases for Automation
o Collecting Test Data
o Automation Framework Implementation
o QTP Tool Settings Configuration
Generating Tests
o Recording
o Keyword driven methodology
o Descriptive Programming
Enhancing Tests
o Inserting Checkpoints
o Inserting Output values
o Adding Comments
o Synchronization
o Parameterization
o Inserting Flow Control Statements
o Calling Functions/Actions
o Generating Steps though Step Generator
o Inserting Transaction Points
o Using Regular Expressions
o Using Environment Variables
Debugging Tests
o Debug Commands & Break Points
o Step by step execution
o Watching Variables
o Changing values of variables
Running Tests
o Normal Execution
o Batch Execution
o AOM Scripting
www.pavanworld.net 15
o Tests Running through framework
o Scheduled Execution
Analyzing Results
o QTP Result window
o Defining our own Results
o Exporting Results
o Deleting Results
Reporting Defects
o Manual Defect Reporting
o Tool based Defect Reporting
o Working with Quality Center
Before we begin creating a test, we need to analyze our application and determine
our testing needs.
Then determine the functionality that we want to test. To do this, consider the
various activities that customers perform in our application to accomplish specific
tasks. Which objects and operations are relevant for the set of business processes
that need to be tested? Which operations require customized keywords to provide
additional functionality?
While we are thinking about the business processes we want to test, consider how
we can divide these processes into smaller units, which will be represented by our
test's actions. Each action should emulate an activity that a customer might perform
when using your application.
As we plan, try to keep the amount of steps we plan to include in each action to a
minimum. Creating small, modular actions helps make our tests easier to read,
follow, and maintain.
www.pavanworld.net 16
Recording and Running:
1. Normal Recording
It records User Mouse and Keyboard operations on AUT with respect to objects, but
unable to record continuous mouse operations like Digital Signatures, graphs, paints
etc.
Navigation: Automation>Record
Or
Select Record option on automation toolbar
Or
Use short cut key (F3)
5. Click OK
6. Perform actions on AUT
7. Stop recording.
8. Save the Test
2. Analog Recording:
It records the exact mouse and keyboard operations. We can use this mode for
recording continuous mouse operations. It is not useful for recording normal
operations why because it does not generate steps for each operation, generates
total user actions in a Track File. The Track file is not editable.
Navigation:
www.pavanworld.net 17
2. Automation >Analog Recording
OR
Use Short cut Key (Shift + ALT+F3)
If we select first option QTP records User operations with respect to Desktop co-
ordinates.
If we select Second option, we have to show the window (AUT), after showing
the Window it records with respect to that window co-ordinates.)
5. Select any one option in the dialog box and click Start Analog record.
6. It records User actions
7. Stop Recording
This mode records at the object level and records all run time objects as window or
winobject Test objects.
Use Low Level Recording for recording in an environment not recognized by QTP.
Navigation:
1. Keep tool under recording mode
2. Automation >Low Level Recording
www.pavanworld.net 18
Object Repository
Object Repository:
It is a storage place of QTP where we can store the objects information and it also
acts as interface between the test script and the AUT in order to identify the
objects during execution.
Object:
Software objects:
We call windows, WebPages, buttons, edit boxes, check boxes etc.. as software
objects.
Run time objects: The objects present in the AUT. Ex: Buttons, links, etc…
Test Objects: References of Run time objects. Ex: WinEdit, WinButton, WebButton,
Link, etc…
Note:
Test objects names vary from one environment to another.
Ex:
Run time objects Test objects in Test objects in VB Test objects in
windows Environment web Environment
Environment
buttons WinButton VBButton WebButton
Edit box WinEdit VBEdit WebEdit
Check box Wincheckbox Vbcheckbox Webcheckbox
Utility objects
They are QTP reserved objects used for testing and result reporting.
Ex:
1. SystemUtil for launching/closing the application.
2. Reporter for defining results.
www.pavanworld.net 19
3. Services for inserting transaction points
4. Environment for using environment variables
User can create objects; those can be used for performing specific operations. Ex:
Creating objects in file system object class, adodb.connection class, dictionary object
class, excel. Application class etc.
Local Repository:
QTP creates a Local Repository for every action automatically during Recording.
That cannot be shared among tests.
www.pavanworld.net 20
QTP- Local Repository
Shared Repository:
User (Test Engineer) creates shared repository by adding objects. That can be
shared among number of tests.
Using this method user can perform modifications on objects easily.
Adding objects
a. Local Repository:
B. Shared Repository:
www.pavanworld.net 21
o Selected object only
o Default object types
o All objects types
o Selected object types
(If we select first option it stores Selected objects only, if we select second option it
stores all default objects, if we select third option it stores All objects including static
objects, if we select fourth option, we have to select object classes then it stores
that class objects, we can select more than one class also.)
Renaming objects
a. Local Repository:
Resources > object repository >select object and right click >choose rename option
>modify the name>release the mouse.>close repository
b. Shared Repository:
Deleting objects
a. Local Repository:
Resources > object repository >select object and right click >choose delete option
>confirm deletion>. >close repository
b. Shared Repository:
Merging Repositories
Note: After merging also, source repository files will be available, if we do not want
source files we can delete.
www.pavanworld.net 22
Defining new test objects
Note: This feature can be used for preparing tests before the AUT is ready.
Spying objects
For getting objects information, (Test objects names, property & Values) QTP is
providing a feature called Object Spy, using this we can get objects information.
View Options
Locate in Repository
This feature can be used for identifying objects from application to repository.
Navigation: View>Locate in repository >show the object>click Ok>it locates
specified object in the repository.
Highlight in Application
This feature can be used for identifying objects from repository to application.
Navigation: Select object in the repository >view>highlight in application>it
highlights specified objects in the application.
Navigation: File >export Test objects to XML Enter the file name and Save with xml
extension.
Navigation: File>import from XML >browse path of the XML file >it loads objects.
Note: The purpose of this feature is Editing objects information outside of the QTP
www.pavanworld.net 23
Descriptive Programming
Entering / Providing objects information directly into the test script is called
Descriptive Programming.
Advantages:
b) Scripts are portable (we can run these scripts from any machine easily)
d) We can start Test Execution process even though Application is not ready.
1. Static Programming
2. Dynamic Programming
Static Programming
In this style of script generation, we provide objects information directly into the
script.
Ex:
Invokeapplication "C:\Program Files\HP\QuickTest
Professional\samples\flight\app\flight4a.exe"
dialog("text:=Login").Activate
dialog("text:=Login").Winedit("attached text:=Agent Name:").Set "asdf"
dialog("text:=Login").Winedit("attached text:=Password:").Set "mercury"
dialog("text:=Login").Winbutton("text:=OK","width:=60").Click
Note:
1. Dialog, WinEdit and WinButton – Test Objects
2. text, attached text - Property names
3. Login, Agent Name:, Password:, OK - Property values or Logical Names of the
Object
4. Activate, Set, Setsecure, Click - Methods
Note2:
If we feel one property information is not sufficient for recognizing the object
uniquely, then we can provide more properties information by separating with
commas.
www.pavanworld.net 24
Note 3:
If we want to get objects information (Test objects, properties and values), we can
use object spy feature. This feature is available in Tools Menu, in local repository and
in repository manager.
-------------------------------------------------------------------
If we want maintain ‘Objects information’ in centralized location then we can use
Constants.
Steps:
Creating Constants:
Associate the Library file to QTP (File->Settings->Resources-> Click add (+) icon->
Browse path of the Library file->Click Apply and click Ok buttons
Syntax:
Advantages:
www.pavanworld.net 25
Dynamic Programming
Set oLogin=description.Create
Set oAgent=description.Create
Set oPassword=description.Create
Set oOk=description.Create
oLogin("text").value="Login"
oLogin("width").value=320
oLogin("height").value=204
oAgent("attached text").value="Agent Name:"
oPassword("attached text").value="Password:"
oOk("text").value="OK"
Note1: Create Description objects and put into one library file, by associating that
library file, we can generate tests.
----------------------------------------------------
In this style of script creation also, we can maintain Objects information in the
Centralized location by putting collection objects in a Library file.
----------------------------------------------------
www.pavanworld.net 26
Methods or Operations
Ex:
Dialog(“Login”).Activate
Window(“Flight Reservation”).Activate
Ex:
Window(“Flight Reservation”).Close
Browser(“Browser”).Close
Select Method:
Ex:
www.pavanworld.net 27
B. Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select
"12572
Ex:
x=Window("Flight Reservation").WinComboBox("Fly From:").GetVisibleText
msgbox x
GetRoproperty:
It returns current object property value. It can be used for getting any object’s, any
property value.
Syntax: Variable = object hierarchy.getroproperty (“property name”)
Ex: x=Window("Flight Reservation").WinEdit("Tickets:").GetROProperty ("width")
msgbox x
Navigate Method:
It opens a specified URL in the Browser.
Syntax: object hierarchy.navigate “URL”
Ex: Browser("Yahoo!").Navigate "http://www.google.co.in"
www.pavanworld.net 28
Enhancing Tests
After generating the basic test, we have to enhance the test in order to Test the AUT
with respect to requirements.
There are several methods available in QTP for enhancing the TEST.
Inserting Checkpoints
Check point is a verification point, it takes expected result from the user and
compares with actual results during execution and provides test results.
www.pavanworld.net 29
Note 2: From 9 to 11 checkpoints are hidden checkpoints, we can insert these
checkpoints through standard checkpoint.
1. Standard Checkpoint:
It checks object property values. We can use this checkpoint for checking any
property value.
Keep tool under recording mode > place cursor in desired location > Insert >
check point > Standard checkpoint > Show the object > click okay > select
property and enter expected results & click Ok and stop Recording.
Select Checkpoint statement and right click > choose checkpoint properties
option > modify the value > click Ok.
Select Checkpoint statements and right click > choose delete option.
View > Active Screen >place cursor in desired location >Place mouse pointer on
active screen & right click> choose insert standard checkpoint option > click ok >
enter expected result > click ok
Note: Inserting Standard check points through keyword view same as in expert
view.
2) Text Checkpoint:
Navigation:
Keep tool under Recording mode >Insert menu > checkpoint > Text checkpoint
> Show the object > click ok > Select options
www.pavanworld.net 30
We can select one or more options > click ok & stop Recording.
Navigation:
Keep tool under Recording mode > Insert menu> Checkpoint > Text area
checkpoint > Mark the area of text > select one or more options
4. Bitmap checkpoint:
Navigation:
Keep tool under Recording mode > Insert menu > Checkpoint > Bitmap
checkpoint > show the Bitmap >click ok >select “check only selected area”
option if we want to compare part of the bitmap > click ok >stop recording.
5. Database checkpoint:
Navigation:
Insert > checkpoint > Database checkpoint >choose “specify SQL statement
manually” option >click next > click create > select machine data source >
Select DSN (QT_flight32) > click ok > enter SQL statement (select * from
orders) > finish > click ok.
Note: here we do not need to put tool under Recording mode and we do not
need AUT since data is from backend.
Tools menu> options >web > advanced > check/uncheck items > click apply >
click ok
Invigilation:
www.pavanworld.net 31
Keep tool under recording mode with web environment
>insert>checkpoint>accessibility checkpoint>show the webpage>click ok>click
ok>stop recording.
Result Criteria:
a) If item is available but not according to W3C rules then fail.
b) If an item is available, according to W3C rules then Pass.
c) If an item is not available then result would be pass
Navigation:
Keep tool under Recording mode in web environment > insert menu >
checkpoint (from application)> show the xml pages >click ok > stop Recording.
Navigation: Insert menu > checkpoint >xml checkpoint (from resource) >
browse path of the XML File > click ok > click ok.
Note: 1. If XML file is an individual and path available, and then we can go for
inserting xml checkpoint from resource.
Note: 2. If XML file is part of web application, separate path is not available then
we can choose inserting XML checkpoints from application.
9. Page checkpoint:
Navigation:
Keep tool under Recording mode with web environment > Insert menu >
checkpoint > Standard checkpoint >show the web page > click ok > click ok >
stop recording.
Navigation:
Keep tool under Recording mode with web environment > Insert menu >
checkpoint >standard checkpoint > show the image > select image > click ok >
click ok >stop recording.
www.pavanworld.net 32
11. Table checkpoint:
Navigation: Keep tool under Recording mode under web environment > Insert
menu > checkpoint > standard checkpoint >show the web table > click ok >stop
recording.
It is a step in which one or more values are captured during test execution.
The values can later be used as input at a different point in the run session or we
can use as input for another test.
It is stored in run time data table; it is located in QTP result window and can be
retrieved later.
We can use standard output values to output the properties values of most
objects.
Navigation:
Keep tool under Recording mode > Insert menu >output value> standard output
value > show the object > click ok > select property > modify the column name
(if required) > click ok >click ok >stop recording.
www.pavanworld.net 33
2) Text output value:
We can use Text output values to output text strings displayed in an application.
When creating a text output value we can output a part of the objects text and
we can also specify text before and after options.
Navigation:
Keep tool under recording mode> Insert menu> output value > text output value
> show the text >select one of the option(output text/text before/text after) >
click modify if you want to change the column name > click ok > click ok.> check
in runtime table after running it.
We can use text area output values to output text strings displayed within a
defined area of the screen.
Navigation:
Keep tool under recording mode > insert menu >output value > text area output
value >Mark the text area >click modify the column name if necessary > click ok
> again click ok > check in run time table after running it..
We can use Database output values to output the value of the contents of
database cells.
Navigation:
Insert menu> output value > Database output value> choose specify SQL
statements manually >click next >click create >Select Machine Data source >
Select Driver (QT_flight32) > click ok > enter SQL statement (select *from
orders) > click finish > select data cells > click ok > Run and it will capture and
see the results in run time table.
we can use XML output values to output the values of XML elements in XML
documents.
Navigation: Keep tool under recording mode with web environment > Insert
menu > output value > XML output value from application > Show the XML
document > select elements > click ok >stop recording.
We can use XML output values to output the values of XML elements in XML
documents.
www.pavanworld.net 34
Navigation:
Insert menu >output value> XML output value from resource > browse path of
the XML file > click ok > select elements >click ok.
Adding Comments
Purpose of Comments:
Syntax:
Navigation: Select block of statements > Edit menu> Advanced> Comment block
Or
After selecting block of statements use shortcut key Ctrl+M
Or
After selecting comment block, Use shortcut key ctrl+shift+M
QTP adapted VB script engine for applying programming logic to tests. We can
insert VB script conditional statements and loop statements for applying the
logic.
In VB script there are 2 types of conditional statements and four types of loop
statements available.
www.pavanworld.net 35
Synchronization
It is a process of matching the speeds of both QTP and AUT in order to get proper
execution and results.
During test execution QTP gives instructions one by one with same speed, but
AUT takes less time for some operations execution and more time for some
operations execution, that time we may not get proper execution and results. In
order to get proper results in between QTP & AUT synchronization is required.
We can insert wait statements in our test in order to make QTP to wait until AUT
completes current operation.
Syntax:
Wait(time in seconds)
Note: If we insert wait statements QTP waits up to maximum time even though
operation is completed.
Place cursor in desired location>keep tool under recording mode > Insert menu
> Synchronization point > show the object > click ok > select property name &
Value (True)>enter time in Mille seconds>click ok>Stop recording.
Syntax:
object hierarchy.waitproperty “property name”,value,time in milli seconds.
www.pavanworld.net 36
Increasing Tool default synchronization time:
Note: If we increase QTP tool default time that can be applied for all statements
in the test, but QTP does not wait up to maximum time unnecessarily, After
completion of one statement execution it goes to next statement immediately.
1. Suppose in our test one or more statements only are taking more time for
execution then selecting “Inserting synchronization method” is better.
2. Suppose in our test more statements are taking more time for execution then
selecting “increasing tool time out” .
3. Above two are local features but wait statement is Vbscript feature, even
though some drawbacks are there in using wait statement, it is better to use
wait statement in functions.
Syntax:
Services.StartTransaction "name of the transaction"
-------
statements
---------
--------
services.EndTransaction "name of the transaction"
Note: We can insert multiple transactions points in a test.
www.pavanworld.net 37
Parameterization
Passing parameters, through this concept we can pass multiple values.
Data Driven Testing: Testing the Same operation with multiple sets of test
data.
Types of Parameterization:
We can use loop statements for passing sequential numbers & Logical Numbers.
For orderno=1 to 10 step 1 ' for one increment step keyword is not mandatory
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 orderno
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
Next
Through Loop Statements we can give strings also but every time user has to
enter data.
For x=1 to 3
Agent =inputbox("enter an Agent Name")
Password=inputbox("enter a password")
invokeapplication "C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe"
www.pavanworld.net 38
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set Agent
Dialog("Login").WinEdit("Agent Name:").Type micTab
Dialog("Login").WinEdit("Password:").SetSecure password
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
Next
QTP adds one data table (Spreadsheet) for every test, we can use Data Table for
Data Driven Testing.
Click on column header>enter the name of the field (like this we can
create number of columns) > Enter Data>connect the data to test
Agent = Datatable("Agent",1)
pwd=Datatable ("Password",1)
invokeapplication "C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set Agent
Dialog("Login").WinEdit("Agent Name:").Type micTab
Dialog("Login").WinEdit("Password:").SetSecure pwd
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
www.pavanworld.net 39
b. Importing test data from external files:
Open Data Table (view>Data table)>place mouse pointer on data table and right
click>file>import from file>Click ok>Browsw path of the file(it imports data from
the flat file)
Connecting Test Data to QTP Test as above and run the test.
Open Data Table (view>Data table)>place mouse pointer on data table and right
click>file>import from file>Click ok>Browse path of the excel sheet (it imports
data from the excel sheet)
Connecting Test Data to QTP Test as above and run the test.
D. Importing test data from Data bases: Through Data table we can import Test
Data from Data bases, but first we have to create /get the DSN(Data source
Name)& we have to use SQL Commands.
1. Creating a Test Database: open MS Access (or we can use any other
database).
Note: DSN Creation is one time activity, by using the DSN we can get data for
number of tests.
www.pavanworld.net 40
Environment Variables in QTP
These are global variables; if we want to use some variables globally (From number
of tests) declaring as global variables is better. If we declare as local variables in
number of tests, modifications are difficult.
1. Built in variables: These are system defined variables, we can access from all
tests but these are designed as read only.
Syntax:
Variable = Environment(“environment variable name”)
Ex:
X=Environment (“ActionName”)
Msgbox x
Example Script:
Navigation:
File > settings > Environment > select variable type as user defined > click add icon
(+) > enter variable name & Value > click ok (like this we can create number of
variables) > click export > browse path & enter file name, save with xml extension >
click ok.
Navigation:
File > settings >Environment > select variable type as user defined > check “load
variables and values from the external file” > browse path of the xml file > click
apply & ok.
www.pavanworld.net 41
Or
X=environment (“city”)
Msgbox x
www.pavanworld.net 42
Actions
Action: A Set of Statements for performing a Task or Tasks.
Purpose of Actions:
Types of Actions:
Operations on Actions:
• Creating Actions
• Splitting Actions
• Renaming Actions
• Deleting Actions
• Calling an Action
• Copying an Action
Creating an Action:
Insert>call to new action>enter name of the action>click ok
Steps:
Splitting an action:
Steps:
www.pavanworld.net 43
Note: At a time we can split one actions into 2 actions.
Renaming actions:
Select desired action in action drop down box> edit menu>action>rename
action>modify the name>click ok.
Deleting Actions:
Select desired action in action drop down box>edit menu>action>delete
action>confirm deletion.
Calling an action:
Insert>call to existing action>browse path of the test>select desired action>click ok.
Copying an action:
Insert>call to copy of action>browse path of the test>select desired action>click ok.
www.pavanworld.net 44
VB Script
(Fundamentals and Features)
1) Introduction
2) Comments
3) VB Script Variables
4) VB Script Data Types
5) VB Script Operators
6) Input/Output Operations
7) Constants
8) Conditional Statements
9) Loop through Code
10) VB Script Procedures
11) Procedures
12) VBScript syntax rules and guidelines
13) Errors
www.pavanworld.net 45
1.0 Introduction
When a VBScript is inserted into a HTML document, the Internet browser will read
the HTML and interpret the VBScript. The VBScript can be executed immediately, or
at a later event.
Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of
environments, including Web client scripting in Microsoft Internet Explorer and Web
server scripting in Microsoft Internet Information Service.
Windows Script Host is built into Microsoft Windows 98, 2000, and Millennium
Editions and higher versions.
A Windows script is a text file. We can create a script with any text editor as long as
we save our script with a WSH-compatible script extension (.js, vbs, or .wsf).
The most commonly available text editor is already installed on our computer —
Notepad. We can also use your favorite HTML editor, VbsEdit, Microsoft Visual C++,
or Visual InterDev.
1. Start Notepad.
2. Write your script. For example purposes, type Msgbox "Hello VB Script"
3. Save this text file with a .vbs extension (instead of the default .txt extension).
For example, Hello.vbs
4. Navigate to the file you just saved, and double-click it.
5. Windows Script Host invokes the VB Script engine and runs your script. In the
example, a message box is displayed with the message "Hello VB Script"
Scripts are often embedded in Web pages, either in an HTML page (on the client
side) or in an ASP page (on the server side). In the case of a script embedded in an
HTML page, the engine component that interprets and runs the script code is loaded
by the Web browser, such as Internet Explorer. In the case of a script embedded in
www.pavanworld.net 46
an ASP page, the engine that interprets and runs the script code is built into Internet
Information Services (IIS).
Windows Script Host executes scripts that exist outside an HTML or ASP page and
that stand on their own as text files.
Generally, we write scripts in either Microsoft JScript or VBScript, the two script
engines that ship with Microsoft Windows 98, 2000 and Millennium Editions. We can
use other script engines, such as Perl, REXX, and Python, with Windows Script Host.
A stand-alone script written in JScript has the .js extension; a stand-alone script
written in VBScript has the .vbs extension. These extensions are registered with
Windows. When we run one of these types of files, Windows starts Windows Script
Host, which invokes the associated script engine to interpret and run the file.
www.pavanworld.net 47
2.0 Comments
2.1 Syntax
o Select block of statement and use short cut key Ctrl + M (for comment)
o Select comment block and use short cut key Ctrl + Shift + M (for
uncomment)
www.pavanworld.net 48
3.0 VB Script Variables
A variable is a convenient placeholder that refers to a computer memory location
where we can store program information that may change during the time our script
is running.
We declare variables explicitly in our script using the Dim statement, the Public
statement, and the Private statement.
For example:
Dim city
Dim x
We declare multiple variables by separating each variable name with a comma. For
example:
We can also declare a variable implicitly by simply using its name in our script. That
is not generally a good practice because we could misspell the variable name in one
or more places, causing unexpected results when our script is run. For that reason,
the Option Explicit statement is available to require explicit declaration of all
variables.
The Option Explicit statement should be the first statement in our script.
Variable names follow the standard rules for naming anything in VBScript. A variable
name:
www.pavanworld.net 49
3.4 Scope of Variables
The variable is on the left side of the expression and the value you want to assign to
the variable is on the right.
For example:
B = 200
City = “Hyderabad”
Example:
Dim A(3)
Although the number shown in the parentheses is 3, all arrays in VBScript are zero-
based, so this array actually contains 4 elements.
We assign data to each of the elements of the array using an index into the array.
Beginning at zero and ending at 10, data can be assigned to the elements of an
array as follows:
A(0) = 256
A(1) = 324
www.pavanworld.net 50
A(2) = 100
A(3) = 55
Similarly, the data can be retrieved from any element using an index into the
particular array element you want.
For example:
SomeVariable = A(4)
Arrays aren't limited to a single dimension. You can have as many as 60 dimensions,
although most people can't comprehend more than three or four dimensions.
Arrays aren't limited to a single dimension. We can have as many as 60 dimensions,
although most people can't comprehend more than three or four dimensions.
In a two-dimensional array, the first number is always the number of rows; the
second number is the number of columns.
We can also declare an array whose size changes during the time our script is
running. This is called a dynamic array.
The array is initially declared within a procedure using either the Dim statement or
using the ReDim statement.
However, for a dynamic array, no size or number of dimensions is placed inside the
parentheses.
For example:
Dim MyArray()
ReDim AnotherArray()
To use a dynamic array, you must subsequently use ReDim to determine the
number of dimensions and the size of each dimension.
In the following example, ReDim sets the initial size of the dynamic array to 25. A
subsequent ReDim statement resizes the array to 30, but uses the Preserve
keyword to preserve the contents of the array as the resizing takes place.
www.pavanworld.net 51
ReDim MyArray(25)
There is no limit to the number of times we can resize a dynamic array, although if
we make an array smaller, we lose the data in the eliminated elements.
VBScript has only one data type called a Variant. A Variant is a special kind of data
type that can contain different kinds of information, depending on how it is used.
Because Variant is the only data type in VBScript, it is also the data type returned
by all functions in VBScript.
Beyond the simple numeric or string classifications, a Variant can make further
distinctions about the specific nature of numeric information. For example, we can
have numeric information that represents a date or a time. When used with other
date or time data, the result is always expressed as a date or a time. We can also
have a rich variety of numeric information ranging in size from Boolean values to
huge floating-point numbers. These different categories of information that can be
contained in a Variant are called subtypes. Most of the time, we can just put the
kind of data we want in a Variant, and the Variant behaves in a way that is most
appropriate for the data it contains.
The following table shows subtypes of data that a Variant can contain.
Subtype Description
Empty Variant is uninitialized. Value is 0 for numeric variables or a zero-
length string ("") for string variables.
Null Variant intentionally contains no valid data.
Boolean Contains either True or False.
Byte Contains integer in the range 0 to 255.
Integer Contains integer in the range -32,768 to 32,767.
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long Contains integer in the range -2,147,483,648 to 2,147,483,647.
Single Contains a single-precision, floating-point number in the range
-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45
to 3.402823E38 for positive values.
Double Contains a double-precision, floating-point number in the range
-1.79769313486232E308 to -4.94065645841247E-324 for negative
values; 4.94065645841247E-324 to 1.79769313486232E308 for
positive values.
Date (Time) Contains a number that represents a date between January 1, 100
to December 31, 9999.
String Contains a variable-length string that can be up to approximately 2
billion characters in length.
www.pavanworld.net 52
Object Contains an object.
Error Contains an error number.
We can use conversion functions to convert data from one subtype to another. In
addition, the VarType function returns information about how your data is stored
within a Variant.
Operators are used for performing mathematical, comparison and logical operations.
When several operations occur in an expression, each part is evaluated and resolved
in a predetermined order called operator precedence.
We can use parentheses to override the order of precedence and force some parts of
an expression to be evaluated before others.
Operations within parentheses are always performed before those outside. Within
parentheses, however, standard operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic
operators are evaluated first, comparison operators are evaluated next, and logical
operators are evaluated last.
Comparison operators all have equal precedence; that is, they are evaluated in the
left-to-right order in which they appear.
Arithmetic and logical operators are evaluated in the following order of precedence.
Operator Description
1) Exponentiation Operator (^) Raises a number to the power of an exponent.
2) Multiplication Operator (*) Multiplies two numbers.
3) Division Operator (/) Divides two numbers and returns a floating-point result.
4) Integer Division Operator (\) Divides two numbers and returns an integer result.
5) Mod Operator Divides two numbers and returns only the remainder.
www.pavanworld.net 53
6) Addition Operator (+) Sums two numbers.
7) Subtraction Operator (-) Finds the difference between two numbers or indicates the
negative value of a numeric expression.
8) Concatenation Operator (&) Forces string concatenation of two expressions.
Operator Description
1) Addition Operator Sums two numbers.
(+)
If Then
1) Both expressions are numeric Add.
2) Both expressions are strings Concatenate.
3) One expression is numeric and Add.
the other is a string
2) Concatenation Forces string concatenation of two expressions.
Operator (&)
www.pavanworld.net 54
6) Input/Output Operations
6.1 InputBox Function
Displays a prompt in a dialog box, waits for the user to input text or click a button,
and returns the contents of the text box.
Example:
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)
Displays a message in a dialog box, waits for the user to click a button, and returns a
value indicating which button the user clicked.
Example:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
' MyVar contains either 1 or 2, depending on which button is clicked.
7) VB Script Constants
A constant is a meaningful name that takes the place of a number or string and
never changes.
We create user-defined constants in VBScript using the Const statement. Using the
Const statement, we can create string or numeric constants with meaningful names
and assign them literal values.
Const statement
Example:
Represent Date literals and time literals by enclosing them in number signs (#).
We declare multiple constants by separating each constant name and value with a
comma. For example:
www.pavanworld.net 55
8) Conditional Statements
We can control the flow of our script with conditional statements and looping
statements.
Using conditional statements, we can write VBScript code that makes decisions and
repeats actions. The following conditional statements are available in VBScript:
1) If…Then…Else Statement
Dim myDate
myDate = #2/13/98#
If myDate < Now Then myDate = Now
To run more than one line of code, we must use the multiple-line (or block) syntax.
This syntax includes the End If statement.
Dim x
x= 20
If x>10 Then
msgbox "Hello G.C.Reddy"
msgbox "x value is: "&x
msgbox "Bye Bye"
End If
Example:
www.pavanworld.net 56
Dim x
x= Inputbox (" Enter a value")
If x>100 Then
Msgbox "Hello G.C.Reddy"
Msgbox "X is a Big Number"
Msgbox "X value is: "&X
Else
Msgbox "GCR"
Msgbox "X is a Small Number"
Msgbox "X value is: "&X
End If
Example:
Dim x
x= Inputbox (" Enter a value")
Else
Msgbox "Hello Sir"
Msgbox "X is a Grand Number"
End If
End If
End If
Example:
www.pavanworld.net 57
If state= "AP" Then
If Region= "Telangana" Then
msgbox "Hello G.C.Reddy"
msgbox "Dist count is 10"
End If
End If
End If
End If
Example:
Option explicit
Dim x,y, Operation, Result
x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")
Operation= Inputbox ("Enter an Operation")
Case "add"
Result= cdbl (x)+cdbl (y)
Msgbox "Hello G.C.Reddy"
Msgbox "Addition of x,y values is "&Result
Case "sub"
Result= x-y
Msgbox "Hello G.C.Reddy"
Msgbox "Substraction of x,y values is "&Result
Case "mul"
Result= x*y
Msgbox "Hello G.C.Reddy"
Msgbox "Multiplication of x,y values is "&Result
Case "div"
Result= x/y
www.pavanworld.net 58
Msgbox "Hello G.C.Reddy"
Msgbox "Division of x,y values is "&Result
Case "mod"
Result= x mod y
Msgbox "Hello G.C.Reddy"
Msgbox "Mod of x,y values is "&Result
Case "expo"
Result= x^y
Msgbox "Hello G.C.Reddy"
Msgbox"Exponentation of x,y values is "&Result
Case Else
Msgbox "Hello G.C.Reddy"
msgbox "Wrong Operation"
End Select
8.3.1 Write a program for finding out whether the given year is a leap year
or not?
Dim xyear
xyear=inputbox ("Enter Year")
8.3.2 Write a program for finding out whether the given number is, Even number or
Odd number?
Dim num
num=inputbox ("Enter a number")
sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion
require
www.pavanworld.net 59
msgbox ("Sum is " &sum)
Dim p,t, r, si
p=inputbox ("Enter Principle")
t=inputbox ("Enter Time")
r=inputbox ("Enter Rate of Interest")
si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest
msgbox ("Simple Interest is " &si)
8.3.5 Read Four digit number, calculate & display the sum of the number or
display Error message if the number is not a four digit number?
Dim num,rev
num= inputbox("Enter a number")
If len(num)=4 Then
www.pavanworld.net 60
msgbox "Reverse Order of the number is "&rev
Else
msgbox "Number, you entered is not a 4 digit number"
End If
8.3.7 Read 4 subjects marks; calculate the Total marks and grade?
(a) If average marks Greater than or equal to 75, grade is Distinction
b) If average marks Greater than or equal to 60 and less than 75 , then
grade is First
c) If average marks Greater than or equal to 50 and less than 60 , then
grade is Second
d) If average marks Greater than or equal to 40 and less than 50 , then
grade is Third
e) Minimum marks 35 for any subject, otherwise 'no grade fail')
If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot
>=300 Then
msgbox "Grade is Distinction"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot
>=240 and tot<300 Then
msgbox "Grade is First"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot
>=200 and tot<240 Then
msgbox "Grade is Second"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot
>=160 and tot<200 Then
msgbox "Grade is Third"
else
msgbox "No Grade, Fail"
End If
End If
End If
End If
Dim num,n
n=Inputbox ("Enter a Vaule")
www.pavanworld.net 61
For num= 1 to n step 2
msgbox num
Next
Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 2 to n step 2
msgbox num
Next
Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgbox num
Next
www.pavanworld.net 62
Dim num, n, sum
n= inputbox ("Enter a Value")
sum=0
num=1
Do
sum= sum+num
num=num+1
Loop Until num =cdbl (n+1)
msgbox sum
8.16 Verify weather the entered 10 digit value is a numeric value or not?
Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True"
and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) =
"True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) =
"True"and isnumeric (d10) = "True" Then
msgbox "It is a Numeric Value"
else
Msgbox "It is NOT Numeric"
End If
8.17 Verify weather the entered value is a 10 digit value or not and Numeric value or
not? (using multiple if conditions)
Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
www.pavanworld.net 63
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))
If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True"
and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) =
"True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) =
"True"and isnumeric (d10) = "True" Then
msgbox "It is a Numeric Value"
End If
End If
www.pavanworld.net 64
9) Looping Through Code
a) Do While condition
Statements
-----------
-----------
Loop
Example:
Dim x
Do While x<5 x=x+1
Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
Loop
b) Do
Statements
-----------
-----------
Loop While condition
Example:
www.pavanworld.net 65
Dim x
x=1
Do
Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
x=x+1
Loop While x<5
c) Do Until condition
Statements
-----------
-----------
Loop
Example:
Dim x
Do Until x=5 x=x+1
Msgbox "G.C.Reddy"
Msgbox "Hello QTP"
Loop
d) Do
Statements
-----------
-----------
Loop Until condition
Example:
Dim x
x=1
Do
Msgbox “Hello G.C.Reddy”
Msgbox "Hello QTP"
x=x+1
Loop Until x=5
Syntax:
www.pavanworld.net 66
While condition
Statements
-----------
-----------
Wend
Example:
Dim x
x=0
While x<5 x=x+1
msgbox "Hello G.C.Reddy"
msgbox "Hello QTP"
Wend
Syntax:
statements
Next
Example:
Dim x
For x= 1 to 5 step 1
Msgbox "Hello G.C.Reddy"
Next
Syntax:
Statements
Next
Example:
Dim a,b,x (3)
a=20
b=30
x(0)= "Addition is "& a+b
www.pavanworld.net 67
x(1)="Substraction is " & a-b
x(2)= "Multiplication is " & a*b
x(3)= "Division is " & a/b
Example:
MyArray = Array("one","two","three","four","five")
For Each element In MyArray
msgbox element
Next
In VBScript, there are two kinds of procedures; the Sub procedure and the Function
procedure.
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub
statements) that perform actions but don't return a value.
A Sub procedure can take arguments (constants, variables, or expressions that are
passed by a calling procedure).
If a Sub procedure has no arguments, its Sub statement must include an empty set
of parentheses ().
Syntax:
Statements
-----------
-----------
End Sub
Or
Statements
-----------
www.pavanworld.net 68
-----------
End Sub
Example: 1
Sub ConvertTemp()
MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub
Example: 2
A Function procedure is similar to a Sub procedure, but can also return a value.
Syntax:
Statements
-----------
-----------
End Function
Or
Statements
www.pavanworld.net 69
-----------
-----------
End Function
Example: 1
Function Celsius(fDegrees)
End Function
Example: 2
Function cal(a,b,c)
cal = (a+b+c)
End Function
11.3 Getting Data into and out of Procedures
A Function in our code must always be used on the right side of a variable
assignment or in an expression.
For example:
Temp = Celsius(fDegrees)
-Or-
MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."
To call a Sub procedure from another procedure, type the name of the procedure
along with values for any required arguments, each separated by a comma.
The Call statement is not required, but if you do use it, you must enclose any
arguments in parentheses.
www.pavanworld.net 70
The following example shows two calls to the MyProc procedure. One uses the Call
statement in the code; the other doesn't. Both do exactly the same thing.
Notice that the parentheses are omitted in the call when the Call statement isn't
used.
www.pavanworld.net 71
11) VB Script Built in Functions
1) Asc Function
2) Chr Function
'Returns the character associated with the specified ANSI character code.
Dim val
val=65
val=Chr(val)
msgbox val 'Output: A
3) Date Function
It returns current system Date
Dim myDate
myDate=Date
msgbox myDate
4) Abs Function
It returns obsolute value of the given number.
Dim num
num=157.56
num=Abs(num)
msgbox num 'Output: 157.56
num=-157.56
num=Abs(num)
msgbox num 'Output: 157.56
www.pavanworld.net 72
5) Array Function
We can enter list of values using this function
Ex:
Dim var
'List of strings
var=Array("Hyderabad","Chennai", "Nellore")
msgbox var(0) 'output: Hyderabad
msgbox var(1) 'output: Chennai
msgbox var(2) 'output: Nellore
6) IsArray Function
x=isArray(var2)
msgbox x
www.pavanworld.net 73
7) IsDate
myDate="India"
x=IsDate(myDate)
msgbox x 'Output: False
myDate=#10/05/2010#
x=IsDate(myDate)
msgbox x 'Output: True
myDate=#10-05-2010#
x=IsDate(myDate)
msgbox x 'Output: True
myDate=#10-05-10#
x=IsDate(myDate)
msgbox x 'Output: True
myDate=10-05-2010
x=IsDate(myDate)
msgbox x 'Output: False
8) DateDiff Function
www.pavanworld.net 74
x=DateDiff("d", date1,date2) 'd for day
msgbox x' It subtracts date1 from date2
9) IsNumeric
It checks weather the given value is numeric or not and It provides True/False like
Result
Example:
Dim val,x
val="100"
x=Isnumeric(val)
msgbox x 'Output: True
val=100
x=Isnumeric(val)
msgbox x 'Output: True
x=Isnumeric(500)
msgbox x 'Output: True
x=Isnumeric("India")
msgbox x 'Output: False
www.pavanworld.net 75
msgbox x 'Output: 9
val=100
x=Len(val)
msgbox x 'Output: 3
val="Hydera100"
x=Len(val)
msgbox x 'Output: 9
val="hy$@*de"
x=Len(val)
msgbox x 'Output: 7
val="100"
x=Len(val)
msgbox x 'Output: 3
val=#10-10-2010#
x=Len(val)
msgbox x 'Output: 10
x=Len("Krishna")
msgbox x 'Output: 7
x=Len(Krishna)
msgbox x 'Output: 0
x=Len()
msgbox x 'Output: Error
www.pavanworld.net 76
Example:
Dim val,x
val="Hyderabad"
x=Left(val,3)
msgbox x ' Output: Hyd
val="9247837478"
x=Left(val,1)
msgbox x ' Output: 9
val="H92yderabad"
x=Left(val,3)
msgbox x ' Output: H92
x=Left(9247837478,5)
msgbox x ' Output: 92478
val=#10-10-10#
x=Left(val,3)
msgbox x ' Output: 10/
val="9247837478"
x=Right(val,1)
msgbox x ' Output: 8
val="H92yderabad"
x=Right(val,3)
www.pavanworld.net 77
msgbox x ' Output: bad
x=Right(9247837478,5)
msgbox x ' Output: 37478
val=#10-10-10#
x=Right(val,5)
msgbox x ' Output: /2010
val="Hyderabad"
x=Mid(Val,5)
msgbox x ' Output: rabad
val="9247837478"
x=Mid(val,6,5)
msgbox x ' Output: 37478
val="H92yderabad"
x=Mid(val,1)
msgbox x ' Output: H92yderabad
x=Mid(9247837478,5)
msgbox x ' Output: 837478
val=#10-10-10#
x=Mid(val,5)
msgbox x ' Output: 0/2010
www.pavanworld.net 78
14) StrReverse
val="001"
x=StrReverse(val)
msgbox x 'Output: 100
val=1002
x=StrReverse(val)
msgbox x 'Output: 2001
val=#10-10-10#
x=StrReverse(val)
msgbox x 'Output: 0102/01/01
x=StrReverse("Hyderabad")
msgbox x 'Output: dabaredyH
x=StrReverse(100)
msgbox x 'Output: 001
www.pavanworld.net 79
Example:
Dim str1,str2,x
str1="India"
str2="India"
x=StrComp(str1,str2,1)
msgbox x 'Output 0
str1="india"
str2="INDIA"
x=StrComp(str1,str2,1)
msgbox x 'Output 0
str1="India"
str2="Indian"
x=StrComp(str1,str2,1)
msgbox x 'Output -1
str1="Indian"
str2="Ndia"
x=StrComp(str1,str2,1)
msgbox x 'Output -1
str1="Indian"
str2="India"
x=StrComp(str1,str2,1)
msgbox x 'Output 1
str1=100
str2=100
x=StrComp(str1,str2,1)
msgbox x 'Output 0
str1=100
str2=101
x=StrComp(str1,str2,1)
msgbox x 'Output -1
www.pavanworld.net 80
16) Lcase function
Coverts Upper case values into Lower case
Dim val,x
val="HYDERABAD"
x=Lcase(val)
msgbox x 'Output hyderabad
val="Hyderabad"
x=Lcase(val)
msgbox x 'Output hyderabad
val="HederabaD"
x=Lcase(val)
msgbox x 'Output hyderabad
val="hyderabad"
x=Lcase(val)
msgbox x 'Output hyderabad
x=Lcase("HYDERABAD")
msgbox x 'Output hyderabad
Dim val,x
val="HYDERABAD"
x=Ucase(val)
msgbox x 'Output HYDERABAD
val="Hyderabad"
x=Ucase(val)
msgbox x 'Output HYDERABAD
www.pavanworld.net 81
val="HederabaD"
x=Ucase(val)
msgbox x 'Output HYDERABAD
val="hyderabad"
x=Ucase(val)
msgbox x 'Output HYDERABAD
x=Ucase("HYDERABAD")
msgbox x 'Output HYDERABAD
num=14.59
x=Round(num)
msgbox x 'Output: 15
num="14.49"
x=Round(num)
msgbox x 'Output: 14
num="Hyd"
x=Round(num)
msgbox x 'Output: Error
www.pavanworld.net 82
Dim val
val=" VB Script"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val=" 100"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val=" 2#$%^"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val="100 "
x=LTrim(val)
www.pavanworld.net 83
msgbox x
x=Len(x)
msgbox x
val= 100
x=LTrim(val)
msgbox x
x=Len(x)
msgbox x
21) Rtrim
It removes spaces from right side of a string
Dim val
val="VB Script "
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
www.pavanworld.net 84
val=" 2#$%^ "
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
val= 100
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
www.pavanworld.net 85
a=Split(b)
msgbox a(5) 'Output: Scripting
b="VB@Script@is@a@Powerful@scripting@Language"
a=Split(b,"@")
msgbox a(5) 'Output: Scripting
b="VBScriptisaPowerfulscriptingLanguage"
a=Split(b)
msgbox a(5) 'Output: Error
21.1 Case-sensitivity:
By default, VBScript is not case sensitive and does not differentiate between upper-
case and lower-case spelling of words, for example, in variables, object and method
names, or constants.
When we enter a value as a text string, we must add quotation marks before and
after the string. For example, in the above segment of script, the names of the Web
site, Web page, and edit box are all text strings surrounded by quotation marks.
Note that the value 31 is also surrounded by quotation marks, because it is a text
string that represents a number and not a numeric value.
In the following example, only the property name (first argument) is a text string
and is in quotation marks. The second argument (the value of the property) is a
variable and therefore does not have quotation marks. The third argument
(specifying the timeout) is a numeric value, which also does not need quotation
marks.
21.3 Variables:
We can specify variables to store strings, integers, arrays and objects. Using
variables helps to make our script more readable and flexible
21.4 Parentheses:
To achieve the desired result and to avoid errors, it is important that we use
parentheses () correctly in our statements.
www.pavanworld.net 86
21.5 Indentation:
We can indent or outdent our script to reflect the logical structure and nesting of the
statements.
21.6 Comments:
We can add comments to our statements using an apostrophe ('), either at the
beginning of a separate line, or at the end of a statement. It is recommended that
we add comments wherever possible, to make our scripts easier to understand and
maintain.
21.7 Spaces:
We can add extra blank spaces to our script to improve clarity. These spaces are
ignored by VBScript.
13) Errors
We have two types Errors in VB Script; they are VBScript Run-time Errors and
VBScript Syntax Errors
VBScript run-time errors are errors that result when our VBScript script attempts to
perform an action that the system cannot execute. VBScript run-time errors occur
while our script is being executed; when variable expressions are being evaluated,
and memory is being dynamic allocated.
www.pavanworld.net 87
File System Operations
File System Object Model:
The File System Object (FSO) model provides an object-based tool for working with
folders and files. It allows us to use the familiar object. method syntax with a rich set
of properties, methods, and events to process folders and files. We can also employ
the traditional Visual Basic statements and commands.
The FSO model gives our application the ability to create, alter, move, and delete
folders, or to determine if and where particular folders exist. It also enables us to get
information about folders, such as their names and the date they were created or
last modified.
The FSO model makes processing files much easier as well. When processing files,
our primary goal is to store data in an efficient, easy-to-access format. We need to
be able to create files, insert and change the data, and output (read) the data.
Although we can store data in a database, doing so adds a significant amount of
overhead to our application. We may not want to have such overhead, or our data
access requirements may not call for the extra functionality associated with a full-
featured database. In this case, storing our data in a text file or binary file is the
most efficient solution.
The FSO model, contained in the Scripting type library (Scrrun.dll), supports the
creation and manipulation of text files through the TextStream object; however, the
FSO model does not support binary files. To manipulate binary files, use the FileOpen
Function with the Binary keyword.
Examples
1) Create a Folder
Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:\Pavan"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder(strDirectory)
2) Delete a Folder
3) Copying Folders
Set oFSO=createobject("Scripting.Filesystemobject")
oFSO.CopyFolder "E:\gcr", "C:\jvr", True
4) Checking weather the folder available or not, if not creating the folder
www.pavanworld.net 88
Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:\Pavan"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
msgbox strDirectory & " already created "
else
Set objFolder = objFSO.CreateFolder(strDirectory)
end if
8) Checking weather the File is available or not, if not creating the File
strDirectory="E:\"
strFile="Pavan.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile("E:\Pavan.txt")
End if
www.pavanworld.net 89
10) Reading Data line by line from a Flat File
11) Reading data from a flat file and using in data driven testing
Dim fso,myfile
Set fso=createobject("scripting.filesystemobject")
Set myfile= fso.opentextfile ("F:\Pavan.txt",1)
myfile.skipline
While myfile.atendofline <> True
x=myfile.readline
s=split (x, ",")
Set objFSO=createobject("Scripting.filesystemobject")
Set txtFilepath = objFSO.GetFile("E:\gcr.txt")
txtFilepath.Delete()
14) Checking weather the File is available or not, if available delete the File
strDirectory="E:\"
strFile="gcr.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
www.pavanworld.net 90
Set objFile = objFSO.Getfile(strDirectory & strFile)
objFile.delete ()
End if
Dim f1, f2
f1="e:\Pavan1.txt"
f2="e:\Pavan2.txt"
Public Function CompareFiles (FilePath1, FilePath2)
Dim FS, File1, File2
Set FS = CreateObject("Scripting.FileSystemObject")
If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then
CompareFiles = True
Exit Function
End If
Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0)
Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)
CompareFiles = False
Do While File1.AtEndOfStream = False
Str1 = File1.Read
Str2 = File2.Read
CompareFiles = StrComp(Str1, Str2, 0)
If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
Loop
File1.Close()
File2.Close()
End Function
Call Comparefiles(f1,f2)
If CompareFiles(f1, f2) = False Then
MsgBox "Files are identical."
Else
MsgBox "Files are different."
End If
sFileName="E:\gcr.txt"
sString="pavan"
Const FOR_READING = 1
Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING)
sReadTxt = oTxtFile.ReadAll
Set oRegEx = New RegExp
oRegEx.Pattern = sString
oRegEx.IgnoreCase = bIgnoreCase
oRegEx.Global = True
Set oMatches = oRegEx.Execute(sReadTxt)
MatchesFound = oMatches.Count
www.pavanworld.net 91
Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing
msgbox MatchesFound
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001
strPathtoTextFile = "C:\Databases\"
Do Until objRecordset.EOF
Wscript.Echo "Name: " & objRecordset.Fields.Item("Name")
Wscript.Echo "Department: " & _
objRecordset.Fields.Item("Department")
Wscript.Echo "Extension: " & objRecordset.Fields.Item("Extension")
objRecordset.MoveNext
Loop
Const ForReading = 1
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
arrServiceList = Split(strNextLine , ",")
Wscript.Echo "Server name: " & arrServiceList(0)
For i = 1 to Ubound(arrServiceList)
Wscript.Echo "Service: " & arrServiceList(i)
Next
Loop
www.pavanworld.net 92
Excel File Operations
1) Create an Excel file, enter some data and save the file through VB
scripting?
1) Dim objexcel
2) Set objExcel = createobject("Excel.application")
3) objexcel.Visible = True
4) objexcel.Workbooks.add
5) objexcel.Cells(1, 1).Value = "Testing"
6) objexcel.ActiveWorkbook.SaveAs("f:\exceltest.xls")
7) objexcel.Quit
1) Set myExcel=Createobject("Excel.Application")
2) Set myFile=myExcel.workbooks.open ("C:\Documents and Settings\admin\My
Documents\pavan.xls")
3) Set mySheet=myFile.worksheets("Sheet1")
4) Rows_Count=mySheet.usedrange.rows.count
5) For i= 1 to Rows_Count
6) Agent=mySheet.cells(i,"A")
7) pwd=mySheet.Cells(i,"B")
8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury
Interactive\QuickTest Professional\samples\flight\app\","open"
9) Dialog("Login").Activate
10) Dialog("Login").WinEdit("Agent Name:").Set Agent
11) Dialog("Login").WinEdit("Password:").SetSecure pwd
12) Dialog("Login").WinEdit("Password:").Type micReturn
13) Window("Flight Reservation").Close
14) Next
www.pavanworld.net 93
objExcel.quit
set objExcel=nothing
Datatable.AddSheet "pavan"
Datatable.ImportSheet "C:\Documents and
Settings\Administrator\Desktop\pavan.xls",1,3
n=datatable.GetSheet (3).GetRowCount
For i= 1 to n
Datatable.SetCurrentRow(i)
Invokeapplication "C:\Program Files\HP\QuickTest
Professional\samples\flight\app\flight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set datatable("agent",3)
Dialog("Login").WinEdit("Password:").Set datatable("pwd",3)
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
Next
Example 2):
Datatable.AddSheet "pavan"
Datatable.ImportSheet "C:\Documents and
Settings\Administrator\Desktop\pavan.xls",1,3
n=datatable.GetSheet (3).GetRowCount
For i= 1 to n
Datatable.SetCurrentRow(i)
VbWindow("Form1").Activate
VbWindow("Form1").VbEdit("val1").Set datatable("V1",3)
VbWindow("Form1").VbEdit("val2").Set datatable("V2",3)
VbWindow("Form1").VbButton("ADD").Click
eres= Datatable.Value ("res",3)
ares=VbWindow("Form1").VbEdit("res").GetROProperty ("text")
If eres=ares Then
datatable("res",3)=pass
else
datatable("res",3)=fail
End If
Next
www.pavanworld.net 94
("C:\Scripts\New_users.xls")
intRow = 2
objExcel.Quit
objExcel.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"
objExcel.Cells(1, 1).Font.Bold = TRUE
objExcel.Cells(1, 1).Font.Size = 24
objExcel.Cells(1, 1).Font.ColorIndex = 3
Const xlAscending = 1
Const xlDescending = 2
Const xlYes = 1
objRange.Sort objRange2,xlAscending,objRange3,,xlDescending, _
objRange4,xlDescending,xlYes
www.pavanworld.net 95
Database Operations
ADO (Active Data Objects), this technology allows users to access data easily from
many existing databases (such as Access or Paradox) or from ODBC compliant
databases like Oracle or MS SQL Server. Using ADO is quite simple and allows
programmers to provide flexible database front ends to users that are reliable and
include many features.
Following are some of the key objects found in the ADO object model and some of
their key methods and properties.
Connection Object
This object represents an open connection to the data source. This connection can be
a local connection (say App.Path) or can be across a network in a client server
application. Some of the methods and properties of this object are not available
depending on the type of data source connected to.
Command Object
A command object specifies a specific method we intend to execute on or against the
data source accessed by an open connection.
RecordSet Object
Examples
1) Get Test Data from a Database and use in Data Driven Testing (through
Scripting)
1) Dim con,rs
2) Set con=createobject("Adodb.connection")
3) Set rs=createobject("Adodb.recordset")
4) con.provider=("microsoft.jet.oledb.4.0")
5) con.open "C:\Documents and Settings\Administrator\My Documents\Pavan.mdb"
6) rs.open "Select * From Login",con
7) While rs.eof <>True
8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe"
9) Dialog("Login").Activate
10) Dialog("Login").WinEdit("Agent Name:").Set rs.fields ("Agent")
11) Dialog("Login").WinEdit("Password:").Set rs.fields ("Password")
12) Dialog("Login").WinButton("OK").Click
13) Window("Flight Reservation").Close
14) rs.movenext
15) Wend
www.pavanworld.net 96
2) Exporting Data from a Database to an Excel Sheet
1) Dim con,rs
2) Set con=createobject("adodb.connection")
3) Set rs=createobject("adodb.recordset")
4) con.provider="microsoft.jet.oledb.4.0"
5) con.open"C:\Documents and Settings\admin\My Documents\Pavan.mdb"
6) rs.open"select*from Login",con
7) Set ex=createobject("Excel.Application")
8) Set a=ex.workbooks.open("C:\Documents and Settings\admin\My
Documents\Pavan.xls")
9) Set b=a.worksheets("sheet1")
10) i=1
11) Do While Not rs.EOF
12) b.cells (i,1).value=rs.fields("agent")
13) b.cells(i,2).value=rs.fields("password")
14) rs.movenext
15) i=i+1
16) Loop
17) a.save
18) a.close
Const adOpenStatic = 3
Const adLockOptimistic = 3
objConnection.Open _
www.pavanworld.net 97
"Provider=SQLOLEDB;Data Source=atl-sql-01;" & _
"Trusted_Connection=Yes;Initial Catalog=Northwind;" & _
"User ID=fabrikam\kenmyer;Password=34DE6t4G!;"
objRecordSet.MoveFirst
Wscript.Echo objRecordSet.RecordCount
Const adOpenStatic = 3
Const adLockOptimistic = 3
objConnection.Open _
"Northwind;fabrikam\kenmyer;34ghfn&!j"
objRecordSet.MoveFirst
Wscript.Echo objRecordSet.RecordCount
6) Open Two Record sets
Const adOpenStatic = 3
Const adLockOptimistic = 3
objConnection.Open _
"Provider= Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=inventory.mdb"
objRecordSet.MoveFirst
www.pavanworld.net 98
objRecordSet2.MoveFirst
Do Until objRecordset.EOF
Wscript.Echo objRecordset.Fields.Item("ComputerName")
Wscript.Echo objRecordset.Fields.Item("OSName")
objRecordSet.MoveNext
Loop
Do Until objRecordset2.EOF
Wscript.Echo objRecordset2.Fields.Item("DriveName"), _
objRecordset2.Fields.Item("DriveDescription")
objRecordSet2.MoveNext
Loop
objRecordSet.Close
objRecordSet2.Close
objConnection.Close
Const adOpenStatic = 3
Const adLockOptimistic = 3
objConnection.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source = eventlogs.mdb"
objRecordSet.MoveFirst
objRecordSet.Close
objConnection.Close
Dim objCon,objCom
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\pavan.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
www.pavanworld.net 99
objCom.Execute
objCon.Close
Set objCom=Nothing
Set objCon=Nothing
9) Insert multiple sets of Data (using Excel sheet) into a database table
using Database Command Object
Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\pavan.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
Datatable.AddSheet("input")
Datatable.ImportSheet "C:\pavan.xls",1,"input"
intRowcount=Datatable.GetSheet("input").GetRowCount
Msgbox intRowcount
For i=1 to intRowcount step 1
DataTable.SetCurrentRow(i)
strEmpName= DataTable.Value(1,"input")
intEmpNo= DataTable.Value(2,"input")
intEmpSal= DataTable.Value(3,"input")
objCom.CommandText="insert into Emp values( '"&strEmpName&"
',"&intEmpNo&","&intEmpSal&")"
objCom.Execute
Next
objCon.Close
Set objCom=Nothing
Set objCon=Nothing
www.pavanworld.net 100
Object Identification Configuration
Overview:
Generally for every object 20-25 properties information available, qtp recognizes
object using 2 0r 3 important properties.
Qtp has default object identification configuration for every environment, if we feel
that configuration is not sufficient for recognizing objects in our application, we can
configure some more
a) Normal identification
1) Mandatory properties
2) Assistive properties
b) Smart identification
c) Ordinal identifier
1) location
2) index
3) creation time(only for web)
First of all the qtp learns all the mandatory properties at a time and thinks whether
these properties sufficient to identify the object uniquely. if it feels sufficient then it
stops learning otherwise,
It learns first assistive property and once again stops and thinks, like this qtp learns
one by one. At the end of assistive properties list also if it feels not satisfied and it
finally goes to Ordinal Identifier.
After normal identification if qtp feels not satisfied then it goes to smart
identification. in smart identification 2 types of properties available, first qtp learns
all base filter properties at a time and thinks whether these properties are sufficient
for identifying the object uniquely. If it feels sufficient, then it stops learning
otherwise it goes Optional Filter Properties and learns one by one. Still it feels not
satisfied finally it goes to Ordinal Identifier.
www.pavanworld.net 101
Ordinal identifiers:
1) Location: is based on object location in the AUT ,location starts from zero.
3) Creation time: it is based on loading time of the web objects. qtp generates 0,1,2
like numbers.
For making tool settings global, QTP is providing a special feature called "Generate
Script".
STEPS:
a) File->Settings
b) Tools->Options
c) Tools->Object Identification
3) Share Script files to team members and ask them to execute those scripts.
NOTE: After executing these scripts all team members can get same settings.
www.pavanworld.net 102
Regular Expressions in QTP
What is Regular Expression?
It is a way of representing data using symbols. They are often used within
matching, searching or replacing algorithms.
Regular expressions can be used in QTP for identifying objects and text strings with
varying values.
Where we use:
We can define a regular expression for a constant value, a Data Table parameter
value, an Environment parameter value, or a property value in Descriptive
programming.
We can define the text string as a regular expression, when creating a text
checkpoint to check that a varying text string is displayed on our application,
For XML checkpoints we can set attribute or element values as regular expressions.
a) Backslash Character:
A backslash (\) can serve two purposes. It can be used in conjunction with a special
character to indicate that the next character be treated as a literal character.
Alternatively, if the backslash (\) is used in conjunction with some characters that
would otherwise be treated as literal characters, such as the letters n, t, w, or d, the
combination indicates a special character.
A period (.) instructs QTP to search for any single character (except for \n).
Ex:
www.pavanworld.net 103
welcome.
Matches welcomes, welcomed, or welcome followed by a space or any other single
character.
Square brackets instruct QTP to search for any single character within a list of
characters.
Ex:
To search for the date 1867, 1868, or 1869, enter:
186[789]
When a caret (^) is the first character inside square brackets, it instructs QTP to
match any character in the list except for the ones specified in the string.
Example:
[^ab]
Matches any character except a or b.
To match a single character within a range, we can use square brackets ([ ]) with
the hyphen (-) character.
Example:
For matching any year in the 2010s, enter:
201[0-9]
An asterisk (*) instructs QTP to match zero or more occurrences of the preceding
character.
For example:
ca*r
A plus sign (+) instructs QTP to match one or more occurrences of the preceding
character.
For example:
ca+r
Matches car and caaaaaar, but not cr.
www.pavanworld.net 104
h) Matching Zero or One Specific Character:
A question mark (?) instructs QTP to match zero or one occurrences of the preceding
character.
For example:
ca?r
Matches car and cr, but nothing else.
Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as in
mathematics and programming languages. Using groups is especially useful for
delimiting the argument(s) to an alternation operator ( | ) or a repetition operator
( * , + , ? , { } ).
A caret (^) instructs QTP to match the expression only at the start of a line, or after
a newline character.
A dollar sign ($) instructs QTP to match the expression only at the end of a line, or
before a newline character.
\w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-
z, 0-9, _).
\W instructs QTP to match any character other than alphanumeric characters and
underscores.
www.pavanworld.net 105
exact search criteria we need.
For example,
start.*
Matches start, started, starting, starter, and so forth.
we can use a combination of brackets and an asterisk to limit the search to a
combination of non-numeric characters.
For example:
[a-zA-Z]*
To match any number between 0 and 1200, we need to match numbers with 1 digit,
2 digits, 3 digits, or 4 digits between 1000-1200.
The regular expression below matches any number between 0 and 1200.
([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200)
RegExp object
Properties:
a) Global Property
b) IgnoreCase Property
c) Pattern Property
Methods:
a) Execute Method
b) Replace Method
www.pavanworld.net 106
c) Test Method
--------------------------------------------------
www.pavanworld.net 107
Batch Testing
For performing Batch Testing, QTP has provided a separate Tool called 'Test Batch
Runner'.
Note: Test Batch Runner launches QTP Tool, QTP runs Tests one by one.
Open Test Batch Runner >open Test Batch>Select or deselect tests>run test batch.
www.pavanworld.net 108
VB Script Other Objects
1) Dictionary Object
Add Method
Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.
Items Method
Keys Method
Remove Method
RemoveAll Method
The RemoveAll method removes all key, item pairs from a Dictionary object.
Example:
Dim cities
Set cities = CreateObject("Scripting.Dictionary")
cities.Add "h", "Hyderabad"
cities.Add "b", "Bangalore"
www.pavanworld.net 109
cities.Add "c", "Chennai"
CompareMode Property
Sets and returns the comparison mode for comparing string keys in a Dictionary
object.
Key Property
Item Property
Sets or returns an item for a specified key in a Dictionary object. For collections,
returns an item based on the specified key. Read/write.
Examples:
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
colKeys = objDictionary.Keys
Wscript.Echo "First run: "
For Each strKey in colKeys
Wscript.Echo strKey
Next
objDictionary.RemoveAll
colKeys = objDictionary.Keys
www.pavanworld.net 110
Wscript.Echo VbCrLf & "Second run: "
For Each strKey in colKeys
Wscript.Echo strKey
Next
colKeys = objDictionary.Keys
Wscript.Echo strKey
Next
objDictionary.Remove("Printer 2")
colKeys = objDictionary.Keys
Wscript.Echo strKey
Next
www.pavanworld.net 111
4) List the Number of Items in a Dictionary
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Wscript.Echo objDictionary.Count
Else
End If
2) RegExp object
Properties:
a) Global Property
b) IgnoreCase Property
c) Pattern Property
Methods:
a) Execute Method
www.pavanworld.net 112
b) Replace Method
c) Test Method
strCurrentDirectory = objShell.CurrentDirectory
objRE.Global = True
objRE.IgnoreCase = False
objRE.Pattern = WScript.Arguments(0)
bMatch = objRE.Test(objFile.Name)
If bMatch Then
WScript.Echo objFile.Name
End If
Next
www.pavanworld.net 113
2) Match Content in a File against a Regular Expression
strFileName = "E:\pavan.txt"
strFileContents = objTS.ReadAll
WScript.Echo strFileContents
objTS.Close
objRE.Global = True
objRE.IgnoreCase = False
objRE.Pattern = WScript.Arguments(0)
WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value
Next
Dim objCon,objCom
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\pavan.mdb;"
Set objCom=Createobject("ADODB.Command")
www.pavanworld.net 114
objCom.ActiveConnection=objCon
objCon.Close
Set objCom=Nothing
Set objCon=Nothing
2) Insert multiple sets of Data (using Excel sheet) into a database table
using Database Command Object
Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\pavan.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
Datatable.AddSheet("input")
Datatable.ImportSheet "C:\pavan.xls",1,"input"
intRowcount=Datatable.GetSheet("input").GetRowCount
Msgbox intRowcount
For i=1 to intRowcount step 1
DataTable.SetCurrentRow(i)
strEmpName= DataTable.Value(1,"input")
intEmpNo= DataTable.Value(2,"input")
intEmpSal= DataTable.Value(3,"input")
objCom.CommandText="insert into Emp values( '"&strEmpName&"
',"&intEmpNo&","&intEmpSal&")"
objCom.Execute
Next
objCon.Close
Set objCom=Nothing
Set objCon=Nothing
4) Word Object
dim mw
set mw=CreateObject("Word.Application")
mw.Documents.Add
mw.selection.typetext "hello"
mw.ActiveDocument.SaveAs "e:\pavan.doc"
mw.quit
set mw=nothing
www.pavanworld.net 115
2) Create Script to get the list of links in Google and do spell check
Dim d
set mw=CreateObject("Word.Application")
set d=Description.Create
d("micclass").value="Link"
set a=Browser("Google").page("Google").childobjects(d)
mw.WordBasic.filenew
s=a(i).getROProperty("innertext")
mw.WordBasic.insert s
if mw.ActiveDocument.Spellingerrors.count>0 then
end if
mw.ActiveDocument.Close(False)
next
mw.quit
set mw=nothing
3) Script to display all the doc files in all the drives in the system
Dim mw
Set mw=CreateObject("Word.Application")
Set fs=createobject("Scripting.FileSystemObject")
Set d=fs.Drives
mw.FileSearch.FileName="*.doc"
For each dr in d
msgbox dr
mw.FileSearch.LookIn=dr
mw.FileSearch.SearchSubFolders=True
mw.FileSearch.Execute
For each i in mw.FileSearch.FoundFiles
print i
Set f=fs.GetFile(i)
www.pavanworld.net 116
print f.Name&" "&f.Size&" "&f.DateCreated
print "-------------------------------------------------------------------"
Next
Next
mw.Quit
5) IE Object
Dim ie
Set ie=CreateObject("InternetExplorer.Application")
ie.Visible=True
ie.Navigate "www.yahoomail.com"
x=Browser("CreationTime:=0").GetROProperty("title")
msgbox x
www.pavanworld.net 117
Automation Framework
Automation:
Automation Framework:
Or
In one project test automation we use various files, we perform various tasks, in
order to organize and manage them all, a systematic approach (Automation
Framework) required.
Files to be used:
Tasks to be performed:
www.pavanworld.net 118
d) Creating Generic and project specific functions.
j) Analyzing results
k) Test reporting
m) Modifying tests
Automation Framework is not a qtp feature, it’s a 3rd party concept. And this is
purely local concept.(framework may vary from one company to another)
Advantages:
Drawbacks:
Less usage of keywords, no concentration on Data driven testing and low
performance than latest Frameworks like Keyword Driven Framework.
www.pavanworld.net 119
3. Data Driven Framework
Advantages:
Drawbacks:
5. Hybrid Framework
In the above frameworks Keyword Driven framework is very famous in the industry.
It is a mixing of more than one approach.
In this approach,we mix Data driven and Modular approaches OR Data Driven and
Keyword Driven approaches---etc
Advantages:
Scope is very high as we mix different approaches,Flexible for performing any tasks.
Drawbacks:
NOTE: Now a days Mix of Data driven and Keyword driven approaches is a famous
Hybrid Framework in the industry.
c) Methods (Ex:Set,Select,Activate,Navigate---etc)
www.pavanworld.net 120
d) Statements (EX:Dim,If,For---etc)
In this approach we use keywords for preparing tests. First we create tests and make
them as functions, through framework we execute them and generate results.
In order to create, store, organize and manage files a well defined folder structure
required. Folder structure is a mandatory element of any framework, but folder
names may vary from one framework to another and company to another .
Folder Structure:
1. Object Repository
2. Environment
3. Library
a) Company
b) Project Specific
4. Test data
5. Test log
6. Recovery scenarios
7. Miscellaneous
And
1) Object Repository: In this folder we store object repository files(.tsr), all team
members can use this repositories.
www.pavanworld.net 121
3) Function Library:this folder contains two sub folders one is for storing common
functions of our company, another folder for storing our project specific
functions(.vbs).
4) Test Data: in this folder we store test data required for data driven testing, for
that we use either .xls files or .txt files or .mdb files.
7) Miscellaneous: in this folder we store the files other than above files(ex-process
guideline doc and messages among team members and instructions by team lead
etc).
And
1) Initialization script (.vbs file): It launches qtp tool and calls driver script, at end
it closes qtp tool.
2) Driver script (QTP Script file): It is only the qtp script, we can associate all
resources to this script
*******************
www.pavanworld.net 122