138
Quick Test Professional 10.00 Visit: www.pavanworld.net for QTP Scripts and Documents www.pavanworld.net 1

Pavan+Advanced QTP Guide

Embed Size (px)

Citation preview

Page 1: Pavan+Advanced QTP Guide

Quick Test Professional 10.00

Visit:www.pavanworld.net

for QTP Scripts and Documents

www.pavanworld.net 1

Page 2: Pavan+Advanced QTP Guide

I) Basic features of QTP

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.

Version History of QTP

www.pavanworld.net 2

Page 3: Pavan+Advanced QTP Guide

Astra Quick test (Mother tool of QTP) 1.0 to 5.0

Quick Test Professional

5.6 – Nov 2002

6.5 – 2003

8.0 – 2004

8.2, 8.3 –2005

9.0,9.1-2006

9.2- 2007 mercury interactive

9.5 –2008 H.P

10.00 –2009 January

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.

Default Add- ins of QTP are:

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.

Launching QTP

We can launch QTP BY selecting desktop icon otherwise start > programs> QTP Professional > QTP.

www.pavanworld.net 3

Page 4: Pavan+Advanced QTP Guide

During launching it shows Add-In Manager.

Add-in manager window

Select appropriate Add Ins and click okay.

Quick Test Launches

II) Key Elements of QTP Tool Window

www.pavanworld.net 4

Page 5: Pavan+Advanced QTP Guide

QTP Tool Window

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)

Action: It is a set of Statements. (It is a local concept)

www.pavanworld.net 5

Page 6: Pavan+Advanced QTP Guide

Statement: A minimal executable unit. Statements may have keywords. (Keyword such as function, method, statement etc). It is a global concept.

Test pane has 2 views.

Expert view- Test in VB script format.

QTP Test Pane-Expert View

Key word view- Test in Icon based GUI format.

www.pavanworld.net 6

Page 7: Pavan+Advanced QTP Guide

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.

Note 3: User can customize Test pane view options.

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.

It can be used for understanding and editing the test easily.

www.pavanworld.net 7

Page 8: Pavan+Advanced QTP Guide

Navigation: View menu>active screen (for launching and closing)

Configuring active screen: view>options>active screen tab>increase /Decrease capture level, apply and okay.

Note 1: Generally novice testers use this feature but it occupies lot of memory space on QTP.

Active Screen3) Data Table

www.pavanworld.net 8

Page 9: Pavan+Advanced QTP Guide

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. Enter test data directly into Data Table and use. 2. Importing data from external files (Flat files, excel sheets, etc) and Data bases

(MS access, Sql Server, oracle, etc.)

It has two types of sheets.

1. Global Sheet- for entire test /used for all actions in the test.2. Action Sheets- for specific action only.

Data table available in 2 ways:

1. Design time data table. (Attached with every test)2. Run time data table. (Available in result window)

Run time is a carbon copy of design time data table.

QTP has Data table methods for performing operations on data table.

www.pavanworld.net 9

Page 10: Pavan+Advanced QTP Guide

QTP Tool window- Data Table

4) Debug Viewer

It is used for locating and rectifying or fixing errors.

It can be used for debugging the tests by step-by-step execution.

We use step into, step over and step out commands for debugging. (debug commands)

www.pavanworld.net 10

Page 11: Pavan+Advanced QTP Guide

Through Debug viewer user can watch variables and change values of variables temporarily.

Navigation: View menu>debug viewer (for launching and closing)

QTP Tool Window-Debug Viewer

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

Page 12: Pavan+Advanced QTP Guide

Navigation: View menu >missing resources (for launching and closing)

6) Information

This pane shows syntax errors automatically during saving the test.

Navigation: view menu> information

QTP Tool Window-Information Pane

7) QTP Commands

QTP Commands are available in 3 ways.

www.pavanworld.net 12

Page 13: Pavan+Advanced QTP Guide

1. Menu options2. Tool Bar options3. 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

Page 14: Pavan+Advanced QTP Guide

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.

III) QTP Testing ProcessPlanning

www.pavanworld.net 14

Page 15: Pavan+Advanced QTP Guide

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

o Tests Running through framework

o Scheduled Execution

Analyzing Results

www.pavanworld.net 15

Page 16: Pavan+Advanced QTP Guide

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

Analyzing the AUT

Before we begin creating a test, we need to analyze our application and determine our testing needs.

First, determine the development environments in which our application controls were developed, such as Web, Java, or .NET, so that we can load the required QuickTest add-ins.

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.

Recording and Running:

In QTP there are 3 recording modes available for preparing Tests.

1. Normal Recording

www.pavanworld.net 16

Page 17: Pavan+Advanced QTP Guide

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.

During recording QTP generates VbScript statements in Test Pane, Simultaneously it stores objects information into object repository.

Navigation: Automation>RecordOr Select Record option on automation toolbarOrUse short cut key (F3)

Steps for preparing a Test (through Recording):

1. Put AUT in base state 2. Select Record Option3. It shows Record and Run Settings, Select type of Environment (Windows or

Web)4. Select Record Option

(It shows two Options :1. Record and Run Test on any open window based applications2. Record and Run only on

If we select first option it records on any opened application on Desktop.If we select Second option, it asks for the path of the AUT, After Providing the path it records only on that particular application.)

5. Click OK6. Perform actions on AUT7. 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:

1. Keep tool under recording mode2. Automation >Analog Recording ORUse Short cut Key (Shift + ALT+F3)

Steps for preparing a TEST (through Analog Recording):

1. Launch AUT (or we can launch AUT through QTP)2. Select Record option 3. Automation>Analog Recording4. Analog Recording Settings Dialog box opens

www.pavanworld.net 17

Page 18: Pavan+Advanced QTP Guide

(In this Dialog box two options available.

1. Record relative to the screen2. Record relative to the following window

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

3. Low Level Recording

It records some operations on Non-supported environments apart from Normal operations.

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 mode2. Automation >Low Level Recording

Steps for preparing a TEST (through Low Level Recording):

1) Launch AUT (or we can launch AUT through QTP)

2) Select Record option

3) Automation> Low Level Recording

4) Perform options on AUT

5) Stop Recording

6) Save the Test

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:

www.pavanworld.net 18

Page 19: Pavan+Advanced QTP Guide

Object is something, which has structure and properties.

Software objects:

We call windows, WebPages, buttons, edit boxes, check boxes etc.. as software objects.

Types of Object in QTP:

There are four types of object available in QTP.

1. Run time objects2. Test objects3. Utility objects4. Automation objects/User defined 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

windows Environment

Test objects in VB Environment

Test objects in web Environment

buttons WinButton VBButton WebButtonEdit box WinEdit VBEdit WebEditCheck 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.3. Services for inserting transaction points 4. Environment for using environment variables

Automation objects/User defined objects

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.

There are two types of repository available in QTP.1. Local repository (.MTR extension)2. Shared repository(.TSR extension)

Local Repository:

www.pavanworld.net 19

Page 20: Pavan+Advanced QTP Guide

QTP creates a Local Repository for every action automatically during Recording. That cannot be shared among tests.

User can add some more objects to Local repository

User can perform rename, delete operations in local repository. As it is QTP internal file user no need to save modifications.

Navigation: Resource menu>object repository (Short cut key Ctrl+R)

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.

Operations on Object Repository

Adding objects

www.pavanworld.net 20

Page 21: Pavan+Advanced QTP Guide

a. Local Repository:

Navigation: open local repository (resource menu>object repository)>objects>Add objects to Local>show the object>click ok(No need to save separately, it saves automatically)

B. Shared Repository:

Navigation: Resource menu>object repository manager>object>Add objects>show the window/object>click ok

o Selected object onlyo Default object typeso All objects typeso 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:

Resources >object repository manager>file>open>browse path of the repository file >file>enable editing>select object &Right click>choose rename option>modify the name > release mouse>save the file & close repository manager.

Deleting objects

a. Local Repository:

Resources > object repository >select object and right click >choose delete option >confirm deletion>. >close repository

b. Shared Repository:

Resources >object repository manager>file>open>browse path of the repository file >file>enable editing>select object &Right click>choose delete option>confirm the deletion >save the file & close repository manager.

Associating objects repositories to an action

Resources>Associate repositories>click add icon (+)>browse path of the repository>Associate with an action>click ok

Merging Repositories

www.pavanworld.net 21

Page 22: Pavan+Advanced QTP Guide

Resources > object repository manager>tools>object repository merge tool >browse path of the first repository> browse path of the second repository>click ok>click close>save the merged repository>close the repository manager.

Note: After merging also, source repository files will be available, if we do not want source files we can delete.

Defining new test objects

Navigation: Object>Define new test object >Select Environment>Select Class of the object>Enter name of the object>Click Add>click close>Select object >select property name>enter value (like this select one by one properties and enter values)>save

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.

Navigation>Tools>object spy>take hand icon & Show the object>get information (Object Spy shows the specific objects all available properties with their values)

Note: As Object spy is an important feature, it can be available in 3 Areas.(1. In tools Menu 2. In local repository 3. In Repository manager)

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.

Exporting Repository to an XML file

We can export our repository file to an xml file.

Navigation: File >export Test objects to XML Enter the file name and Save with xml extension.

Importing Repository from XML file

We can import XML file to our repository.

Navigation: File>import from XML >browse path of the XML file >it loads objects.

www.pavanworld.net 22

Page 23: Pavan+Advanced QTP Guide

Note: The purpose of this feature is Editing objects information outside of the QTP

Descriptive ProgrammingEntering / Providing objects information directly into the test script is called Descriptive Programming.

In this method of script creation, we no need to have Object Repositories.

Advantages:

a) Descriptive Programming based Test scripts are faster in execution than Repository based Test scripts.

b) Scripts are portable (we can run these scripts from any machine easily)

c) Maintenance is easy (less amount of resources)

d) We can start Test Execution process even though Application is not ready.

Descriptive programming is basically 2 types.

1. Static Programming2. 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").Activatedialog("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 Objects2. text, attached text - Property names3. Login, Agent Name:, Password:, OK - Property values or Logical Names of the

Object4. 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 23

Page 24: Pavan+Advanced QTP Guide

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:

Const Login="text:=Login", Agent="attached text:=Agent Name:"

Const Pwd ="attached text:=Password:", Ok="text:=OK"

Note: we can declare no of Constants in a line by separating with Camas (,), if we take other line then we have to use Const Statement again.

Creating a Library file

Place Constants in Notepad and save as .vbs file

Associate the Library file to QTP (File->Settings->Resources-> Click add (+) icon-> Browse path of the Library file->Click Apply and click Ok buttons

Otherwise, we can load the library file during run-time

Syntax:

ExecuteFile “Path of the Library file(.vbs)”

After that create the Test Script using Constants

Creating the Test Script using Constants:

Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog(Login).ActivateDialog(Login).Winedit(Agent).Set "asdf"Dialog(Login).Winedit(Pwd").Set "mercury"Dialog(Login).Winbutton(Ok).Click

Advantages:

If we maintain Object Information in the centralized location, then we can handle modifications easily.-------------------------------------------------------------------

www.pavanworld.net 24

Page 25: Pavan+Advanced QTP Guide

Dynamic Programming

In this style of script generation, first we create description objects, provide properties information and use description objects in the test script.

Creating Properties Collection Objects

Set oLogin=description.CreateSet oAgent=description.CreateSet oPassword=description.CreateSet oOk=description.Create

Entering Properties Information into Objects

oLogin("text").value="Login"oLogin("width").value=320oLogin("height").value=204oAgent("attached text").value="Agent Name:"oPassword("attached text").value="Password:"oOk("text").value="OK"

Generating Tests using Properties collection Objects

Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog(oLogin).ActivateDialog(oLogin).Winedit(oAgent).Set "asdf"Dialog(oLogin).Winedit(oPassword).Set "mercury"Dialog(oLogin).Winbutton(oOK).Click

Note1: Create Description objects and put into one library file, by associating that library file, we can generate tests.

Note2: Dynamic programming is some difficult in preparation than static programming but maintenance is very easy.

----------------------------------------------------In this style of script creation also, we can maintain Objects information in the Centralized location by putting collection objects in a Library file.

----------------------------------------------------

Methods or Operations

Activate: It activates dialog boxes/Windows

www.pavanworld.net 25

Page 26: Pavan+Advanced QTP Guide

Syntax: Object hierarchy. Activate

Ex: Dialog(“Login”).ActivateWindow(“Flight Reservation”).Activate

Click Method: It clicks on an object (Buttons)Syntax: Object hierarchy. ClickEx: Dialog(“Login”).Winbutton(“ok”).click

Close Method: It closes the window,Dialog box, Browser window etc.

Syntax: Object hierarchy. Close

Ex:

Window(“Flight Reservation”).CloseBrowser(“Browser”).Close

DBL CLICK: It Double clicks the object.

Set Method: It can be used in three ways.

a. For setting the value of an edit boxSyntax: Object Hierarchy. SET “Value”Ex: Dialog (“Login”).WinEdit(“Agent Name”).Set “asdf”

b. Selecting a Radio ButtonSyntax: Object Hierarchy. SetEx: Window("Flight Reservation").WinRadioButton("Business").Set

c. Selecting/Deselecting check boxesSyntax:object Hierarchy.Set “ON/off”

Ex: Window ("Flight Reservation"). Dialog("Open Order").WinCheckBox("Order No.").Set "ON"

Select Method:

It is used for selecting an item from a combo box or list box.Syntax: Object hierarchy.select “item”

Ex:

A. Window("Flight Reservation").WinComboBox("Fly From:").Select "London"B. Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select "12572

GetVisibletext: It returns Text from the specified area.

www.pavanworld.net 26

Page 27: Pavan+Advanced QTP Guide

Syntax: Variable =object hierarchy.getvisibletext

Ex:x=Window("Flight Reservation").WinComboBox("Fly From:").GetVisibleTextmsgbox 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"

Getitemscount: It returns number of items in a combobox.

Syntax: Variable=object hierarchy.getitemscountEx: x=Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCountmsgbox x

Getcontent: It returns all items from a combobox.Syntax: variable=object hierarchy.GetContentEx: x=Window("Flight Reservation").WinComboBox("Fly From:").GetContentmsgbox x

Exist property: It checks whether the object is available or not.Syntax: Object hierarchy.exist(time in seconds)Ex: Window("Flight Reservation").Exist(5)

Enhancing Tests

www.pavanworld.net 27

Page 28: Pavan+Advanced QTP Guide

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.

1. Inserting Check Points

2. Inserting Output Values

3. Adding Comments

4. Inserting Flow Control Statements

5. Synchronization

6. Parameterization

7. Generating Steps through Step Generator

8. Inserting Transaction Points:(Start and End)

Inserting CheckpointsCheck point is a verification point, it takes expected result from the user and compares with actual results during execution and provides test results.

There are 11 Checkpoints available in QTP:

1. Standard check point

2. Text check point

3. Text area check point

4. Bit map check point

5. Data base check point

6. Accessibility check point

7. XML Check point (from Application)

8. XML Check point (from Resource)

9. Page check point

10. Image checkpoint

11. Table checkpoint

Note 1: From 6 to 11 checkpoints are only for Web.

Note 2: From 9 to 11 checkpoints are hidden checkpoints, we can insert these checkpoints through standard checkpoint.

1. Standard Checkpoint:

www.pavanworld.net 28

Page 29: Pavan+Advanced QTP Guide

It checks object property values. We can use this checkpoint for checking any property value.

Navigation for Inserting standard checkpoint

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.

Navigation for Editing standard checkpoint

Select Checkpoint statement and right click > choose checkpoint properties option > modify the value > click Ok.

Navigation for Deleting standard checkpoint:

Select Checkpoint statements and right click > choose delete option.

Inserting Standard check points through active screen:

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.

Note: We can insert standard checkpoints in 3 ways.

1. Through expert view,

2. Through keyword view,

3. Through Active screen.

2) Text Checkpoint:

It Checks object’s text property value in different ways.

Navigation: Keep tool under Recording mode >Insert menu > checkpoint > Text checkpoint > Show the object > click ok > Select options

(Match case; ignore spaces, exact match, text not displayed.)

We can select one or more options > click ok & stop Recording.

3) Text Area Checkpoint:

It checks the text area present in the application.

Navigation:

www.pavanworld.net 29

Page 30: Pavan+Advanced QTP Guide

Keep tool under Recording mode > Insert menu> Checkpoint > Text area checkpoint > Mark the area of text > select one or more options

(Match case, ignore spaces, exact match, text not displayed.)

Click ok and stop recording.

4. Bitmap checkpoint:

It compares bitmaps; we can compare complete bitmaps as well as part of the bitmaps.

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:

It checks Content of the back end Database.

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.

6. Accessibility check point:

It checks whether the webpage in our web application is developed according to W3C (World Wide Web consortium) Rules and Regulations or not.

It is a configurable checkpoint, according to our requirements, we can customize.

Configuring accessibility checkpoint:

Tools menu> options >web > advanced > check/uncheck items > click apply > click ok

Invigilation: 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.

www.pavanworld.net 30

Page 31: Pavan+Advanced QTP Guide

c) If an item is not available then result would be pass

7. XML Check point (from Application)

It checks content of the XML file.

Navigation: Keep tool under Recording mode in web environment > insert menu > checkpoint (from application)> show the xml pages >click ok > stop Recording.

8. XML Check point (from Resource)

It checks content of the XML file.

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:

It checks number of Links, Images and Loading time in a web page.

It is a hidden checkpoint; we can insert this through standard 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.

10.Image checkpoint:

It checks Image property values.

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.

11.Table checkpoint:

It checks content of the web tables.

Navigation: Keep tool under Recording mode under web environment > Insert menu > checkpoint > standard checkpoint >show the web table > click ok >stop recording.

www.pavanworld.net 31

Page 32: Pavan+Advanced QTP Guide

Inserting Output Values

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.

Types of Output Values:

1. Standard output value

2. Text output value

3. Text area output value

4. Database output value

5. XML output value (From Application)

6. XML output value (From Resource)

1) Standard output value:

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.

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.

www.pavanworld.net 32

Page 33: Pavan+Advanced QTP Guide

3) Text Area output value:

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..

4) Database output value:

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.

5) XML output value (from application):

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.

6) XML output Value (From Resource):

We can use XML output values to output the values of XML elements in XML documents.

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:

o For making the script understandableo For making the Script Disable from execution

www.pavanworld.net 33

Page 34: Pavan+Advanced QTP Guide

Syntax:

1. Use Apostrophe (‘) before the statement 2. Use REM Command with single space before the statement

Comment a Block of Statements: Navigation: Select block of statements > Edit menu> Advanced> Comment block

OrAfter selecting block of statements use shortcut key Ctrl+M

Uncomment a block of statements:

Navigation: Select comment block>Edit menu> Advanced>Uncomment block

OrAfter selecting comment block, Use shortcut key ctrl+shift+M

Inserting Flow Control Statements

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

It is a process of matching the speeds of both QTP and AUT in order to get proper execution and results.

Where Synchronization is required:

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.

There are several methods available in QTP for synchronization.

1. Inserting Wait statements.

2. Inserting Synchronization points.

www.pavanworld.net 34

Page 35: Pavan+Advanced QTP Guide

3. Increasing Tool default synchronization time.

4. Sync Method (Only for WEB)

5. Exist Property

Inserting Wait Statements:

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.

Inserting Synchronization point:

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.

Note: if we insert Synchronization points, it does not wait up to maximum time, after completion of the current operations, it goes to next step immediately.

Syntax: object hierarchy.waitproperty “property name”,value,time in milli seconds.

Increasing Tool default synchronization time:

Navigation: File>settings>run tab>increase object synchronization time out>apply>ok

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.

Sync Method: (only for WEB)

Waits for the browser to complete current navigation.

Syntax: Object Hirearchy.Sync

Ex: Browser("Yahoo! Toolbar").Page("Yahoo! Toolbar").Sync

Selecting an appropriate Method:

www.pavanworld.net 35

Page 36: Pavan+Advanced QTP Guide

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.

Inserting Transaction Points

We can insert Transaction points for measuring Transaction time.It is a performance concept but QTP supports measuring transaction time per user only.

Syntax: Services.StartTransaction "name of the transaction"-------statements-----------------services.EndTransaction "name of the transaction"Note: We can insert multiple transactions points in a test.

ParameterizationPassing parameters, through this concept we can pass multiple values.

We use parameterization in Data Driven Testing.

Data Driven Testing: Testing the Same operation with multiple sets of test data.

Types of Parameterization:

We can parameterize tests in several ways.

1. Through Loop Statements

2. Dynamic Test Data Submission

3. Through Data Table

4. Fetching Test Data directly from External files (Flat files & Spreadsheets)

5. Fetching Test Data directly from Databases (MS Acess, oracle etc).

6. Getting Test Data from front end objects.

www.pavanworld.net 36

Page 37: Pavan+Advanced QTP Guide

1. Through Loop Statements:

We can use loop statements for passing sequential numbers & Logical Numbers.

Note: We can’t generate Strings.

For orderno=1 to 10 step 1 ' for one increment step keyword is not mandatoryWindow("Flight Reservation").ActivateWindow("Flight Reservation").WinButton("Button").ClickWindow("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ordernoWindow("Flight Reservation").Dialog("Open Order").WinButton("OK").ClickNext

2.Dynamic Test Data Submission:

Through Loop Statements we can give strings also but every time user has to enter data.

For x=1 to 3Agent =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").ActivateDialog("Login").WinEdit("Agent Name:").Set AgentDialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure passwordDialog("Login").WinButton("OK").ClickWindow("Flight Reservation").CloseNext

3. Through Data Table:

QTP adds one data table (Spreadsheet) for every test, we can use Data Table for Data Driven Testing.

It has 3 types of usage

a. Entering test data directly into data table and use

b. Importing test data from external Flat files

c. Importing test data from external Spread sheets

d. Importing test data from Data bases.

A. Entering test data directly into data table and use.

Steps: Generate the basic test>open data table(View>Data Table)

www.pavanworld.net 37

Page 38: Pavan+Advanced QTP Guide

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

(variable=datatable(“column name”, Sheet id)Example: agent=datatable(“agent”,1)

Pass parameters.)

Run the test.

Agent = Datatable("Agent",1)pwd=Datatable ("Password",1)invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set AgentDialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure pwdDialog("Login").WinButton("OK").ClickWindow("Flight Reservation").Close

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.

c. Importing test data from external Spread sheets:

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).

Start programs>MS Office>MS Access>file >new>Select blank Database>enter name of the database>Save with mdb extension.

Creating Tables: Select Create table in design view>Enter field name(Agent)and Select data type(text) Like this we can create number of fields>save&enter table name.

www.pavanworld.net 38

Page 39: Pavan+Advanced QTP Guide

Entering Data into Tables: Select table>enter the data.

Creating DSN & importing data

Navigation: view>data table>Place mouse pointer on Data table>sheet>import>from database(Database query wizard opens)>choose ‘specify SQL statements manually>click next >click create>click new>select driver type>click next >browse path to store> enter DSN Name>Click Save>click next>click finish>select>browse the database& select>click ok>click ok>select DSN>click ok>enter SQL statement (select *from login)>click finish.

Note: DSN Creation is one time activity, by using the DSN we can get data for number of tests.

4. Fetching Test Data directly from Flat files

5). Fetching Test Data directly from Excel Sheets

6) Fetching Test Data directly from Databases

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.

Types of Environment variables:

1. Built in variables: These are system defined variables, we can access from all tests but these are designed as read only.

2. User defined variables: Variables that we predefine in the active external environment variables file. We can create as many files as we want and we can change values of variables.

Usage of environment variables:

Syntax: Variable = Environment(“environment variable name”)

Ex: 

X=Environment (“ActionName”)Msgbox x

Example Script: 

ProductDir =environment ("ProductDir")app= "\samples\flight\app\flight4a.exe"Systemutil.Run ProductDir & appDialog("Login").Activate

www.pavanworld.net 39

Page 40: Pavan+Advanced QTP Guide

Dialog("Login").WinEdit("Agent Name:").Set "pavan"Dialog("Login").WinEdit("Password:").SetSecure "4b3c86f2107ff565cc195ba6c24739091b656407"Dialog("Login").WinButton("OK").Click

Creating user defined environment variables:

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.

Associating environment variable file:

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 

We can load environment file directly 

Environment.loadfromfile”path of the xml file”

Usage of user defined Environment variables:

Associate environment file to current test:Variable = Environment (“Variable Name”)

X=environment (“city”)Msgbox x

Modifying Environment files:

Select XML file>open with notepad>modify the values>Save.

www.pavanworld.net 40

Page 41: Pavan+Advanced QTP Guide

ActionsAction: A Set of Statements for performing a Task or Tasks.

We divide our test into actions to streamline the process of testing.

Purpose of Actions:

For better understandability

For reusing components

Types of Actions:

1) Non Re usable actions2) Re usable actions3) External actions

Operations on Actions:

• Creating Actions

• Splitting Actions

• Renaming Actions

• Deleting Actions

• Calling an Action

• Copying an Action

• Making an Action Reusable/Non Reusable

www.pavanworld.net 41

Page 42: Pavan+Advanced QTP Guide

Creating an Action: Insert>call to new action>enter name of the action>click okSteps:

1. Create required actions(ex login, insert,delte)2. Prepare Scripts for those actions.

Splitting an action:

Navigation: Place cursor in desired location>Edit menu>action>split action>Enter Action 1 name & action 2 name.

Steps:

1. Generate total test in the default action2. Split into meaningful actions.

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.

Note: U can’t edit

Copying an action: Insert>call to copy of action>browse path of the test>select desired action>click ok.

Note: we can edit this action.

Making an action reusable: Select Non Reusable action >edit >action>action properties>check reusable action check box >click ok.

www.pavanworld.net 42

Page 43: Pavan+Advanced QTP Guide

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 43

Page 44: Pavan+Advanced QTP Guide

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.

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.

1.1 Windows Script Host (WSH)

It is a Windows administration tool. WSH creates an environment for hosting scripts. That is, when a script arrives at your computer, WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine

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.2 Creating a script with Notepad

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.

www.pavanworld.net 44

Page 45: Pavan+Advanced QTP Guide

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"

1.3 Hosting Environments and Script Engines

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.

1.4 Available Script Engines

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 45

Page 46: Pavan+Advanced QTP Guide

2.0 Comments

The comment argument is the text of any comment we want to include.

2.0 Purpose of comments:

o We can use comments for making the script understandable.o We can use comments for making one or more statements disable from

execution.

2.1 Syntax

Rem comment (After the Rem keyword, a space is required before comment.) Or

Apostrophe (') symbol before the comment

2.2 Comment/Uncomment a block of statements

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 46

Page 47: Pavan+Advanced QTP Guide

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.

3.1 Declaring Variables

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:

Dim x, Top, Bottom, Left, Right

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.

3.2 Option Explicit

Forces explicit declaration of all variables in a script.

Option Explicit ' Force explicit variable declaration.Dim MyVar ' Declare variable.MyInt = 10 ' Undeclared variable generates error.MyVar = 10 ' Declared variable does not generate error.

3.3 Naming Restrictions for Variables

Variable names follow the standard rules for naming anything in VBScript. A variable name:

www.pavanworld.net 47

Page 48: Pavan+Advanced QTP Guide

Must begin with an alphabetic character. Cannot contain an embedded period. Must not exceed 255 characters. Must be unique in the scope in which it is declared.

3.4 Scope of Variables

o A variable's scope is determined by where you declare it.

o When we declare a variable within a procedure, only code within that procedure can access or change the value of that variable

o If we declare a variable outside a procedure, we make it recognizable to all the procedures in our script. This is a script-level variable, and it has script-level scope.

3.5 Life Time of Variables

o The lifetime of a variable depends on how long it exists.

o The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running.

o At procedure level, a variable exists only as long as you are in the procedure.

3.6 Assigning Values to Variables

Values are assigned to variables creating an expression as follows:

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 = 200City = “Hyderabad”

3.7 Scalar Variables and Array Variables

A variable containing a single value is a scalar variable.

A variable containing a series of values, is called an array variable.

Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name.

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.

www.pavanworld.net 48

Page 49: Pavan+Advanced QTP Guide

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) = 256A(1) = 324A(2) = 100A(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 the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns:

Dim MyTable(5, 10)

In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns.

3.8 Dynamic Arrays

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.

www.pavanworld.net 49

Page 50: Pavan+Advanced QTP Guide

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) ReDim Preserve MyArray(30)

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.

4.0 VB Script Data Types

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.

4.1 Variant Subtypes

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.

NullVariant 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

www.pavanworld.net 50

Page 51: Pavan+Advanced QTP Guide

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.

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.

5.0 VB Script Operators

Operators are used for performing mathematical, comparison and logical operations.

VBScript has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators.

4.1 Operator Precedence

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.

4.2 Arithmetic Operators:

Operator Description1) 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 51

Page 52: Pavan+Advanced QTP Guide

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.

4.3 Comparison Operators

Used to compare expressions.

Operator Description Operator Description1) = Equal to 5) <= Less than or equal to2) <> Not equal to 6) >= Greater than or equal to3) < Less than 7) Is Object equivalence4) > Grater than

4.4 Concatenation Operators

Operator Description1) Addition Operator (+)

Sums two numbers.

If Then1) Both expressions are numeric Add.2) Both expressions are strings Concatenate.3) One expression is numeric and the other is a string

Add.

2) Concatenation Operator (&)

Forces string concatenation of two expressions.

4.5 Logical Operators

Operator Description Syntax1) Not Performs logical negation on an

expression.result= Not expression

2) And Performs a logical conjunction on two expressions.

result= expression1 And expression2

3) Or Performs a logical disjunction on two expressions.

result= expression1 Or expression2

4) Xor Performs a logical exclusion on two expressions.

result= expression1 Xor expression2

5) EqvPerforms a logical equivalence on two expressions.

result= expression1 Eqv expression2

6) ImpPerforms a logical implication on two expressions.

result= expression1 Imp expression2

6) Input/Output Operations

www.pavanworld.net 52

Page 53: Pavan+Advanced QTP Guide

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 InputInput = InputBox("Enter your name") MsgBox ("You entered: " & Input)

6.2 MsgBox Function

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 MyVarMyVar = 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.

7.1 Creating Constants

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

Declares constants for use in place of literal values.

Example:

Const MyString = "This is my string."Const MyAge = 49Const CutoffDate = #6-1-97#

Note that String literal is enclosed in quotation marks (" ").

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:

Const price= 100, city= “Hyderabad”, x= 27

8) Conditional Statements

www.pavanworld.net 53

Page 54: Pavan+Advanced QTP Guide

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

2) Select Case Statement

8.1 Making Decisions Using If...Then...ElseThe If...Then...Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another.

If...Then...Else statements can be nested to as many levels as you need.

8.1.1 Running a Statements if a Condition is True (single statement) To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement.

Dim myDate myDate = #2/13/98# If myDate < Now Then myDate = Now

8.1.2 Running Statements if a Condition is True (multiple statements)

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 xx= 20If x>10 Then

msgbox "Hello G.C.Reddy"msgbox "x value is: "&xmsgbox "Bye Bye"

End If

8.1.3 Running Certain Statements if a Condition is True and Running Others if a Condition is False

We can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False.

Example:

Dim xx= Inputbox (" Enter a value")If x>100 Then

Msgbox "Hello G.C.Reddy"

www.pavanworld.net 54

Page 55: Pavan+Advanced QTP Guide

Msgbox "X is a Big Number"Msgbox "X value is: "&X

Else Msgbox "GCR"

Msgbox "X is a Small Number" Msgbox "X value is: "&XEnd If

8.1.4 Deciding Between Several Alternatives

A variation on the If...Then...Else statement allows us to choose from several alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else statement so we can control program flow based on different possibilities.

Example:

Dim xx= Inputbox (" Enter a value")

If x>0 and x<=100 ThenMsgbox "Hello G.C.Reddy"Msgbox "X is a Small Number"Msgbox "X value is "&x

Else IF x>100 and x<=500 ThenMsgbox "Hello GCR"

Msgbox "X is a Medium Number"

Else IF x>500 and x<=1000 Then Msgbox "Hello Chandra Mohan Reddy" Msgbox "X is a Large Number"

Else Msgbox "Hello Sir"Msgbox "X is a Grand Number"

End IfEnd IfEnd If

8.1.5 Executing a certain block of statements when two / more conditions are True (Nested If...)

Example:

Dim State, RegionState=Inputbox ("Enter a State")Region=Inputbox ("Enter a Region")

If state= "AP" ThenIf Region= "Telangana" Then

msgbox "Hello G.C.Reddy"msgbox "Dist count is 10"

Else if Region= "Rayalasema" Then

www.pavanworld.net 55

Page 56: Pavan+Advanced QTP Guide

msgbox "Hello GCR"msgbox "Dist count is 4"

Else If Region= "Costal" Thenmsgbox "Hello Chandra mohan Reddy"msgbox "Dist count is 9"

End IfEnd IfEnd IfEnd If

8.2 Making Decisions with Select Case

The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable.

Example:

Option explicit Dim x,y, Operation, Result x= Inputbox (" Enter x value")y= Inputbox ("Enter y value")Operation= Inputbox ("Enter an Operation")

Select Case 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-yMsgbox "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 yMsgbox "Hello G.C.Reddy"Msgbox "Mod of x,y values is "&Result

www.pavanworld.net 56

Page 57: Pavan+Advanced QTP Guide

Case "expo" Result= x^y

Msgbox "Hello G.C.Reddy"Msgbox"Exponentation of x,y values is "&Result

Case ElseMsgbox "Hello G.C.Reddy"msgbox "Wrong Operation"

End Select

8.3 Other Examples

8.3.1 Write a program for finding out whether the given year is a leap year or not?

Dim xyearxyear=inputbox ("Enter Year")

If xyear mod 4=0 Thenmsgbox "This is a Leap year"

Else msgbox "This is NOT"End If

8.3.2 Write a program for finding out whether the given number is, Even number or Odd number?

Dim numnum=inputbox ("Enter a number")

If num mod 2=0 Thenmsgbox "This is a Even Number"

Else msgbox "This is a Odd Number"End If

8.3.3 Read two numbers and display the sum?

Dim num1,num2, sumnum1=inputbox ("Enter num1")num2=inputbox ("Enter num2")

sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require

msgbox ("Sum is " &sum)

8.3.4 Read P,T,R values and Calculate the Simple Interest?

Dim p,t, r, sip=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 interestmsgbox ("Simple Interest is " &si)

www.pavanworld.net 57

Page 58: Pavan+Advanced QTP Guide

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, sumnum=inputbox ("Enter a Four digit number")If Len(num) = 4 Thensum=0

sum=sum+num mod 10num=num/10num= left (num, 3)

sum=sum+num mod 10num=num/10num= left (num, 2)

sum=sum+num mod 10num=num/10num= left (num, 1)

sum=sum+num mod 10 msgbox ("Sum is " &sum)else msgbox "Number, you entered is not a 4 digit number"End If8.3.6 Read any Four digit number and display the number in reverse order?

Dim num,revnum= inputbox("Enter a number")If len(num)=4 Then

rev=rev*10 + num mod 10num=num/10num= left(num,3)

rev=rev*10 + num mod 10num=num/10num= left(num,2)

rev=rev*10 + num mod 10num=num/10num= left(num,1)

rev=rev*10 + num mod 10

msgbox "Reverse Order of the number is "&revElse

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 Distinctionb) If average marks Greater than or equal to 60 and less than 75 , then grade is Firstc) If average marks Greater than or equal to 50 and less than 60 , then

www.pavanworld.net 58

Page 59: Pavan+Advanced QTP Guide

grade is Secondd) If average marks Greater than or equal to 40 and less than 50 , then grade is Thirde) Minimum marks 35 for any subject, otherwise 'no grade fail')

Dim e,m,p,c, tote=inputbox ("Enter english Marks")m=inputbox ("Enter maths Marks")p=inputbox ("Enter physics Marks")c=inputbox ("Enter chemistry Marks")

tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c)msgbox tot

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 IfEnd IfEnd IfEnd If

8.3.8 Display Odd numbers up to n?

Dim num,nn=Inputbox ("Enter a Vaule")For num= 1 to n step 2msgbox numNext

8.3.9 Display Even numbers up to n?

Dim num,nn=Inputbox ("Enter a Vaule")For num= 2 to n step 2msgbox numNext

www.pavanworld.net 59

Page 60: Pavan+Advanced QTP Guide

8.3.10 display natural numers up to n and write in a text file?

Dim num, n, fso, myfilen= inputbox ("Enter any Value")num=1For num= 1 to n step 1Set fso= createobject ("scripting.filesystemobject")set myfile=fso.opentextfile ("E:\gcr.txt", 8, true)myfile.writeline nummyfile.closeNext

8.11 Display Natural numbers in reverse order up to n?

Dim num,nn=Inputbox ("Enter a Vaule")For num=n to 1 step -1msgbox numNext

8.12 Display Natural numbers sum up to n? (using For...Next Loop)

Dim num, n, sumn= inputbox ("Enter a Value")sum=0For num= 1 to n step 1

sum= sum+numNext

msgbox sum

8.13 Display Natural numbers sum up to n? (using While...Wend Loop)

Dim num, n, sumn= inputbox ("Enter a Value")While num <=cdbl (n)

sum= sum+numnum=num+1

Wendmsgbox sum

8.14 Display Natural numbers sum up to n? (using Do...Until...Loop)

Dim num, n, sumn= inputbox ("Enter a Value")sum=0num=1Do

sum= sum+numnum=num+1

Loop Until num =cdbl (n+1)msgbox sum

8.15 Write a Function for Natural Numbers sum up to n?

www.pavanworld.net 60

Page 61: Pavan+Advanced QTP Guide

Function NNumCou (n)Dim num, sumsum=0For num= 1 to n step 1

sum= sum+numNextmsgbox sumEnd Function

8.16 Verify weather the entered 10 digit value is a numeric value or not? Dim a,x,y,z,numnum=Inputbox ("Enter a Phone Number")

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"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,numnum=Inputbox ("Enter a Phone Number")

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 len (num) =10 Then If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True"

www.pavanworld.net 61

Page 62: Pavan+Advanced QTP Guide

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 IfEnd If

If len (num) <> 10 Then Msgbox "It is NOT valid Number "End If

9) Looping Through Code

o Looping allows us to run a group of statements repeatedly.

o Some loops repeat statements until a condition is False;

o Others repeat statements until a condition is True.

o There are also loops that repeat statements a specific number of times.

The following looping statements are available in VBScript:

Do...Loop : Loops while or until a condition is True. While...Wend : Loops while a condition is True. For...Next : Uses a counter to run statements a specified number of times.

www.pavanworld.net 62

Page 63: Pavan+Advanced QTP Guide

For Each...Next : Repeats a group of statements for each item in a collection or each element of an array.

9.1 Using Do LoopsWe can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.

9.1.1 Repeating Statements While a Condition is True

Repeats a block of statements while a condition is True or until a condition becomes True

a) Do While condition Statements    ----------- ----------- Loop

Or, we can use this below syntax:

Example:

Dim xDo While x<5 x=x+1

Msgbox "Hello G.C.Reddy"Msgbox "Hello QTP"

Loop

b) Do Statements    ----------- ----------- Loop While condition

Example:

Dim xx=1Do Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" x=x+1Loop While x<5

9.1.2 Repeating a Statement Until a Condition Becomes True

c) Do Until condition Statements    ----------- ----------- Loop

www.pavanworld.net 63

Page 64: Pavan+Advanced QTP Guide

Or, we can use this below syntax:

Example:

Dim xDo Until x=5 x=x+1 Msgbox "G.C.Reddy" Msgbox "Hello QTP"Loop

Or, we can use this below syntax:

d) Do Statements    ----------- ----------- Loop Until condition

Or, we can use this below syntax:

Example:

Dim xx=1Do Msgbox “Hello G.C.Reddy” Msgbox "Hello QTP" x=x+1Loop Until x=5

9.2 While...Wend Statement

Executes a series of statements as long as a given condition is True.

Syntax:While condition Statements    ----------- -----------WendExample:Dim xx=0 While x<5 x=x+1

msgbox "Hello G.C.Reddy"msgbox "Hello QTP"

Wend

9.3 For...Next Statement

Repeats a group of statements a specified number of times.

www.pavanworld.net 64

Page 65: Pavan+Advanced QTP Guide

Syntax:

For counter = start to end [Step step]

       statements

Next

Example:

Dim x

For x= 1 to 5 step 1

Msgbox "Hello G.C.Reddy"

Next

9.4 For Each...Next Statement

Repeats a group of statements for each element in an array or collection.

Syntax:

For Each item In array

       Statements

Next

Example:Dim a,b,x (3)a=20b=30x(0)= "Addition is "& a+b x(1)="Substraction is " & a-bx(2)= "Multiplication is " & a*bx(3)= "Division is " & a/b

For Each element In x msgbox elementNext

Example:

MyArray = Array("one","two","three","four","five")For Each element In MyArray       msgbox elementNext

www.pavanworld.net 65

Page 66: Pavan+Advanced QTP Guide

10) VB Script Procedures

In VBScript, there are two kinds of procedures; the Sub procedure and the Function procedure.

11.1 Sub Procedures

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:

Sub Procedure name ()

Statements

-----------

-----------

End Sub

Or

Sub Procedure name (argument1, argument2)

Statements

-----------

-----------

End Sub

Example: 1

Sub ConvertTemp()

temp = InputBox("Please enter the temperature in degrees F.", 1)

MsgBox "The temperature is " & Celsius(temp) & " degrees C."

End Sub

www.pavanworld.net 66

Page 67: Pavan+Advanced QTP Guide

Example: 2

11.2 Function Procedures

A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements.

A Function procedure is similar to a Sub procedure, but can also return a value.

A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure).

If a Function procedure has no arguments, its Function statement must include an empty set of parentheses.

A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.

Syntax:

Function Procedure name ()

Statements

-----------

-----------

End Function

Or

Function Procedure name (argument1, argument2)

Statements

-----------

-----------

End Function

Example: 1

Function Celsius(fDegrees)

Celsius = (fDegrees - 32) * 5 / 9

End Function

www.pavanworld.net 67

Page 68: Pavan+Advanced QTP Guide

Example: 2

Function cal(a,b,c)

cal = (a+b+c)

End Function

11.3 Getting Data into and out of Procedures

o Each piece of data is passed into our procedures using an argument. o Arguments serve as placeholders for the data we want to pass into our

procedure. We can name our arguments any valid variable name.

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.

o Any arguments are placed inside these parentheses, separated by commas.

11.4 Using Sub and Function Procedures in Code

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.

Call MyProc(firstarg, secondarg)

MyProc firstarg, secondarg

Notice that the parentheses are omitted in the call when the Call statement isn't used.

www.pavanworld.net 68

Page 69: Pavan+Advanced QTP Guide

11) VB Script Built in Functions

1) Asc Function

'Returns ANSI character code corresponding to first letter in a string

Dim val

val="hyderabad"

val=Asc(val)

msgbox val

2) Chr Function

www.pavanworld.net 69

Page 70: Pavan+Advanced QTP Guide

'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

Note: It provide positive value

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

'List of numeric values

www.pavanworld.net 70

Page 71: Pavan+Advanced QTP Guide

var=Array(100,200, 300)

msgbox var(0) 'output: 100

msgbox var(1) 'output: 200

msgbox var(2) 'output: 300

'List of mixed values

var=Array(100,"India", #01-05-2010#)

msgbox var(0) 'output: 100

msgbox var(1) 'output: India

msgbox var(2) 'output: 01/05/2010

6) IsArray Function

It checks weather the given variable is an Array or not

Dim var1, var2,x

'List of strings

var1=Array("Hyderabad","Chennai", "Nellore")

x=isArray(var1) 'It returns True/False like Result

msgbox x

x=isArray(var2)

msgbox x

7) IsDate

It checks weather the given value is Date type data or not

Examples:

Dim myDate,x

myDate=100

x=IsDate(myDate)

msgbox x 'Output: False

myDate="India"

x=IsDate(myDate)

msgbox x 'Output: False

www.pavanworld.net 71

Page 72: Pavan+Advanced QTP Guide

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

It provides difference between two dates, based on interval (day/month)

Dim Date1, Date2,x

Date1=#10-10-2008#

Date2=#10-09-2010#

x=DateDiff("d", date1,date2) 'd for day

msgbox x' It subtracts date1 from date2

x=DateDiff("m", date1,date2)' m for month

msgbox x' It subtracts date1 from date2

x=DateDiff("y", date1,date2) 'it considers days only

msgbox x' It subtracts date1 from date2

Note: through this function, we can day or month wise diffrence only.

9) IsNumeric

www.pavanworld.net 72

Page 73: Pavan+Advanced QTP Guide

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

10) Len Function

It finds legngh of the String

Example:

Dim val,x

val="Hyderabad"

x=Len(val)

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)

www.pavanworld.net 73

Page 74: Pavan+Advanced QTP Guide

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

11) Left Function

Returns a specified number of charectors of a given string from left side

Syntax:

variable=Left(string,Lengh)

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"

www.pavanworld.net 74

Page 75: Pavan+Advanced QTP Guide

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/

12) Right Function

Returns a specified number of charectors of a given string from Right side

Example:

Dim val,x

val="Hyderabad"

x=Right(val,3)

msgbox x ' Output: bad

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)

msgbox x ' Output: /2010

13) Mid function

www.pavanworld.net 75

Page 76: Pavan+Advanced QTP Guide

Returns a specified number of characters of a given string

Example:

Dim val,x

val="Hyderabad"

x=Mid(Val,5,3)

msgbox x ' Output: rab

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

retuns reverse value of a string

Example:

Dim val,x

val="Hyderabad"

x=StrReverse(val)

msgbox x 'Output dabaredyH

val="001"

x=StrReverse(val)

msgbox x 'Output: 100

www.pavanworld.net 76

Page 77: Pavan+Advanced QTP Guide

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

15) StrComp Function

It compares two string (Binary and textual)

If

a) Both are equal, returns 0(zero)

b) String 1 greater than string 2, returns 1(one)

b) String 2 greater than string 1, returns -1

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

www.pavanworld.net 77

Page 78: Pavan+Advanced QTP Guide

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

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

www.pavanworld.net 78

Page 79: Pavan+Advanced QTP Guide

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

17) Ucase function

Coverts Lower case values into Upper case

Example:

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

x=Ucase("HYDERABAD")

msgbox x 'Output HYDERABAD

www.pavanworld.net 79

Page 80: Pavan+Advanced QTP Guide

18) Round Function

Returns the round value of a given value

if value decimal point above .5 it returns, next nearest value, below

.5 returns before integer value.

Example:

Dim num,x

num=14.49

x=Round(num)

msgbox x 'Output: 14

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

19) Trim Function

Returns a copy of string without leading spaces

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

www.pavanworld.net 80

Page 81: Pavan+Advanced QTP Guide

val=" 2#$%^"

x=Trim(val)

msgbox x

x=Len(x)

msgbox x

val=" VB Script "

x=Trim(val)

msgbox x

x=Len(x)

msgbox x

20) Ltrim Function

It removes spaces from left side of a string

Dim val

val=" VB Script"

x=LTrim(val)

msgbox x

x=Len(x)

msgbox x

val="100 "

x=LTrim(val)

msgbox x

x=Len(x)

msgbox x

val=" 2#$%^ "

x=LTrim(val)

msgbox x

x=Len(x)

msgbox x

val=" VB Script "

x=LTrim(val)

www.pavanworld.net 81

Page 82: Pavan+Advanced QTP Guide

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

val=" 100 "

x=RTrim(val)

msgbox x

x=Len(x)

msgbox x

val=" 2#$%^ "

x=RTrim(val)

msgbox x

x=Len(x)

msgbox x

val=" VB Script "

x=RTrim(val)

msgbox x

x=Len(x)

msgbox x

www.pavanworld.net 82

Page 83: Pavan+Advanced QTP Guide

val= 100

x=RTrim(val)

msgbox x

x=Len(x)

msgbox x

22) Split function

Returns a zero-based, one-dimensional array containing a specified number of substrings

Example:

Dim a,b,x

b="VB Script is a Powerful scripting Language"

a=Split(b," ")

x=IsArray(b)

msgbox x 'Output: False

x=IsArray(a)

msgbox x 'Output: True

msgbox a(6) 'Output: Language

b="VB,Script,is,a,Powerful,scripting,Language"

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="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

12) VBScript syntax rules and guidelines

21.1 Case-sensitivity:

www.pavanworld.net 83

Page 84: Pavan+Advanced QTP Guide

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.

For example, the two statements below are identical in VBScript:

Browser("Mercury").Page("Find a Flight:").WebList("toDay").Select "31" browser("mercury").page("find a flight:").weblist("today").select "31"

21.2 Text strings:

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.

Browser("Mercury").Page("Find a Flight:").WaitProperty("items count", Total_Items, 2000)

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.

21.7 Spaces:

We can add extra blank spaces to our script to improve clarity. These spaces are ignored by VBScript.

www.pavanworld.net 84

Page 85: Pavan+Advanced QTP Guide

13) Errors

We have two types Errors in VB Script; they are VBScript Run-time Errors and VBScript Syntax Errors

13.1 VBScript Run-time 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.

13.2 VBScript Syntax Errors

VBScript syntax errors are errors that result when the structure of one of our VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed.

File System OperationsFile 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

www.pavanworld.net 85

Page 86: Pavan+Advanced QTP Guide

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 ExplicitDim objFSO, objFolder, strDirectorystrDirectory = "D:\Pavan"Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFolder = objFSO.CreateFolder(strDirectory)

2) Delete a Folder

Set oFSO = CreateObject("Scripting.FileSystemObject")oFSO.DeleteFolder("E:\Pavan")

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 ExplicitDim objFSO, objFolder, strDirectorystrDirectory = "D:\Pavan"Set objFSO = CreateObject("Scripting.FileSystemObject")If objFSO.FolderExists(strDirectory) ThenSet objFolder = objFSO.GetFolder(strDirectory)msgbox strDirectory & " already created "elseSet objFolder = objFSO.CreateFolder(strDirectory)end if

5) Returning a collection of Disk Drives

Set oFSO = CreateObject("Scripting.FileSystemObject")Set colDrives = oFSO.DrivesFor Each oDrive in colDrivesMsgBox "Drive letter: " & oDrive.DriveLetterNext

6) Getting available space on a Disk Drive

www.pavanworld.net 86

Page 87: Pavan+Advanced QTP Guide

Set oFSO = CreateObject("Scripting.FileSystemObject")Set oDrive = oFSO.GetDrive("C:")MsgBox "Available space: " & oDrive.AvailableSpace

7) Creating a Flat File

Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.CreateTextFile("E:\Pavan.txt")

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) ThenSet objFolder = objFSO.GetFolder(strDirectory)ElseSet objFile = objFSO.CreateTextFile("E:\Pavan.txt")End if

9) Reading Data character by character from a Flat File

Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.OpenTextFile("E:\Pavan.txt", 1)Do Until objFile.AtEndOfStreamstrCharacters = objFile.Read(1)msgbox strCharactersLoop

10) Reading Data line by line from a Flat File

Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.OpenTextFile("E:\Pavan.txt", 1)Do Until objFile.AtEndOfStreamstrCharacters = objFile.Readlinemsgbox strCharactersLoop

11) Reading data from a flat file and using in data driven testing

Dim fso,myfileSet fso=createobject("scripting.filesystemobject")Set myfile= fso.opentextfile ("F:\Pavan.txt",1)myfile.skiplineWhile myfile.atendofline <> True x=myfile.readlines=split (x, ",")

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"Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set s(0)

www.pavanworld.net 87

Page 88: Pavan+Advanced QTP Guide

Dialog("Login").WinEdit("Password:").SetSecure s(1)Dialog("Login").WinButton("OK").ClickWindow("Flight Reservation").CloseWend

12) Writing data to a text file

Dim Stuff, myFSO, WriteStuff, dateStampdateStamp = Date()Stuff = "I am Preparing this script: " &dateStampSet myFSO = CreateObject("Scripting.FileSystemObject")Set WriteStuff = myFSO.OpenTextFile("e:\Pavan.txt", 8, True)WriteStuff.WriteLine(Stuff)WriteStuff.CloseSET WriteStuff = NOTHINGSET myFSO = NOTHING

13) Delete a text file

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) ThenSet objFile = objFSO.Getfile(strDirectory & strFile)objFile.delete ()End if

15) Comparing two text files

Dim f1, f2f1="e:\Pavan1.txt"f2="e:\Pavan2.txt"Public Function CompareFiles (FilePath1, FilePath2)Dim FS, File1, File2Set FS = CreateObject("Scripting.FileSystemObject") If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size ThenCompareFiles = TrueExit FunctionEnd IfSet File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0)Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)CompareFiles = FalseDo While File1.AtEndOfStream = FalseStr1 = File1.Read Str2 = File2.Read CompareFiles = StrComp(Str1, Str2, 0)If CompareFiles <> 0 ThenCompareFiles = TrueExit Do

www.pavanworld.net 88

Page 89: Pavan+Advanced QTP Guide

End IfLoopFile1.Close()File2.Close()End Function Call Comparefiles(f1,f2) If CompareFiles(f1, f2) = False ThenMsgBox "Files are identical."ElseMsgBox "Files are different."End If

16) Counting the number of times a word appears in a file

sFileName="E:\gcr.txt"sString="pavan"Const FOR_READING = 1Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatchesSet oFso = CreateObject("Scripting.FileSystemObject")Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING)sReadTxt = oTxtFile.ReadAllSet oRegEx = New RegExpoRegEx.Pattern = sStringoRegEx.IgnoreCase = bIgnoreCaseoRegEx.Global = TrueSet oMatches = oRegEx.Execute(sReadTxt)MatchesFound = oMatches.CountSet oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothingmsgbox MatchesFound

17) Read a CSV File Using Database Techniques

On Error Resume Next

Const adOpenStatic = 3Const adLockOptimistic = 3Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")

strPathtoTextFile = "C:\Databases\"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _          "Data Source=" & strPathtoTextFile & ";" & _          "Extended Properties=""text;HDR=YES;FMT=Delimited"""

objRecordset.Open "SELECT * FROM PhoneList.csv", _          objConnection, adOpenStatic, adLockOptimistic, adCmdText

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")  

www.pavanworld.net 89

Page 90: Pavan+Advanced QTP Guide

    objRecordset.MoveNextLoop

18) Read a Text File into an Array

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")Set objTextFile = objFSO.OpenTextFile _    ("e:\pavan.txt", ForReading)

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)    NextLoop

Excel File Operations1) Create an Excel file, enter some data and save the file through VB scripting?

1) Dim objexcel2) Set objExcel = createobject("Excel.application")3) objexcel.Visible = True4) objexcel.Workbooks.add5) objexcel.Cells(1, 1).Value = "Testing"6) objexcel.ActiveWorkbook.SaveAs("f:\exceltest.xls")7) objexcel.Quit

2) Data Driven Testing through an External Excel Sheet

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.count5) For i= 1 to Rows_Count6) 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").Activate10) Dialog("Login").WinEdit("Agent Name:").Set Agent

www.pavanworld.net 90

Page 91: Pavan+Advanced QTP Guide

11) Dialog("Login").WinEdit("Password:").SetSecure pwd12) Dialog("Login").WinEdit("Password:").Type micReturn13) Window("Flight Reservation").Close14) Next

3) Compare two excel files

Set objExcel = CreateObject("Excel.Application")objExcel.Visible = TrueSet objWorkbook1= objExcel.Workbooks.Open("E:\pavan1.xls")Set objWorkbook2= objExcel.Workbooks.Open("E:\pavan2.xls")Set objWorksheet1= objWorkbook1.Worksheets(1)Set objWorksheet2= objWorkbook2.Worksheets(1)For Each cell In objWorksheet1.UsedRangeIf cell.Value <> objWorksheet2.Range(cell.Address).Value Thenmsgbox "value is different"Elsemsgbox "value is same"End IfNextobjWorkbook1.closeobjWorkbook2.closeobjExcel.quitset objExcel=nothing

4) Data Driven Testing using Data Table methods

Datatable.AddSheet "pavan"Datatable.ImportSheet "C:\Documents and Settings\Administrator\Desktop\pavan.xls",1,3n=datatable.GetSheet (3).GetRowCountFor i= 1 to nDatatable.SetCurrentRow(i)Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set datatable("agent",3)Dialog("Login").WinEdit("Password:").Set datatable("pwd",3)Dialog("Login").WinButton("OK").ClickWindow("Flight Reservation").CloseNext

Example 2):

Datatable.AddSheet "pavan"Datatable.ImportSheet "C:\Documents and Settings\Administrator\Desktop\pavan.xls",1,3n=datatable.GetSheet (3).GetRowCountFor i= 1 to nDatatable.SetCurrentRow(i)VbWindow("Form1").ActivateVbWindow("Form1").VbEdit("val1").Set datatable("V1",3)VbWindow("Form1").VbEdit("val2").Set datatable("V2",3)

www.pavanworld.net 91

Page 92: Pavan+Advanced QTP Guide

VbWindow("Form1").VbButton("ADD").Clickeres= Datatable.Value ("res",3)ares=VbWindow("Form1").VbEdit("res").GetROProperty ("text")If eres=ares Thendatatable("res",3)=passelsedatatable("res",3)=failEnd IfNext

5) Open an Excel Spreadsheet

Set objExcel = CreateObject("Excel.Application")Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\pavan.xls")

6) Read an Excel Spreadsheet

Set objExcel = CreateObject("Excel.Application")Set objWorkbook = objExcel.Workbooks.Open _("C:\Scripts\New_users.xls")

intRow = 2

Do Until objExcel.Cells(intRow,1).Value = ""Wscript.Echo "CN: " & objExcel.Cells(intRow, 1).ValueWscript.Echo "sAMAccountName: " & objExcel.Cells(intRow, 2).ValueWscript.Echo "GivenName: " & objExcel.Cells(intRow, 3).ValueWscript.Echo "LastName: " & objExcel.Cells(intRow, 4).ValueintRow = intRow + 1Loop

objExcel.Quit

7) Add Formatted Data to a Spreadsheet

Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = TrueobjExcel.Workbooks.AddobjExcel.Cells(1, 1).Value = "Test value"objExcel.Cells(1, 1).Font.Bold = TRUEobjExcel.Cells(1, 1).Font.Size = 24objExcel.Cells(1, 1).Font.ColorIndex = 3

8) Sort an Excel Spreadsheet on Three Different Columns

Const xlAscending = 1Const xlDescending = 2Const xlYes = 1

Set objExcel = CreateObject("Excel.Application")

www.pavanworld.net 92

Page 93: Pavan+Advanced QTP Guide

objExcel.Visible = TrueSet objExcel = CreateObject("Excel.Application")objExcel.Visible = TrueSet objWorkbook = _objExcel.Workbooks.Open("C:\Scripts\Sort_test.xls")

Set objWorksheet = objWorkbook.Worksheets(1)Set objRange = objWorksheet.UsedRange

Set objRange2 = objExcel.Range("A1")Set objRange3 = objExcel.Range("B1")Set objRange4 = objExcel.Range("C1")

objRange.Sort objRange2,xlAscending,objRange3,,xlDescending, _objRange4,xlDescending,xlYes

Database OperationsADO (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 ObjectA command object specifies a specific method we intend to execute on or against the data source accessed by an open connection.

RecordSet Object

The RecordSet object represents a complete set of records from an executed command or from an underlying base table in the database. A key thing to note is that a RecordSet object references only one record at a time as the current record.

Examples

1) Get Test Data from a Database and use in Data Driven Testing (through Scripting)

www.pavanworld.net 93

Page 94: Pavan+Advanced QTP Guide

1) Dim con,rs2) 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",con7) While rs.eof <>True 8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"9) Dialog("Login").Activate10) Dialog("Login").WinEdit("Agent Name:").Set rs.fields ("Agent")11) Dialog("Login").WinEdit("Password:").Set rs.fields ("Password")12) Dialog("Login").WinButton("OK").Click13) Window("Flight Reservation").Close14) rs.movenext15) Wend

2) Exporting Data from a Database to an Excel Sheet

1) Dim con,rs2) 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",con7) 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=111) Do While Not rs.EOF12) b.cells (i,1).value=rs.fields("agent")13) b.cells(i,2).value=rs.fields("password")14) rs.movenext15) i=i+116) Loop17) a.save18) a.close

3) Exporting Data from a Database to a Text fileDim objCon,objRs,ObjFso,myFile,myData,rc,rSet objCon=createobject("Adodb.connection")Set objRs=createobject("Adodb.Recordset")set objFso=createobject("Scripting.Filesystemobject")Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr\My Documents\pavan.txt",8)objcon.provider=("Microsoft.jet.oledb.4.0")objcon.open"C:\Documents and Settings\gcr\My Documents\pavan.mdb"objrs.open "select * from login",objConr=1Do until objRs.EOFa=objRs.Fields ("Agent")b=objRs.Fields ("Pwd")myFile.Writeline a &","& b

www.pavanworld.net 94

Page 95: Pavan+Advanced QTP Guide

r=r+1objRs.MoveNextLoopmyFile.CloseobjCon.Close

4) Connecting to a SQL Sever database

Const adOpenStatic = 3Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _"Provider=SQLOLEDB;Data Source=atl-sql-01;" & _"Trusted_Connection=Yes;Initial Catalog=Northwind;" & _"User ID=fabrikam\kenmyer;Password=34DE6t4G!;"

objRecordSet.Open "SELECT * FROM Customers", _objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo objRecordSet.RecordCount

5) Open a Database Using a DSN

Const adOpenStatic = 3Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _"Northwind;fabrikam\kenmyer;34ghfn&!j"

objRecordSet.Open "SELECT * FROM Customers", _objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo objRecordSet.RecordCount6) Open Two Record sets

Const adOpenStatic = 3Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")Set objRecordSet2 = CreateObject("ADODB.Recordset")

objConnection.Open _"Provider= Microsoft.Jet.OLEDB.4.0; " & _

www.pavanworld.net 95

Page 96: Pavan+Advanced QTP Guide

"Data Source=inventory.mdb"

objRecordSet.Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'", _objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

objRecordSet2.Open "SELECT * FROM Storage Where ComputerName = 'Computer1'", _objConnection, adOpenStatic, adLockOptimistic

objRecordSet2.MoveFirst

Do Until objRecordset.EOFWscript.Echo objRecordset.Fields.Item("ComputerName")Wscript.Echo objRecordset.Fields.Item("OSName")objRecordSet.MoveNextLoop

Do Until objRecordset2.EOFWscript.Echo objRecordset2.Fields.Item("DriveName"), _objRecordset2.Fields.Item("DriveDescription")objRecordSet2.MoveNextLoop

objRecordSet.CloseobjRecordSet2.CloseobjConnection.Close

7) Searching a Database Using String Criteria

Const adOpenStatic = 3Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _"Provider = Microsoft.Jet.OLEDB.4.0; " & _"Data Source = eventlogs.mdb"

objRecordSet.Open "SELECT * FROM EventTable " & _"WHERE Type = 'Error'", objConnection, adOpenStatic, _adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo "Number of records: " & objRecordset.RecordCount

objRecordSet.CloseobjConnection.Close

www.pavanworld.net 96

Page 97: Pavan+Advanced QTP Guide

8) Insert Data into a database table using Database Command Object

Dim objCon,objComSet 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

objCom.CommandText="insert into Emp values('G C Reddy',88233,30000)"objCom.Execute

objCon.CloseSet objCom=NothingSet 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,iSet 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").GetRowCountMsgbox intRowcountFor 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.CloseSet objCom=NothingSet objCon=Nothing

www.pavanworld.net 97

Page 98: Pavan+Advanced QTP Guide

Object Identification ConfigurationOverview:

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

Object Identification Types

a)    Normal identification

1)   Mandatory properties2)   Assistive properties

b)    Smart identification

1)    base filter properties2)    optional filter properties

c)    Ordinal identifier 

1)    location2)    index3)    creation time(only for web)

QTP learns information in the following in case of normal identification: 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.

QTP learns information in the following in case of Smart Identification:

Smart identification is an optional feature, if we feel normal identification is not sufficient for any object, and then we configure Smart Identification for that object, in order to avoid Ordinal Identifier.

www.pavanworld.net 98

Page 99: Pavan+Advanced QTP Guide

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:

There are 3 types of ordinal identifiers available

1) Location: is based on object location in the AUT ,location starts from zero. 

2) index: it is based on sequence of the programs, index starts from zero 

3) Creation time: it is based on loading time of the web objects. qtp generates 0,1,2 like numbers.

Tool Settings Globalization:

As QTP is a I-tier(Stand-alone) application,making Tool settings globally is not possible.

For making tool settings global, QTP is providing a special feature called "Generate Script".

STEPS:

1) Settings available in 3 areas.        a) File->Settings    b) Tools->Options    c) Tools->Object Identification

2) Perform required settings and generate Scripts

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 99

Page 100: Pavan+Advanced QTP Guide

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 in QTP:

 Regular expressions can be used in QTP for identifying objects and text strings with varying values.

 Where we use: 

 o Defining the property values of an object in Descriptive programming for  handling dynamic objects

o For parameterizing a step

o creating checkpoints with varying values

Using Regular Expressions in QTP:

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 a regular expression in standard checkpoint to verify the property values of an object; we can set the expected value of an object's property as a regular expression so that an object with a varying value can be verified.

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.

Ways of 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.

b) Matching Any Single Character:

www.pavanworld.net 100

Page 101: Pavan+Advanced QTP Guide

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.

c) Matching Any Single Character in a List:

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]

d) Matching Any Single Character Not in a List:

 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.

e) Matching Any Single Character within a Range:

 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]

f) Matching Zero or More Specific Characters:

 An asterisk (*) instructs QTP to match zero or more occurrences of the preceding character.For example:

ca*r

Matches car, caaaaaar, and cr

g) Matching One or More Specific Characters:

 A plus sign (+) instructs QTP to match one or more occurrences of the preceding character.For example:

www.pavanworld.net 101

Page 102: Pavan+Advanced QTP Guide

ca+r Matches car and caaaaaar, but not cr.

 

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.

i) Grouping Regular Expressions:

 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 ( * , + , ? , { } ).

j)  Matching One of Several Regular Expressions:

 A vertical line (|) instructs QTP to match one of a choice of expressions.

k)  Matching the Beginning of a Line:

 A caret (^) instructs QTP to match the expression only at the start of a line, or after a newline character.

l)  Matching the End of a Line:

A dollar sign ($) instructs QTP to match the expression only at the end of a line, or before a newline character.

m)  Matching Any AlphaNumeric Character Including the Underscore:

 \w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-z, 0-9, _).

n)  Matching Any Non-AlphaNumeric Character:

 \W instructs QTP to match any character other than alphanumeric characters and underscores.

o) Combining Regular Expression Operators:

www.pavanworld.net 102

Page 103: Pavan+Advanced QTP Guide

We can combine regular expression operators in a single expression to achieve the 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

 

VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions.

Regular Expression Object Properties and Methods:

 

Properties:

 

a) Global Property

 

b) IgnoreCase Property

 

c) Pattern Property

 

Methods:

 

a) Execute Method

 

b) Replace Method

www.pavanworld.net 103

Page 104: Pavan+Advanced QTP Guide

 

c) Test Method

Regular Expressions Examples:

 

1) Match File Names in a Directory against Regular Expression

Set objFS = CreateObject("Scripting.FileSystemObject")Set objShell = CreateObject("WScript.Shell")strCurrentDirectory = objShell.CurrentDirectory

Set objFolder = objFS.GetFolder(strCurrentDirectory)Set colFiles = objFolder.Files

Set objRE = New RegExpobjRE.Global     = TrueobjRE.IgnoreCase = FalseobjRE.Pattern    = WScript.Arguments(0)

For Each objFile In colFiles   bMatch = objRE.Test(objFile.Name)   If bMatch Then      WScript.Echo objFile.Name   End IfNext

2) Match Content in a File against a Regular ExpressionstrFileName = "E:\pavan.txt"Set objFS = CreateObject("Scripting.FileSystemObject")

Set objTS = objFS.OpenTextFile(strFileName)strFileContents = objTS.ReadAllWScript.Echo "Searching Within: "WScript.Echo strFileContentsobjTS.Close

Set objRE = New RegExpobjRE.Global     = TrueobjRE.IgnoreCase = FalseobjRE.Pattern    = WScript.Arguments(0)

Set colMatches = objRE.Execute(strFileContents)WScript.Echo vbNewLine & "Resulting Matches:"For Each objMatch In colMatches   WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value

 --------------------------------------------------

www.pavanworld.net 104

Page 105: Pavan+Advanced QTP Guide

Batch Testing

Executing a group of tests/series of tests at a time is known as Batch Testing or Batch Execution.

For performing Batch Testing, QTP has provided a separate Tool called 'Test Batch Runner'.

Steps for Batch Testing:

1). Create Individual Tests and Run once.

2). Open 'Test batch Runner' Tool and Form Batches.

3) Provide permission to  'Test batch Runner' to run tests

4). Run or Execute Test Batches from Test Batch Runner.

5) View Test wise Result in 'Test Result Viewer' 

Forming a Test Batch:

Launch Test Batch Runner.

Navigation: Start>program>quicktest professional>Tools>Test Batch Runner>File>new>batch>add>browse path of the test (like this add number of tests)>save with MTB extension (Module test batche)>close test batch runner.

Running or Executing a Test Batch

Open Test Batch Runner Tool

Navigation: File>open>browse path of the test batch>batch>run

Note: Test Batch Runner launches QTP Tool, QTP runs Tests one by one.

Note: Allowing other products to Run Tests.

Navigation: Tools>Options>Run>check allow other mercury products>apply & Ok

Executing partial Test Batch

Open Test Batch Runner >open Test Batch>Select or deselect tests>run test batch.

VB Script Other Objects 

www.pavanworld.net 105

Page 106: Pavan+Advanced QTP Guide

 

1) Dictionary Object

 Dictionary Object that stores data key, item pairs.

A Dictionary object is the equivalent of a PERL associative array/Hash Variable. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.

Creating a Dictionary Object:

Set objDictionary = CreateObject("Scripting.Dictionary") 

Dictionary Objects Methods: 

Add Method 

Adds a key and item pair to a Dictionary object

Exists Method

Returns true if a specified key exists in the Dictionary object, false if it does not.

Items Method

Returns an array containing all the items in a Dictionary object.

Keys Method

Returns an array containing all existing keys in a Dictionary object.

Remove Method

Removes a key, item pair from a Dictionary object.

RemoveAll Method

The RemoveAll method removes all key, item pairs from a Dictionary object. Example:

Dim citiesSet cities = CreateObject("Scripting.Dictionary")cities.Add "h", "Hyderabad"cities.Add "b", "Bangalore"cities.Add "c", "Chennai"

Dictionary Objects Properties:Count Property

www.pavanworld.net 106

Page 107: Pavan+Advanced QTP Guide

Returns the number of items in a collection or Dictionary object. Read-only.

CompareMode PropertySets and returns the comparison mode for comparing string keys in a Dictionary object.

Key Property

Sets a key in a Dictionary object.

Item PropertySets 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:

1)  Add  Elements to a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"   objDictionary.Add "Printer 2", "Offline"objDictionary.Add "Printer 3", "Printing"

 

2) Delete All Elements from Dictionary

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 strKeyNext

objDictionary.RemoveAllcolKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: "For Each strKey in colKeys    Wscript.Echo strKeyNext

3) Delete One Element from a Dictionary

www.pavanworld.net 107

Page 108: Pavan+Advanced QTP Guide

 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.Remove("Printer 2")

colKeys = objDictionary.Keys

 

Wscript.Echo VbCrLf & "Second run: "

For Each strKey in colKeys

    Wscript.Echo strKey

Next

 

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

www.pavanworld.net 108

Page 109: Pavan+Advanced QTP Guide

 5) Verify the Existence of a Dictionary Key

 Set objDictionary = CreateObject("Scripting.Dictionary")

 objDictionary.Add "Printer 1", "Printing"  

objDictionary.Add "Printer 2", "Offline"

objDictionary.Add "Printer 3", "Printing"

 If objDictionary.Exists("Printer 4") Then

    Wscript.Echo "Printer 4 is in the Dictionary."

Else

    Wscript.Echo "Printer 4 is not in the Dictionary."

End If

 2) RegExp object

 

VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions.

Regular Expression Object Properties and Methods:

 Properties:

 a) Global Property

 b) IgnoreCase Property

 c) Pattern Property

 Methods:

 a) Execute Method b) Replace Method c) Test Method

 

1) Match File Names in a Directory against Regular Expression

 

www.pavanworld.net 109

Page 110: Pavan+Advanced QTP Guide

Set objFS = CreateObject("Scripting.FileSystemObject")

Set objShell = CreateObject("WScript.Shell")

strCurrentDirectory = objShell.CurrentDirectory

 

Set objFolder = objFS.GetFolder(strCurrentDirectory)

Set colFiles = objFolder.Files

 

Set objRE = New RegExp

objRE.Global     = True

objRE.IgnoreCase = False

objRE.Pattern    = WScript.Arguments(0)

 

For Each objFile In colFiles

   bMatch = objRE.Test(objFile.Name)

   If bMatch Then

      WScript.Echo objFile.Name

   End If

Next

 

2) Match Content in a File against a Regular Expression

strFileName = "E:\pavan.txt"

Set objFS = CreateObject("Scripting.FileSystemObject")

 

Set objTS = objFS.OpenTextFile(strFileName)

strFileContents = objTS.ReadAll

www.pavanworld.net 110

Page 111: Pavan+Advanced QTP Guide

WScript.Echo "Searching Within: "

WScript.Echo strFileContents

objTS.Close

 

Set objRE = New RegExp

objRE.Global     = True

objRE.IgnoreCase = False

objRE.Pattern    = WScript.Arguments(0)

 

Set colMatches = objRE.Execute(strFileContents)

WScript.Echo vbNewLine & "Resulting Matches:"

For Each objMatch In colMatches

   WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value

Next 

3) Database Command Object

 1) Insert Data into a database table using Database Command Object

Dim objCon,objComSet 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

objCom.CommandText="insert into Emp values('G C Reddy',88233,30000)"objCom.Execute

objCon.CloseSet objCom=NothingSet 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,iSet objCon=Createobject("ADODB.connection")

www.pavanworld.net 111

Page 112: Pavan+Advanced QTP Guide

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").GetRowCountMsgbox intRowcountFor 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.CloseSet objCom=NothingSet objCon=Nothing

4) Word Object

 1) Create a word document and write some data

dim mwset mw=CreateObject("Word.Application")mw.Documents.Addmw.selection.typetext "hello"mw.ActiveDocument.SaveAs "e:\pavan.doc"mw.quitset 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

d("micclass").value="Link"

set a=Browser("Google").page("Google").childobjects(d)

for i=0 to a.count-1

www.pavanworld.net 112

Page 113: Pavan+Advanced QTP Guide

mw.WordBasic.filenew

s=a(i).getROProperty("innertext")

mw.WordBasic.insert s

if mw.ActiveDocument.Spellingerrors.count>0 then

Reporter.ReportEvent 1,"Spelling","spelling error :"&s

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 mwSet mw=CreateObject("Word.Application")Set fs=createobject("Scripting.FileSystemObject")Set d=fs.Drivesmw.FileSearch.FileName="*.doc"For each dr in dmsgbox drmw.FileSearch.LookIn=drmw.FileSearch.SearchSubFolders=Truemw.FileSearch.ExecuteFor each i in mw.FileSearch.FoundFilesprint iSet f=fs.GetFile(i)print f.Name&" "&f.Size&" "&f.DateCreatedprint "-------------------------------------------------------------------"NextNextmw.Quit 

 5) IE Object

 

1) Open Internet Explorer and navigate to yahoo mail

 Dim ie

Set ie=CreateObject("InternetExplorer.Application")

www.pavanworld.net 113

Page 114: Pavan+Advanced QTP Guide

ie.Visible=True

ie.Navigate "www.yahoomail.com"

x=Browser("CreationTime:=0").GetROProperty("title")

msgbox x

 

Automation FrameworkAutomation:

Accessing one Software Objects from another Software is called Automation.

(AUT is one s/w and Testing Tool is another s/w.)

Automation Framework:

It is a set of guidelines, assumptions and process developed by experts in order to perform a task(s) in an effective, efficient and optimized way.

Or

A systematic approach to automate software Test process

www.pavanworld.net 114

Page 115: Pavan+Advanced QTP Guide

Why Automation Framework:

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:

a) Flat files (.txt),

b) Excel files (.xls)

c) Object repository files (.tsr)

d) XML files (.xml)

e) Library files (.vbs/.qfl)

f) Test Scripts (.mts)

g) Test Batch Files (.mtb)

h) Recovery scenario files (.qrs)

i) Test Result file (.XML)   Etc...

Tasks to be performed:

a) Analyzing the application

b) Selecting Areas/Test Cases for Automation

c) Planning (Effort estimation, Schedule, Work allocation and Automation Framework implementation)

d) Creating Generic and project specific functions.

e) Creating required Automation resources (Functions, Object repository Files, Environment variable files---etc)

f) Creating Tests (Using Object Repository or Descriptive Programming)

g) Enhancing Tests(Inserting Checkpoints, Output Values, Transaction points, Flow Control Statements, Synchronization, Parameterization---etc )

h) Debugging and running tests(Individual test execution, Test Batch execution --etc)

i) Defining and exporting test results

j) Analyzing results

k) Test reporting

l) Defect Reporting using companies defect management system.

www.pavanworld.net 115

Page 116: Pavan+Advanced QTP Guide

m) Modifying tests

n) Performing re and regression testing ---etc

Types Of Automation Framework:

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)

1. Record/Playback or Linear Framework (1st generation framework).

In this Framework we create tests using recording,low resources maintenance, Form batches and executing tests.

Drawbacks: Modifications and maintenance are difficult,less command on scripts,low performance ---etc2. Modular Framework.

In this Framework,reusable components can be recognized,first we concentrate on creating reusable components, then creating tests using those components.

Advantages: 

It reduces test Automation time

Performance is high than recording and playback

Drawbacks: Less usage of keywords, no concentration on Data driven testing and low performance than latest Frameworks like Keyword Driven Framework.

3. Data Driven Framework

In this Framework,we concentrate more on Data Driven testing.We recognize positive and negative scenarios,then collecting test data and parameterizing.

Advantages: 

We can check reliability of the system,positive and negative testing.

Drawbacks: 

Less concentration on complex Functionality Testing and low keywords usage.4. Keyword Driven framework

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: 

www.pavanworld.net 116

Page 117: Pavan+Advanced QTP Guide

Scope is very high as we mix different approaches,Flexible for performing any tasks.

Drawbacks:

Organizing and managing resources are difficult,complex architecture,low in performance.

NOTE: Now a days Mix of Data driven and Keyword driven approaches is a famous Hybrid Framework in the industry.

Keyword Driven Framework

Keyword:

1. Any word used as the key to a code

2 A reserved word used to identify a specific command, function etc.

(in our test automation example keywords are :

Keywords to be used in Test Automation:

a) Test Objects (EX: Browser,page,webEdit,WinButton---etc)

b) Functions (Built-In and User defined)

c) Methods (Ex:Set,Select,Activate,Navigate---etc)

d) Statements (EX:Dim,If,For---etc)

e) Operators (EX: +,/,*,and,or,not---etc)

Keyword Driven Approach:

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.

Key elements of Automation Framework:

1. Well defined folder structure2. Initialization script3. Driver script4. input data spreadsheet5. process guidelines document

Why folder structure?

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

www.pavanworld.net 117

Page 118: Pavan+Advanced QTP Guide

2. Environment

3. Library

a) Company

b) Project Specific

4. Test data

5. Test log

6. Recovery scenarios

7. Miscellaneous

And

1. Initialization script (.vbs file)2. Driver script (QTP Script file)

1) Object Repository: In this folder we store object repository files(.tsr), all team members can use this repositories.

2) Environment: In this folder we store environment variables files(.xml), all team members can use this variables.

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.

5) Test Log: In this folder we store test result(excel sheet).

6) Recovery scenarios: In this folder we store qtp recovery scenarios files(.qrs).

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 118