Professional Documents
Culture Documents
Quicktest Professional 10.00: For QTP Scripts and Documents
Quicktest Professional 10.00: For QTP Scripts and Documents
com
Visit:
www.gcreddy.com
for QTP Scripts and Documents
www.gcreddy.com 1
gcreddy@gcreddy.com
o QTP Launched in 2002 (Nov). By Mercury Interactive. Later taken over by HP,
in 2007.
o QTP is an Object Based Testing Tool.
o QTP is for functional and Regression Testing.
o It follows Keyword driven approach.
o It supports Windows Operating Environment only.
o It supports GUI based (Graphical user interface) and Web based Applications
Automation, does not support CUI (Command user interface) Applications.
o It has multilingual support. (It supports English, Chinese, Japanese, Korean,
etc languages with respect to license.)
o It has adapted Microsoft Visual Basic Scripting edition for programming and
excel like spread sheet for Data driven testing.
o SQL (Structured query language) embedded or inserted with QTP, so we can
use SQL statements directly from QTP.
o It can be integrated with other Tools like WinRunner and Quality Center.
o It can be used for user interface (UI) test case automation and some limited
(Non UI) Test case automation like File system operations and Data base
operations.
o It was derived from Astra QuickTest (mother tool of QTP).
o It supports IE (Internet Explorer) only for recording tests, for execution it
supports other browsers like Mozilla and AOL, opera Etc apart from IE.
o QTP is a Desktop Application (I-Tier/Stand alone).
o QTP has two types of License,
1. Seat or Node locked License,
2. Concurrent or float license.
Seat license for one system and Concurrent License, we can use for any
system but one user at any time. If we want multiple concurrent licenses we
can purchase.
o QTP has UNI code support.
www.gcreddy.com 2
gcreddy@gcreddy.com
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.gcreddy.com 3
gcreddy@gcreddy.com
Launching QTP
We can launch QTP BY selecting desktop icon otherwise start > programs> QTP
Professional > QTP.
www.gcreddy.com 4
gcreddy@gcreddy.com
www.gcreddy.com 5
gcreddy@gcreddy.com
1) Test Pane:
It is programming interface of QTP, used for creating, editing, viewing and deleting
test scripts.
Test: It is a set of statements or set of one or more actions. (It is a local concept)
www.gcreddy.com 6
gcreddy@gcreddy.com
www.gcreddy.com 7
gcreddy@gcreddy.com
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.gcreddy.com 8
gcreddy@gcreddy.com
Note 1: Generally novice testers use this feature but it occupies lot of memory space
on QTP.
Active Screen
www.gcreddy.com 9
gcreddy@gcreddy.com
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.gcreddy.com 10
gcreddy@gcreddy.com
4) Debug Viewer
We use step into, step over and step out commands for debugging. (debug
commands)
www.gcreddy.com 11
gcreddy@gcreddy.com
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.gcreddy.com 12
gcreddy@gcreddy.com
6) Information
This pane shows syntax errors automatically during saving the test.
7) QTP Commands
www.gcreddy.com 13
gcreddy@gcreddy.com
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.gcreddy.com 14
gcreddy@gcreddy.com
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 objects
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.gcreddy.com 15
gcreddy@gcreddy.com
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.gcreddy.com 16
gcreddy@gcreddy.com
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.gcreddy.com 17
gcreddy@gcreddy.com
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.gcreddy.com 18
gcreddy@gcreddy.com
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.gcreddy.com 19
gcreddy@gcreddy.com
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 web
windows Environment 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.
www.gcreddy.com 20
gcreddy@gcreddy.com
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.gcreddy.com 21
gcreddy@gcreddy.com
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.gcreddy.com 22
gcreddy@gcreddy.com
(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.gcreddy.com 23
gcreddy@gcreddy.com
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.gcreddy.com 24
gcreddy@gcreddy.com
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.gcreddy.com 25
gcreddy@gcreddy.com
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.gcreddy.com 26
gcreddy@gcreddy.com
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.gcreddy.com 27
gcreddy@gcreddy.com
Methods or Operations
Ex:
Dialog(Login).Activate
Window(Flight Reservation).Activate
Ex:
Window(Flight Reservation).Close
Browser(Browser).Close
Select Method:
Ex:
www.gcreddy.com 28
gcreddy@gcreddy.com
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 objects, 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.gcreddy.com 29
gcreddy@gcreddy.com
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.gcreddy.com 30
gcreddy@gcreddy.com
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.gcreddy.com 31
gcreddy@gcreddy.com
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.gcreddy.com 32
gcreddy@gcreddy.com
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.gcreddy.com 33
gcreddy@gcreddy.com
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.gcreddy.com 34
gcreddy@gcreddy.com
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.gcreddy.com 35
gcreddy@gcreddy.com
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.
Synchronization
www.gcreddy.com 36
gcreddy@gcreddy.com
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.gcreddy.com 37
gcreddy@gcreddy.com
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.
Parameterization
Passing parameters, through this concept we can pass multiple values.
www.gcreddy.com 38
gcreddy@gcreddy.com
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"
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
www.gcreddy.com 39
gcreddy@gcreddy.com
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
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)
www.gcreddy.com 40
gcreddy@gcreddy.com
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.gcreddy.com 41
gcreddy@gcreddy.com
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.
Or
www.gcreddy.com 42
gcreddy@gcreddy.com
X=environment (city)
Msgbox x
Actions
Action: A Set of Statements for performing a Task or Tasks.
www.gcreddy.com 43
gcreddy@gcreddy.com
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:
Renaming actions:
Select desired action in action drop down box> edit menu>action>rename
action>modify the name>click ok.
www.gcreddy.com 44
gcreddy@gcreddy.com
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.
VB Script
(Fundamentals and Features)
www.gcreddy.com 45
gcreddy@gcreddy.com
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
1.0 Introduction
VBScript is a scripting language.
A scripting language is a lightweight programming language.
VBScript is a light version of Microsoft's programming language Visual Basic.
www.gcreddy.com 46
gcreddy@gcreddy.com
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
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.
www.gcreddy.com 47
gcreddy@gcreddy.com
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.
2.0 Comments
www.gcreddy.com 48
gcreddy@gcreddy.com
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.gcreddy.com 49
gcreddy@gcreddy.com
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.gcreddy.com 50
gcreddy@gcreddy.com
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
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.
www.gcreddy.com 51
gcreddy@gcreddy.com
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.
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.
www.gcreddy.com 52
gcreddy@gcreddy.com
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
www.gcreddy.com 53
gcreddy@gcreddy.com
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.
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.
www.gcreddy.com 54
gcreddy@gcreddy.com
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 (&)
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")
www.gcreddy.com 55
gcreddy@gcreddy.com
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:
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) IfThenElse Statement
www.gcreddy.com 56
gcreddy@gcreddy.com
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:
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
www.gcreddy.com 57
gcreddy@gcreddy.com
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.gcreddy.com 58
gcreddy@gcreddy.com
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
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"
www.gcreddy.com 59
gcreddy@gcreddy.com
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
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)
www.gcreddy.com 60
gcreddy@gcreddy.com
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
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
www.gcreddy.com 61
gcreddy@gcreddy.com
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")
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
www.gcreddy.com 62
gcreddy@gcreddy.com
Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgbox num
Next
www.gcreddy.com 63
gcreddy@gcreddy.com
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.gcreddy.com 64
gcreddy@gcreddy.com
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.gcreddy.com 65
gcreddy@gcreddy.com
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:
Dim x
x=1
Do
Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
x=x+1
Loop While x<5
c) Do Until condition
www.gcreddy.com 66
gcreddy@gcreddy.com
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:
While condition
Statements
-----------
-----------
Wend
Example:
Dim x
x=0
While x<5 x=x+1
msgbox "Hello G.C.Reddy"
msgbox "Hello QTP"
www.gcreddy.com 67
gcreddy@gcreddy.com
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
x(1)="Substraction is " & a-b
x(2)= "Multiplication is " & a*b
x(3)= "Division is " & a/b
Example:
www.gcreddy.com 68
gcreddy@gcreddy.com
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
-----------
-----------
End Sub
Example: 1
Sub ConvertTemp()
www.gcreddy.com 69
gcreddy@gcreddy.com
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
-----------
-----------
End Function
Example: 1
Function Celsius(fDegrees)
www.gcreddy.com 70
gcreddy@gcreddy.com
End Function
Example: 2
Function cal(a,b,c)
cal = (a+b+c)
End Function
11.3 Getting Data into and out of Procedures
o When we create a procedure using either the Sub statement or the Function
statement, parentheses must be included after the name of the procedure.
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.
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.
www.gcreddy.com 71
gcreddy@gcreddy.com
Notice that the parentheses are omitted in the call when the Call statement isn't
used.
www.gcreddy.com 72
gcreddy@gcreddy.com
msgbox val
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
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
www.gcreddy.com 73
gcreddy@gcreddy.com
6) IsArray Function
x=isArray(var2)
msgbox x
7) IsDate
www.gcreddy.com 74
gcreddy@gcreddy.com
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.gcreddy.com 75
gcreddy@gcreddy.com
Note: through this function, we can day or month wise diffrence only.
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
val=100
x=Len(val)
msgbox x 'Output: 3
val="Hydera100"
x=Len(val)
www.gcreddy.com 76
gcreddy@gcreddy.com
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
val="9247837478"
x=Left(val,1)
www.gcreddy.com 77
gcreddy@gcreddy.com
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)
msgbox x ' Output: bad
x=Right(9247837478,5)
msgbox x ' Output: 37478
val=#10-10-10#
x=Right(val,5)
www.gcreddy.com 78
gcreddy@gcreddy.com
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
14) StrReverse
www.gcreddy.com 79
gcreddy@gcreddy.com
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
str1="india"
www.gcreddy.com 80
gcreddy@gcreddy.com
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.gcreddy.com 81
gcreddy@gcreddy.com
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
val="HederabaD"
x=Ucase(val)
msgbox x 'Output HYDERABAD
val="hyderabad"
x=Ucase(val)
msgbox x 'Output HYDERABAD
www.gcreddy.com 82
gcreddy@gcreddy.com
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
val=" 100"
www.gcreddy.com 83
gcreddy@gcreddy.com
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)
msgbox x
x=Len(x)
msgbox x
www.gcreddy.com 84
gcreddy@gcreddy.com
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.gcreddy.com 85
gcreddy@gcreddy.com
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
val= 100
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
www.gcreddy.com 86
gcreddy@gcreddy.com
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.
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.
www.gcreddy.com 87
gcreddy@gcreddy.com
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.
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
www.gcreddy.com 88
gcreddy@gcreddy.com
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:\Gcreddy"
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
Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:\Gcreddy"
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
www.gcreddy.com 89
gcreddy@gcreddy.com
8) Checking weather the File is available or not, if not creating the File
strDirectory="E:\"
strFile="Gcreddy.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile("E:\Gcreddy.txt")
End if
11) Reading data from a flat file and using in data driven testing
Dim fso,myfile
www.gcreddy.com 90
gcreddy@gcreddy.com
Set fso=createobject("scripting.filesystemobject")
Set myfile= fso.opentextfile ("F:\Gcreddy.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
Set objFile = objFSO.Getfile(strDirectory & strFile)
objFile.delete ()
End if
Dim f1, f2
f1="e:\Gcreddy1.txt"
f2="e:\Gcreddy2.txt"
Public Function CompareFiles (FilePath1, FilePath2)
Dim FS, File1, File2
Set FS = CreateObject("Scripting.FileSystemObject")
www.gcreddy.com 91
gcreddy@gcreddy.com
sFileName="E:\gcr.txt"
sString="gcreddy"
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
Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing
msgbox MatchesFound
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001
www.gcreddy.com 92
gcreddy@gcreddy.com
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
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")
www.gcreddy.com 93
gcreddy@gcreddy.com
7) objexcel.Quit
1) Set myExcel=Createobject("Excel.Application")
2) Set myFile=myExcel.workbooks.open ("C:\Documents and Settings\admin\My
Documents\gcreddy.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
Datatable.AddSheet "gcreddy"
Datatable.ImportSheet "C:\Documents and
Settings\Administrator\Desktop\gcreddy.xls",1,3
n=datatable.GetSheet (3).GetRowCount
For i= 1 to n
Datatable.SetCurrentRow(i)
www.gcreddy.com 94
gcreddy@gcreddy.com
Example 2):
Datatable.AddSheet "gcreddy"
Datatable.ImportSheet "C:\Documents and
Settings\Administrator\Desktop\gcreddy.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
intRow = 2
www.gcreddy.com 95
gcreddy@gcreddy.com
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
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.
www.gcreddy.com 96
gcreddy@gcreddy.com
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\Gcreddy.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
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\Gcreddy.mdb"
6) rs.open"select*from Login",con
7) Set ex=createobject("Excel.Application")
www.gcreddy.com 97
gcreddy@gcreddy.com
Const adOpenStatic = 3
Const adLockOptimistic = 3
objConnection.Open _
"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
www.gcreddy.com 98
gcreddy@gcreddy.com
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
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"), _
www.gcreddy.com 99
gcreddy@gcreddy.com
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:\gcreddy.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
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
www.gcreddy.com 100
gcreddy@gcreddy.com
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
Datatable.AddSheet("input")
Datatable.ImportSheet "C:\gcreddy.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
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
www.gcreddy.com 101
gcreddy@gcreddy.com
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.
Ordinal identifiers:
1) Location: is based on object location in the AUT ,location starts from zero.
www.gcreddy.com 102
gcreddy@gcreddy.com
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.
It is a way of representing data using symbols. They are often used within matching,
searching or replacing algorithms.
www.gcreddy.com 103
gcreddy@gcreddy.com
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:
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:
www.gcreddy.com 104
gcreddy@gcreddy.com
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.
A question mark (?) instructs QTP to match zero or one occurrences of the preceding
character.
For example:
www.gcreddy.com 105
gcreddy@gcreddy.com
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.gcreddy.com 106
gcreddy@gcreddy.com
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
c) Test Method
www.gcreddy.com 107
gcreddy@gcreddy.com
--------------------------------------------------
Batch Testing
For performing Batch Testing, QTP has provided a separate Tool called 'Test Batch
Runner'.
www.gcreddy.com 108
gcreddy@gcreddy.com
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.
1) Dictionary Object
www.gcreddy.com 109
gcreddy@gcreddy.com
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"
cities.Add "c", "Chennai"
www.gcreddy.com 110
gcreddy@gcreddy.com
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:
SetobjDictionary=CreateObject("Scripting.Dictionary")
objDictionary.Add"Printer1","Printing"
objDictionary.Add"Printer2","Offline"
objDictionary.Add"Printer3","Printing"
SetobjDictionary=CreateObject("Scripting.Dictionary")
objDictionary.Add"Printer1","Printing"
objDictionary.Add"Printer2","Offline"
objDictionary.Add"Printer3","Printing"
colKeys=objDictionary.Keys
Wscript.Echo"Firstrun:"
ForEachstrKeyincolKeys
Wscript.EchostrKey
Next
objDictionary.RemoveAll
colKeys=objDictionary.Keys
Wscript.EchoVbCrLf&"Secondrun:"
ForEachstrKeyincolKeys
Wscript.EchostrKey
Next
www.gcreddy.com 111
gcreddy@gcreddy.com
colKeys = objDictionary.Keys
Wscript.Echo strKey
Next
objDictionary.Remove("Printer 2")
colKeys = objDictionary.Keys
Wscript.Echo strKey
Next
SetobjDictionary=CreateObject("Scripting.Dictionary")
objDictionary.Add"Printer1","Printing"
objDictionary.Add"Printer2","Offline"
www.gcreddy.com 112
gcreddy@gcreddy.com
objDictionary.Add"Printer3","Printing"
Wscript.EchoobjDictionary.Count
Else
End If
2) RegExp object
Properties:
a) Global Property
b) IgnoreCase Property
c) Pattern Property
Methods:
a) Execute Method
b) Replace Method
c) Test Method
www.gcreddy.com 113
gcreddy@gcreddy.com
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
strFileName = "E:\gcreddy.txt"
www.gcreddy.com 114
gcreddy@gcreddy.com
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:\gcreddy.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
objCon.Close
Set objCom=Nothing
Set objCon=Nothing
www.gcreddy.com 115
gcreddy@gcreddy.com
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:\gcreddy.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
Datatable.AddSheet("input")
Datatable.ImportSheet "C:\gcreddy.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:\gcreddy.doc"
mw.quit
set mw=nothing
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
www.gcreddy.com 116
gcreddy@gcreddy.com
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)
print f.Name&" "&f.Size&" "&f.DateCreated
print "-------------------------------------------------------------------"
Next
Next
mw.Quit
5) IE Object
www.gcreddy.com 117
gcreddy@gcreddy.com
Dim ie
Set ie=CreateObject("InternetExplorer.Application")
ie.Visible=True
ie.Navigate "www.yahoomail.com"
x=Browser("CreationTime:=0").GetROProperty("title")
msgbox x
Automation Framework
Automation:
www.gcreddy.com 118
gcreddy@gcreddy.com
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.gcreddy.com 119
gcreddy@gcreddy.com
h) Debugging and running tests(Individual test execution, Test Batch execution --etc)
j) Analyzing results
k) Test reporting
m) Modifying tests
Automation Framework is not a qtp feature, its 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.
Advantages:
www.gcreddy.com 120
gcreddy@gcreddy.com
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.
Keyword:
c) Methods (Ex:Set,Select,Activate,Navigate---etc)
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.
www.gcreddy.com 121
gcreddy@gcreddy.com
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.
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.
www.gcreddy.com 122
gcreddy@gcreddy.com
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.gcreddy.com 123