126
QUALITY THOUGHT QTP-MATERIAL Introduction to Automation Testing 1. What is Automation? 2. Why we Need to go for Automation? 3. When we Need to go for Automation? 4. When not to go for Automation? What is Automation? Test Automation is the process of simulating a set of (manual) actions on the given system using an Automation tool or utility REMEMBER: Automation is NOT a replacement for manual testing Automation is NOT intended to find bugs 100% testing can’t be automated Why to Automate: Repetitive tests performed by a tester manually May result in Human Errors Consume more time Automation Helps to Reducing repetitive manual interactions with system during testing phase Improve product reliability & quality by eliminating human errors Improve Test Coverage with automation, and Reduce costs of testing [when wisely used] What to Automate: Tests that Need to Run for Every Build Tests that use multiple data values for same action Identical tests that need to be executed using different browsers What NOT to Automate: Page 1 of 126

QT QTP Material

Embed Size (px)

DESCRIPTION

QTP Complete material

Citation preview

QUALITY THOUGHT QTP-MATERIAL

QUALITY THOUGHT QTP-MATERIAL

Introduction to Automation Testing1. What is Automation?2. Why we Need to go for Automation?3. When we Need to go for Automation?4. When not to go for Automation?What is Automation? Test Automation is the process of simulating a set of (manual) actions on the given system using an Automation tool or utility REMEMBER: Automation is NOT a replacement for manual testing Automation is NOT intended to find bugs 100% testing cant be automatedWhy to Automate: Repetitive tests performed by a tester manually May result in Human Errors Consume more time Automation Helps to Reducing repetitive manual interactions with system during testing phase Improve product reliability & quality by eliminating human errors Improve Test Coverage with automation, and Reduce costs of testing [when wisely used]What to Automate: Tests that Need to Run for Every Build Tests that use multiple data values for same action Identical tests that need to be executed using different browsersWhat NOT to Automate: Tests Cases that will only be executed once Test Cases used for Ad-hoc/random Testing Test cases that are infrequently selected for execution Test cases that will require manual intervention i.e. a task not possible to automate The most important one-based on the intuition and knowledge of applicationE.g. If you find that you cant escape from manual intervention

Advantages of Automations: Less Execution Time and Effort. Tests can be executed on unattended mode and 24*7. Parameterize all the input data through a single global data sheet makes it easy to modify the input data for any future enhancement in the application thus reducing the maintenance cost. Automation is cost effective.QTP Testing Process: Test Planning Plan How you want to automate your Tests Creating Tests Recording steps using QTP Coding steps Enhancing your test Insert Checkpoints Parameterization Debugging your test Ensure that it operates smoothly and without interruption Running your test Run the test to check the behavior of your application Analyzing the Test results Examine the test results to locate defects in your application Reporting defects Report the defects in to bug tracking tool

QTP Tool Features QTP was Launched in 2002 (Nov). By Mercury Interactive. Later taken over by HP, in 2007 QTP is an Object Based Testing Tool QTP is for Functional and Regression Testing It follows Keyword Driven Approach It supports Windows Operating Environment only. It supports GUI based (Graphical user interface) and Web based Applications Automation, does not support CUI (Command user interface) Applications. It has multilingual support. (It supports English, Chinese, Japanese, Korean, etc languages with respect to license.) It has adapted Microsoft Visual Basic Scripting edition for programming and Excel like spread sheet for Data driven testing.Tools support for QTP: VB Script for Scripting (for implementing programming logic) VB Script Engine integrated in QTP, so apart from scripting features we can use File system, Excel, word, Adodb etc. Object models from QTP. SQL (Structured query language) Engine integrated in QTP, so we can use SQL Statements in QTP to perform Database Operations Excel like spread sheet integrated in QTP for performing Data driven Testing We can install MS Script Debugger with QTP for Debugging Test scripts. QTP uses XML format for Test results, Environment variables and for exporting object repositories. QTP can be integrated with other Tools like WinRunner and Quality Center. QTP 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. It was derived from Astra QuickTest (mother tool of QTP). It supports IE (Internet Explorer) only for recording tests, for execution it supports other browsers like Mozilla and AOL, opera Etc apart from IE. QTP is a Desktop Application (I-Tier/Stand alone). QTP developed in .NET Technology. Since it is Stand-alone Application, It doesn't have Database, It stores resources as files (Internal and External). We can't share qtp services from one machine to another, but we can share resources (Ex: Object Repository files, Function Libraries, Environment variable files, Recovery scenario files etc...)

QTP has two types of License: Seat or Node locked License Concurrent or float license. We have to use Seat license from fixed system/machine and Concurrent License, we can use from any system but one user at a time. If we want multiple concurrent licenses that we can purchase QTP has UNI code support.Version History of QuickTest Professional Astra QuickTest (Mother tool of QTP) 1.0 to 5.0 QTP derived from Astra QuickTest and influenced by WinRunner 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 11.00 2010** (It is Latest Version)********************************************QTP Tool Window Menus

QTP Commands are available in 3 ways.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.

Command Function

New > Test Creates a new test. Ctrl+N

New > Business Component Creates a new business component. Ctrl+Shift+N

New > Scripted Component Creates a new scripted component.

New > Application Area Creates a new application area. Ctrl+Alt+N

New > Function Library Creates a new function library. Shift+Alt+N

Open > Test Opens an existing test. Ctrl+O

Open > Business/Scripted Component Opens an existing business or scripted component. Ctrl+Shift+O

Open > Application Area Opens an existing application area. Ctrl+Alt+O

Open > Function Library Opens an existing function library. Shift+Alt+O

Close Closes the active function library.

Close All Function Libraries Closes all open function libraries.

QualityCenter Connection Opens the QualityCenter Connection dialog box, enabling you to connect to a QualityCenter project.

QualityCenter Version Control Provides a sub-menu of options for managing versions of QuickTest assets in QualityCenter. The sub-menu is available only when you are connected to version-control enabled QualityCenter project.

Save Saves the active document. Ctrl+S

Save As Opens the relevant Save dialog box so you can save the open document.

Save Test with Resources Saves a standalone copy of the current test together with its resource files.

Save All Saves all open documents.

Enable Editing Makes read-only function libraries editable.

Export Test to Zip File Creates a zip file of the active document. Ctrl+Alt+S

Import Test from Zip File Imports a document from a zip file. Ctrl+Alt+M

Convert to Scripted Component Converts a business component to a scripted component. Ctrl+Alt+C

Print Prints the active document. Ctrl+P

Print Preview Displays the Keyword View as it will look when printed and enables you to modify the page setup.

Settings Opens the Settings dialog box, enabling you to define settings for the open document. (Not relevant for function libraries)

Process Guidance Management Opens the Process Guidance Management dialog box, enabling you to manage the list of processes that are available in QuickTest.

Associate Library '' with '' Associates the active function library with the open document. (Available only from function libraries)

Recent Files Lists the recently viewed files.

Exit Closes the QuickTest session.

Edit Menu: It provides editing options and renaming, deleting and splitting actions.

Command Function

Undo Reverses the last command or deletes the last entry you typed.

Redo Reverses the most recent operation of the Undo command.

Cut Removes the selection from your document.

Copy Copies the selection from your document.

Paste Pastes the selection to your document.

Delete Deletes the selection from your document.

Copy Documentation to Clipboard Copies the content of the Documentation column of the Keyword View, enabling you to paste it in an external application.

Action > Split Action Separates an action into two sibling actions or into parent-child nested actions.

Action > Rename Action Changes the name of an action.

Action > Delete Action Enables you to remove the selected call to the action, or delete the action and its calls from the active test.

Action > Action Properties Enables you to specify options, parameters, and associated object repositories for a stored action.

Action > Action Call Properties Enables you to specify the number of run iterations according to the number of rows in the Data Table, and to define the values of input parameters and the storage location of output parameters.

Step Properties > Comment Properties Opens the Comment Properties dialog box for a comment step. Available only when the selected step is a comment.

Step Properties > Object Properties Opens the Object Properties dialog box for a selected object. Available only when the selected step contains a test object.

Step Properties > Checkpoint Properties Opens the relevant Checkpoint Properties dialog box for a selected object. Available only when the selected step is a checkpoint step.

Step Properties > Output Value Properties Opens the relevant Output Value Properties dialog box for a selected object. Available only when the selected step is an output value step.

Step Properties > Report Properties Displays the Report Properties dialog box for a report step. Available only when the selected step is a Reporter.ReportEvent step.

Find Searches for a specified string.

Replace Searches and replaces a specified string.

Go To Moves the cursor to a particular line in the test.

Bookmarks Creates bookmarks in your script for easy navigation.

Advanced > Comment Block Comments out the current row, or selected rows.

Advanced > Uncomment Block Removes the comment formatting from the current or selected rows.

Advanced > Indent Indents the step according to the tab spacing defined in the Editor Options dialog box.

Advanced > Outdent Outdents the step (reduces the indentation) according to the tab spacing defined in the Editor Options dialog box.

Advanced > Go to Function Definition Navigates to the definition of the selected function.

Advanced > Complete Word Completes the word when you type the beginning of a VBScript method or object.

Advanced > Argument Info Displays the syntax of a method.

Advanced > Apply "With" to Script Generates With statements for the action displayed in the Expert View, and enables IntelliSense within With statements.

Advanced > Remove "With" Statements Converts any With statements in the action displayed in the Expert View to regular (single-line) VBScript statements.

Optional Step Inserts an optional step (a step that is not required to successfully complete a run session).

View menu: Through this menu we can launch and close, active screen, Data Table, Debug viewer, information, missing resources etc.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)

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.Key word view- Test in Icon based GUI format.

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

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

Configuring Active Screen: Tools > Options > Active screen tab > Increase / Decrease capture level, Apply and OK.

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

3) Data Table It has an integrated spread sheet (Excel like), used for Data driven testing.

Navigation: View menu>Data table (for launching and closing)

Data driven Testing: Testing the same task(S) or same operation with multiple sets of test data.

It can be used in two ways.

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

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)

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

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

5) Missing Resources

It can be used for showing missing resources that attached to current test such as (Recovery Scenarios, Library files etc).

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

6) InformationThis pane shows syntax errors automatically during saving the test. Navigation: view menu> information

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

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.

Command Function Short Cut Keys

Record Starts a recording session. F3

Run Starts a run session from the beginning or from the line at which the session was paused. F5

Stop Stops the recording or run session. F4

Run Current Action Runs only the active action.

Run from Step Starts a run session from the selected step. Ctrl+F5

Maintenance Run Mode Starts a run session during which the Maintenance Run Mode wizard opens for steps that failed because an object was not found in the application (if applicable).

Update Run Mode Starts a run session to update test object descriptions and other options (if applicable).

Analog Recording Starts recording in Analog Recording mode. Shift+Alt+F3

Low Level Recording Starts recording in Low Level Recording mode. Ctrl+Shift+F3

Record and Run Settings Opens the Record and Run Settings dialog box, enabling you to define browser preferences for recording and running your test.

Process Guidance List Lists the processes that are available for the current document type and for the currently loaded QuickTest add-ins, enabling you to open them.

Results Enables you to view results for a test run session.

QTP supports three types of recording modes. They are:1) Normal recording mode2) Analog Recording3) Low Level Recording1) Normal recording mode records the objects in your application and the operations performed on them. This mode is the default and takes full advantage of the QuickTest test object model, recognizing the objects in your application regardless of their location on the screen. 2) Analog Recording. Enables you to record the exact mouse and keyboard operations you perform in relation to either the screen or the application window. In this recording mode, QuickTest records and tracks every movement of the mouse as you drag the mouse around a screen or window.3) Low Level Recording. Enables you to record on any object in your application, whether or not QuickTest recognizes the specific object or the specific operation. 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 or on an object not recognized by QuickTest. You can also use low-level recording if the exact coordinates of the object are important for your test.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.

Command Function

Object Repository (Ctrl+R)Opens the Object Repository window, which displays a tree containing all objects in the current test or component.

Object Repository Manager Opens the Object Repository Manager dialog box, enabling you to open and modify multiple shared object repositories.

Associate Repositories Opens the Associate Repositories dialog box, enabling you to manage the object repository associations for the test.

Map Repository Parameters Opens the Map Repository Parameters dialog box, enabling you to map repository parameters, as needed.

Recovery Scenario Manager Opens the Recovery Scenario Manager dialog box.

Associated Function Libraries Lists the function libraries associated with the active document, enabling you to open them.

Debug Menu: This menu provides debug commands for step by step execution.Through this menu we can insert/remove/break points.

Tools Menu: This menu provides Tools settings option, view options and object identification configuration.Through this menu we can set tool options as well as test pane view options.In this menu object spy option available, through this we can get objects information.(Properties and values)In this menu Virtual object option available; through this option we can create virtual objects.

Command Function

Options Opens the Options dialog box, enabling you to modify global testing options.

View Options Opens the Editor Options dialog box, enabling you to customize how tests and function libraries are displayed in the Expert View and Function Library windows.

Check Syntax (Ctrl+F7)Checks the syntax of the active document.

Object Identification Opens the Object Identification dialog box, enabling you to specify how QuickTest identifies a particular test object.

Object Spy Opens the Object Spy dialog box, enabling you to view the native properties and operations of any object in an open application, as well as the test object hierarchy, identification properties, and operations of the test object that QuickTest uses to represent that object.

Web Event Recording Configuration Opens the Web Event Recording Configuration dialog box, enabling you to specify a recording configuration level. (Relevant for tests only)

Data Driver Opens the Data Driver dialog box, which displays the default Constants list for the action. (Relevant for tests only)

Change Active Screen Replaces the previously recorded Active Screen with the selected Active Screen. (Relevant for tests only)

Virtual Objects > New Virtual Object Opens the Virtual Object Wizard, enabling you to teach QuickTest to recognize an area of your application as a standard test object.

Virtual Objects > Virtual Object Manager Opens the Virtual object Manager, enabling you to manage all of the virtual object collections defined on your computer.

Customize Opens the Customize dialog box, which enables you to customize toolbars and menus, and create new menus.

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.

Object Identification Configuration

Object: Object is something, which has structure and properties. Every test automation tool is GUI (graphical user interface) sensitive. Test automation tool has to identify the objects on the application, then only it can do the intended operations.Quick Test Professional has its own mechanism to identify the objects on the Application under Test. QTP has variousadd-ins available for different applications.

Let us have a look at the QTPs object identification mechanism1. Open QTP 2. Click Tools > Object Identification 3. Object Identification dialog gets opened

In QTP 10.0 standard installation, it comes with ActiveX, Visual Basic, and Web add-ins and can identify the objects of ActiveX, Standard Windows, Visual Basic, and Web applications.QTP identifies the objects with the following properties:1. Mandatory properties 2. Assistive properties 3. Smart identification 4. Ordinal identifier Location Index

Will get into each one of these bullet points later. Let us have look at one of the important features of QTP which will be used many times during the test automation of an application is Object Spy. Open the Application under Test (AUT)Click Tools > Object Spy..

Click on the hand button on the spy Click on a particular object on the AUTs user interface. All the properties of the object will be displayed on this spy. Below figures illustrate how object spy displays the object properties (Windows, Visual Basic, and Web application are taken as examples)

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.

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

1) Systemutil: Operating System

BROWSER

PPTS PAGE

OBJECTS in BROWSER

NOTEPAD

CARGAMES

From the above diagram, It is Clearly understood that the Browser, Notepad, Car Game anything installed in windows are all SIBLINGS under the windows operating system. To access these installed application, we need to have reference of the operating system-----SystemUtil will give you the reference of the operating systemSystemutil: Is an implicit object of QTP that brings reference to existing operating system in which QTP is installed instantlyExample:Suppose QTP is installed in windows 7 operating system then systemutil bring the reference of windoews7 operating systemMethods:

BlockInputPrevents Keyboard and mouse input events from reaching applicationPrevents keyboard and mouse input events from reaching applicationsPrevents keyboard and mouse input events from reaching applicaPrevents keyboard and mouse input events from reaching applications

CloseDescendentProcessesCloses all processes by Quick Test

CloseProcessByHwndCloses a process that is the owner of a window with the specified handle

CloseProcessByIdCloses a process according to its process ID (PID)

CloseProcessByNameCloses a process according to its name

CloseProcessByWndTitleCloses all processes that are owners of windows with the specified title

RunRuns a file or Application

UnblockInputRe-enables Keyword and mouse input events after a BlockInput statement was used to Block them

Process Names that we use in Above MethodsApplication NameWindows Process name

NotepadNotepad.exe

WordpadWinword.exe

Internet ExplorerIexplore.exe

Micro soft paintMspaint.exe

ExcelExcel.exe

Filght"C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"

2) Reporter:The object used for sending information to the test resultsSyntax:Reporter.ReportEvent EventStatus, ReportStepName, Details [, ImageFilePath] Argument Type Description

EventStatus Number or pre-defined constant Status of the Test Results step: 0 or micPass: Causes the status of this step to be passed and sends the specified message to the Test Results window. 1 or micFail: Causes the status of this step to be failed and sends the specified message to the Test Results window. When this step runs, the test fails. 2 or micDone: Sends a message to the Test Results window without affecting the pass/fail status of the test. 3 or micWarning: Sends a warning message to the Test Results window, but does not cause the test to stop running, and does not affect the pass/fail status of the test.

ReportStepName String Name of the step displayed in the Test Results window.

Details String Description of the Test Results event. The string will be displayed in the step details frame in the Test Results window.

ImageFilePath String Optional. Path and filename of the image to be displayed in the Results Details tab of the Test Results window. Images in the following formats can be displayed: BMP, PNG, JPEG, and GIF. Notes: Images cannot be loaded from QualityCenter. Including large images in the test results may impact performance. If an image is specified as a relative path, QuickTest will first search the Results folder for the image and then the search paths specified in the Folders pane of the Options dialog box.

Example: The following examples use the ReportEvent method to report a failed step.Reporter.ReportEvent 1, "Custom Step", "The user-defined step failed." or Reporter.ReportEvent micFail, "Custom Step", "The user-defined step failed." The following example uses the ReportEvent method to include a captured bitmap in the test results. Browser("Browser").Page("WebPage").Image("MyLogo").CaptureBitmap("MyLogo.bmp") Reporter.ReportEvent micDone, "Display Logo", "This is my logo", "MyLogo.bmp"

3) Environment:Enables you to work with environment variables. You can set or retrieve the value of environment variables using the Environment object. You can retrieve the value of any environment variable. You can set the value of only user-defined, environment variables.

Syntax :To set the value of a user-defined, environment variable: Environment (VariableName) = NewValue To retrieve the value of a loaded environment variable: CurrValue = Environment (VariableName) Argument Type Description

VariableName String The name of the environment variable.

NewValue Variant The new value of the environment variable.

CurrValue Variant The current value of the environment variable.

Example The following example creates a new internal user-defined variable named MyVariable with a value of 10, and then retrieves the variable value and stores it in the MyValue variable. Environment.Value("MyVariable")=10 MyValue=Environment.Value("MyVariable")

Automation objects/User defined objects

User can create objects; those can be used for performing specific operations. Ex: Creating objects in filesystemobject class, adodb.connection class, and dictionary object class, Excel. Application class etc

Overview:Generally for every object 20-25 properties information available, qtp recognizes object using 2 0r 3 important properties.

Qtp has default object identification configuration for every environment, if we feel that config is not sufficient for recognizing objects in our application, we can configure some more

Object Identification Types:

a) Normal identification Mandatory properties Assistive properties

b) Smart identification base filter properties optional filter propertiesc) Ordinal identifier Location Index 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.

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 available1) 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 zero3) 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.or making tool settings global, QTP is providing a special feature called "Generate Script". STEPS:1) Settings available in 3 areasa) File->Settingsb) Tools->Optionsc) Tools->Object Identification2) Perform required settings and generate Scripts3) 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.

Object Repository

Object Repository: It is a storage place of QTP where objects information can be storedand it also acts as interface between the Test script and the AUT in order to identify the objects during execution.There are two types of repository available in QTP.1) Local repository (.MTR extension)2) Shared repository(.TSR extension)Local Repository: 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 operationson local repository. As it is QTP internal file user no need to save modifications.

Shared Repository: User (Test Engineer) creates the 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

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 Selected object only Default object types All objects types 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 Objectsa) Local Repository: Resources > object repository >select object and right click >choose rename option >modify the name>release the mouse.>close repositoryb) 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 Objectsa) Local Repository: Resources > object repository >select object and right click >choose delete option >confirm deletion>. >close repositoryb) 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 Object Repositories to an Action/Test1) Resources>Associate repositories>click add icon (+)>browse path of the repository>Associate with an action>click ok2) Repositoriescollection.Add Repository file path (It is Used to Associate Repository to QTP at Run Time)Merging Repositories 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 OptionsLocate 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.

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

Global or Shared Object Repository ispreferable when application is dynamicand object description change frequently Between Shared and local object repository ,shared object repository is more commonly used in automation projects But it hasmaintenance and administrationoverheads as compared to local object repository.To create and use a shared object repository you need to perform three broad steps1) Creating a Shared Object Repository2) Associating a Shared Object Repository3) Editing a Shared Object Repository1) Creating a Shared Object Repository All repositories are local by default. If you want to Create a Shared Object repository Select Resources>Click on Object Repository Manager. Object Repository Manger will open Repository files have an extension .tsr .Give a suitable name say "qtt and save The Shared Repository File is now created

2) Associating a Shared Object Repository Next step is to associate the repository to your test, which enables you to use it To associate repository with a test, Click Resources > Associate Repository You can select the Repository to associate with Actions available in your test. Now you can now use this shared repository to develop your test3) Editing a Shared Object Repository You can use theObject Repository Manager to Edit a Shared Repository. Select Resources > Object Repository Manager .Open the Object Repository we created "qtt" By Default, Repository is opened in Read-only mode. To enable editing click File > Enable Editing Once editing is enabled you can all the operations like cut , copy , pate , rename objects etc that you can also do in Object Repository Using Object Repository Manager is you cancompare two Object Repositories.QTP will give you a static's of what's unique and common in both the repositories You can use the Object repository merge to Convert Local object Repository to Shared Object Repository All repositories are local by default. To create a Shared Object Repository, in the Object Repository Dialog Box , Click File > Export Local Objects Repository files have an extension .tsr .Give a suitable name say "quality and save The Shared Repository File is now created

Configure Web Object Properties into Object Identification ToolS.NoWeb UI Object NameTest Object Property

1BrowserName

2PageTitle

3FrameName

4WebTableName

5WebEditName

6WebListName, allitems

7WebRadiGroupName,allitems

8WebCheckBoxName

9ImageFile Name

10WebButtomnName, Type

11FileName

12LinkName,Innertext,href

13WebElementName, Innertext, href

14Dialog BoxName, regexptitle

Relation Between Object Identification tool and Object Repository/Object Repository managerOR/ORM and Object Identification tool go hand in hand and they are both sides of same coin. Whatever configured in object identification tool reflects in ORM while adding Objects.

Suppose If you try to Add the Web UI WebButton Object to the Object Repository.The changes in Mandatory properties in Object Identification tool will appear as Description properties in the right pane of the Object RepositoryAs below figs shown

QTP Actions:

Action: Set of Statements for perfoming a Task(s)We divide our test into actions to streamline the process of testing.

Purpose of Actions:

For 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

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 cant 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.VBSCRIPT VARIABLES AND DATATYPESWhat Is a Variable?A variable is a convenient placeholder that refers to a computer memory location where you can store program information that may change during execution(Or)Variable is a named memory location for storing program informationDeclaring VariablesWe declare variables explicitly in our script using the Dim statement, the Public statement, and the Private statement. We declare multiple variables by separating each variable name with a comma. For example: Dim Top, Bottom, Left, RightWe can also declare a variable implicitly by simply using its name in our script. Generally it is not a good practice because you could misspell the variable name in one or more places, causing unexpected results During execution. 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 the script. Purpose of Variable:a) Comparing valuesExample: Dim x,y,ax=100y=100a=x=yMsgbox a 'It returns Trueb) Holding Program ResultExample: Cost=Tickets*Price

c) Passing parametersd) To store data that returned by functionsExample:myDate=Now It returns current data & timee) To hold dataExample:myName=Quality thought

Option explicit:When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, or ReDim statements. If you attempt to use an undeclared variable name, an error occurs.Naming RestrictionsVariable names follow the standard rules for naming anything in VBScript. A variable name: 1. Must begin with an alphabetic character. 1. Cannot contain an embedded period. 1. Must not exceed 255 characters. 1. Must be unique in the scope in which it is declared. Assigning Values to VariablesValues 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 = 200DATATYPESWhat Are VBScript 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's used. Because Variant is the only data type in VBScript, it's also the data type returned by all functions in VBScript.At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when you use it in a numeric context and as a string when you use it in a string context. That is, if you're working with data that looks like numbers, VBScript assumes that it is numbers and does the thing that is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. Of course, you can always make numbers behave as strings by enclosing them in quotation marks (" "). Variant Subtypes The following table shows the subtypes of data that a Variant can contain.SubtypeDescription

EmptyVariant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.

NullVariant intentionally contains no valid data.

BooleanContains either True or False.

ByteContains integer in the range 0 to 255.

IntegerContains integer in the range -32,768 to 32,767.

Currency-922,337,203,685,477.5808 to 922,337,203,685,477.5807.

LongContains integer in the range -2,147,483,648 to 2,147,483,647.

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

DoubleContains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

Date (Time)Contains a number that represents a date between January 1, 100 to December 31, 9999.

StringContains a variable-length string that can be up to approximately 2 billion characters in length.

ObjectContains an object.

ErrorContains an error number.

Operator PrecedenceWhen several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. You 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.ArithmeticDescription Symbol

Exponentiation ^

Unary negation -

Multiplication *

Division /

Integer division \

Modulus arithmetic Mod

Addition +

Subtraction -

String concatenation &

ComparisonDescription Symbol

Equality =

Inequality

Less than

Less than or equal to =

Object equivalence Is

LogicalDescription Symbol

Logical negation Not

Logical conjunction And

Logical disjunction Or

Logical exclusion Xor

Logical equivalence Eqv

Logical implication Imp

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.The string concatenation (&) operator is not an arithmetic operator, but in precedence it falls after all arithmetic operators and before all comparison operators. The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object. The logic of OR is that if at least one of the inputs are True, the output is true; True OR True = True True OR False = True False OR True = True False OR False = FalseXOR only returns True if one and only one of the inputs is True. True Xor True = False True Xor False = True False Xor True = True False Xor False = FalseImp returns false if first one is true and second one false except this it returns true. True imp True = True True imp False = False False imp True = True False imp False = TrueCONDITIONAL AND LOOPING STATEMENTSWe 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:Conditional Statements:1) IfThenElse StatementIf...Then...Else: Conditionally executes a group of statements, depending on the value of an expression.Syntax:If condition Then statements [Else elsestatements ]ORIf condition Then [statements][ElseIf condition-n Then [elseifstatements]] . . .[Else [elsestatements]]End If

2) Select Case StatementSelect Case: Executes one of several groups of statements, depending on the value of an expression.Syntax:Select Case testexpression [Case expressionlist-n [statements-n]] . . . [Case Else expressionlist-n [elsestatements-n]]End SelectExample:'Select CaseColour =Ucase( Inputbox("Please enter the colour of your choice"))

Select Case Colour Case "RED" MsgBox "Colour selected is Red" Case "BLUE" MsgBox "Colour selected is Red" Case "GREEN" MsgBox "Colour selected is Red" Case ELSE MsgBox "Invalid Colour" End Select

Looping statements are used to run the same block of code a specified number of times.In VBScript we have four looping statements: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.a) Repeating Statements While a Condition is TrueRepeats a block of statements while a condition is True or until a condition becomes True

i) Do While conditionStatements----------------------LoopOr, we can use this below syntax:

Example:

Dim xDo While x60

Filter: Returns a zero-based array containing a subset of a string array based on a specified filter criteria. Syntax: Filter (InputStrings, Value [, Include [, Compare]])ArgumentsInputStrings Required. One-dimensional array of strings to be searched.

ValueRequired. String to search for.

IncludeOptional. Boolean value indicating whether to return substrings that include or exclude Value. If Include is True, Filter returns the subset of the array that contains Value as a substring. If Include is False, Filter returns the subset of the array that does not contain Value as a substring.

CompareOptional. Numeric value indicating the kind of string comparison to use. See Settings section for values.

Example:Dim MyArray (3)MyArray (0) = "Sunday"MyArray (1) = "Monday"MyArray (2) = "Tuesday"MyIndex = Filter (MyArray, "Mon")Msgbox MyIndex (0) Return value = "Monday"IsArray Function: IsArray: Returns a Boolean value indicating whether a variable is an array.Syntax: IsArray (varname)VarnameThe varname argument can be any variable.

Example: Dim MyArray (3)MyArray (0) = "Sunday"MyArray (1) = "Monday"MyArray (2) = "Tuesday"MyVariable = IsArray(MyArray) Return value = TrueSplit Function:Returns a zero-based, one-dimensional array containing a specified number of substrings.Syntax: Split (expression[, delimiter[, count[, compare]]])Argumentsexpression Required. String expression containing substrings and delimiters. If expression is a zero-length string, Split returns an empty array, that is, an array with no elements and no data.

delimiterOptional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.

countOptional. Number of substrings to be returned; -1 indicates that all substrings are returned.

compareOptional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Example:1) Dim Strname,StrStrname = QualityXthxoughtxtechxnoXlogixesStr = Split(Strname,x)MsgboxStr(0) Output QualityXthMsgbox Str(1) Output ought--------Msgbox Str(4) Output esNote: The above example the Comparison is Binary by default2) Dim Strname,StrStrname = QualityXthxoughtxtechxnoXlogixesStr = Split(Strname,x,-1,1)MsgboxStr(0) Output QualityMsgbox Str(1) Output th----------------Msgbox Str(6) Outputes

Join: Returns a string that consists of a number of substrings in an arraySyntax: Join (list [, delimiter])Arguments:list Required. One-dimensional array containing substrings to be joined.

delimiterOptional. String character used to separate the substrings in the returned string. If omitted, the space character (" ") is used. If delimiter is a zero-length string, all items in the list are concatenated with no delimiters.

Example:Dim MyArray (3)MyArray (0) = "Welcome "MyArray (1) = "to "MyArray (2) = "QTP "MyArray (3) = "Class"MyString = Join (MyArray)Msgbox MyString

LBound: Returns the smallest subscript for the indicated dimension of an arraySyntax:LBound (arrayname [, dimension])Arguments:arrayname:Name of the array variable; follows standard variable naming conventions.

dimension:Whole number indicating which dimension's lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension isomitted, 1 is assumed.

Example:1) Dim LArrLArr = Array (10, 20, 30)Msgbox Lbound (LArr, 1) 'Output 02) ''multidimensional arrayDim Lmarr(3,2)Msgbox LBound (Lmarr, 2) 'Output 0UBound: Returns the largest subscript for the indicated dimension of an arraySyntax:UBound (arrayname [, dimension])Arguments:arrayname:(Required) Name of the array variable; follows standard variable naming conventions.

dimension:(Optional) Whole number indicating which dimension's upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. Ifdimension is omitted, 1 is assumed.

Example:1) Dim UArrUArr = Array (10, 20, 30)Msgbox Ubound (UArr, 1) 'Output 22) ''multidimensional arrayDim Umarr (3, 2, 4)Msgbox UBound (Umarr, 1) 'Output 3Msgbox UBound (Umarr, 2) 'Output 2Msgbox UBound (Umarr, 3) 'Output 4Date/Time FunctionsDate: Returns the current system dateSyntax: Date

Example:Msgbox Date It displays the current system dateIsDate: Returns a Boolean value that indicates if the evaluated expression can be converted to a dateSyntax:IsDate(expression)ExapressionThe expression argument can be any date expression or string expression recognizable as a date or time

Example:Dim MyDate, YourDate, NoDate, MyCheckMyDate = "October 19, 1962"YourDate = #10/19/62# NoDate = "Hello"MyCheck = IsDate (MyDate) Returns True.MyCheck = IsDate (YourDate) Returns True.MyCheck = IsDate (NoDate) Returns False.Time: Returns a Variant of subtype Date indicating the current system time.Syntax: TimeExample:Msgbox Time It displays the current system time.DateAdd: Returns a date to which a specified time interval has been added.Syntax: DateAdd (interval, number, date)Arguments:Interval(Required) String expression that is the interval you want to add. See Settings section for values.

Number(Required) Numeric expression that is the number of interval you want to add. The numeric expression can either be positive, for dates in the future,or negative, for dates in the past.

Date(Required) Variant or literal representing the date to which interval is added.

SettingsThe interval argument can have the following values:SettingDescription

yyyyYear

qQuarter

mMonth

yDay of year

dDay

wWeekday

wwWeek of year

hHour

nMinute

sSecond

Example: NewDate = DateAdd("m", 1, "31-Dec-12")msgbox NewDate Return Value = 1/31/2013

DateDiff: Returns the number of intervals between two dates Syntax: DateDiff (interval, date1, date2 [, firstdayofweek [, firstweekofyear]])Arguments:Interval(Required) String expression that is the interval you want to use to calculate the differences between date1 and date2.

date1, date2(Required) Date expressions. Two dates you want to use in the calculation.

Firstdayofweek(Optional) Constant that specifies the day of the week. If not specified, Sunday is assumed.

Firstweekofyear(Optional) Constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1occurs.

Example:Diffdate = Datediff ("y","15-aug-10","15-aug-12")Msgbox Diffdate Return Value = 731

DatePart: Returns the specified part of a given date.Syntax: DatePart (interval, date [, firstdayofweek [, firstweekofyear]])

Arguments:Interval(Required) String expression that is the interval of time you want to return.

Date(Required) Date expression you want to evaluate.

firstdayof week(Optional) Constant that specifies the day of the week. If not specified, Sunday is assumed.

Firstweekofyear(Optional) Constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1occurs.

Example: GetQuarter = DatePart ("q", Date)Msgbox GetQuarter Day: Returns a whole number between 1 and 31, inclusive, representing the day of the month.Syntax: Day (date)Dateexpression represent a date. If date contains Null, Null is returned.

Example: MyDay = Day("Aug 15, 2010") Msgbox MyDay Return value = 15MyDay2 =Day ("15/8/2010")Msgbox MyDay2 Return value = 15

Month: Returns a whole number between 1 and 12, inclusive, representing the month of the year.Syntax: Month (date)DateExpressions represent a date. If date contains Null, Null is returned.

Example:Msgbox Month ("8-15-2010") Return value = 8Msgbox Month ("15/8/2010") Return value = 8Msgbox Month ("August 15, 2010") Return value = 8MonthName: Returns a string indicating the specified month.Syntax: MonthName (month [, abbreviate])Arguments:Month(Required) The numeric designation of the month. For example, January is 1, February is 2, and so on.

Abbreviate(Optional) Boolean value that indicates if the month name is to be abbreviated. If omitted, the default is False, which means that the month nameis not abbreviated.

Example: Msgbox MonthName (11, true) Return value = NovMsgbox MonthName (8, false) Return value = AugustMsgbox MonthName (9) Return value = September Weekday: Returns a whole number representing the day of the week.Syntax: Weekday (date, [firstdayofweek])Arguments:DateAny expression that can represent a date. If date contains Null, Null is returned.

FirstdayofweekA constant that specifies the first day of the week. If omitted, vbSunday is assumed.

Example:sMsgbox Weekday("August 15, 2013") Return value = 5WeekdayName: Returns a string indicating the specified day of the week.Syntax: WeekdayName (weekday, abbreviate, firstdayofweek)Arguments:weekday:(Required) The numeric designation for the day of the week. Numeric value of each day depends on setting of the firstdayofweek setting.

abbreviate:(Optional) Boolean value that indicates if the weekday name is to be abbreviated. If omitted, the default is False, which meansthat the weekdayname is not abbreviated.

firstdayofweek:(Optional) Numeric value indicating the first day of the week.

Example: Msgbox WeekdayName (5) Return value = Thursday Year: Returns a whole number representing the year.Syntax: Year (date)Arguments:date: Any expression that can represent a date. If date contains Null, Null is returned.

Example: Msgbox Year("15-08-2010") Rtuen value = 2010Msgbox Year("15/8/2010") Return value =2010Msgbox Year("November 01, 2010") Return value = 2010 Hour:Returns a whole number between 0 and 23, inclusive, representing the hour of the day.Syntax: Hour (time)Arguments:Timeis any expression that can represent a time. If time contains Null, Null is returned.

Example:Msgbox Hour(Now) Displays the current system hourMinute: Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.Syntax: Minute (time)Arguments:time:is any expression that can represent a time. If time contains Null, Null is returned.

Example:Msgbox Minute(Now) Displays the current system minute. Second: Returns a whole number between 0 and 59, inclusive, representing the second of the minute.Syntax: Second (time)Arguments:Timeis any expression that can represent a time. If time contains Null, Null is returned.

Example:Msgbox Second (Now) Displays the current system second. Now: Returns the current date and time according to the setting of your computer's system date and time.Syntax: NowExample:Msgbox Now Displays the current system date & time.

TimeSerial: Returns a Variant of subtype Date containing the time for a specific hour, minute, and second.Syntax: TimeSerial (hour, minute, second)Arguments:HourNumber between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.

MinuteAny numeric expression.

SecondAny numeric expression.

Example: Msgbox Timeserial (12,12,12) Return value =12:12:12 PM

TimeValue:Returns a Variant of subtype Date containing the time.Syntax: TimeValue(time)Arguments:Timeis usually a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be anyexpression that represents a time in that range. If time contains Null, Null is returned.

Example:Msgbox TimeValue("12:30:00") Return value =12:30:00 PM

Other Functions

CreateObject: Creates an object of a specified typeORCreates and returns a reference to an Automation objectSyntax:CreateObject (servername.typename [, location])Arguments:servername Required. The name of the application providing the object.

typenameRequired. The type or class of the object to create.

locationOptional. The name of the network server where the object is to be created.

Example:1) To create the Excel ApplicationSet xlobj = CreateObject (Excel.Application)2) To Create the Data base Connection ObjectSet DbConn = CreateObject(Adodb.Connection)3) To Create to Hold the Records in database TablesSet Rs = CreateObject(Adodb.Recordset)4) To Create the File System ObjectSet fso = CreateObject (Scripting.FileSystemObject)5) To Create Automation Object ModelSet aom = CrateObject (QuickTest.Application)Eval:Evaluates an expression and returns the resultSyntax:result = ]Eval(expression)Arguments:

result Optional. Variable to which return value assignment is made. If result is not specified, consider using the Execute statement instead.

ExpressionRequired. String containing any legal VBScript expression

Example:Dim VarVar = InputBox (Enter the var Type) Select Case Eval(TypeName(Var))Case "Integer" : MsgBox "Integer"Case "Dictionary" : MsgBox "Dictionary"Case "Nothing" : MsgBox "Nothing"Case "String" : MsgBox "String"End SelectUser-defined functionsFunctions and Library:If you have repeatable steps in a test or an action then consider using a user-defined function. User-defined functions will make your tests look shorter, easier to maintain, read and design. A user-defined function can then be called from within an action.Function: Set of statements grouped together with input parameters and output is predefined. The entity is given name and is invoked by the name. Once the function is defined, Next time onwards, if we need to invoke these set of statements just invoke the name given to it.Function Syntax:Function (parameterlist) = returnvalueEnd FunctionLibrary: If the function is written inside automation script that function is available only to the script in which it resides. To make the function available to other automation scripts as well we should transfer the function into library fileA Library can be prepared by adding one or more functions to itQuestion: When can the function be located? Inside library? Inside automation script?Ans: you can write the function either in the automation script (or) In the function library is available only to the automation script in which it is located.If the function should be shared across multiple automation scripts, then we write the function in the library fileAdvantages of writing/transferring function to Library All functions of the project will be existing at one place hence easily manageable Function of library are available to all automation scripts The library file can be sent across to any one by email The library file can be read by simple notepad applicationNote: QTP file contains too many folders and supporting files in it. Hence each QTP automation script is bulky(not flat file) file and it depends on size limitation of Email server to send the automation script fileCreate a Library file:Go to File> New > function libraryFirst you write a function in the automation script and check it is working fine. Once you are confident on the function copy the function into a text file and save the text file with the library How to access the function of Library file?To access the function of a library follow the steps here under Associate the library file to QTP Open the Script and invoke the function with function nameSteps to Associate library to QTP:1) Go to file > Settings

2) Go to Settings > Resources > Associated function libraries

3) Click on Add and select the your library file4) Click on Set as Default. Set as Default Button will make the library available to all automation scripts that are being developed using QTP in that machine.Different ways to associate the Function libraryBased on the type of framework you are using, you can use any of the following methods to associate function libraries to your QTP Script -1) By using File > Settings > Resources > Associate Function Library option in QTP.2) By using Automation Object Model (AOM).3) By using ExecuteFile method.4) Using LoadFunctionLibrary method.In the above methods we already explain 1st method so we can go to the remaining method2) Using Automation Object Model(AOM)QTP AOM is a mechanism using which you can control various QTP operations from outside QTP. Using QTP Automation Object Model, you can write a code which would open a QTP test and associate a function library to that test.Example: Using the below code, you can open QTP, then open any test case and associate a required function library to that test case. To do so, copy paste the below code in a notepad and save it with a .vbs extension.

'Open QTPSet objQTP = CreateObject("QuickTest.Application")objQTP.LaunchobjQTP.Visible = True'Open a test and associate a function library to the testobjQTP.Open "C:\Automation\SampleTest", False, False

Set objLib = objQTP.Test.Settings.Resources.Libraries'If the library is not already associated with the test case, associate it..If objLib.Find("C:\SampleFunctionLibrary.vbs") = -1 Then ' If library is not already addedobjLib.Add "C:\SampleFunctionLibrary.vbs", 1 ' Associate the library to the test caseEnd

3) Using ExecuteFile MethodExecuteFile statement executes all the VBScript statements in a specified file. After the file has been executed, all the functions, subroutines and other elements from the file (function library) are available to the action as global entities. Simply put, once the file is executed, its functions can be used by the action. You can use the below mentioned logic to use ExecuteFile method to associate function libraries to your script.Example: ExecuteFile D:\mylibrary.qfl

4 ) Using LoadFunctionLibrary methodLoadFunctionLibrary, a new method introduced in QTP 11 allows you to load a function library when a step runs. You can load multiple function libraries from a single line by using a comma delimiter.

Example:1) To Associate a single Function libraryLoadFunctionLibrary D:\mylibrary.vbs2) To Associate multiple function librariesLoadFunctionLibrary D:\myLibrary1.qfl,D:\Mylibrary2.txt,D:\Mylibrary3.vbsExamples of Functions:****************************************1) Write a function that perform arithmetic operations-Addition, Subtraction. Multiplication and division On two variablesFunction mathoperation (Byref x, Byref y, Byref arithmeticOperation)Dim zIf arithmeticOperation = Addition Then z = x + y mathoperation = zEnd ifIf arithmeticOperation = Subtraction Then z = x - y mathoperation = zEnd ifIf arithmeticOperation = Division Then z = x/y mathoperation = zEnd ifIf arithmeticOperation = Multiplication Then z = x * y mathoperation = zEnd if End Function returnvalue = mathoperation (20,10, Addition) returnvalue = mathoperation (20,10, Multiplication)**********************************************************************2) Write a Function to Launch websites Based on the keywordsYahoo, Google, Gmail, Facebook, TwitterFunction openwebsite (keyword) Here By default parameter value is ByRefIf keyword = Yahoo thenSystemutil.Run iexplore.exe,www.yahoo.comOpenwebsite = Yahoo application is launchedEnd ifIf keyword = Google thenSystemutil.Run iexplore.exe,www.google.comOpenwebsite = Google application is launchedEnd ifIf keyword = Gmail thenSystemutil.Run iexplore.exe,www.gmail.comOpenwebsite = Gmail application is launchedEnd ifIf keyword = Facebook thenSystemutil.Run iexplore.exe,www.facebook.comOpenwebsite = Facebook application is launchedEnd ifIf keyword = Twitter thenSystemutil.Run iexplore.exe,www.twitter.comOpenwebsite = Twitter application is launchedEnd ifEnd functionreturnvalue = openwebsite(Yahoo)returnvalue = openwebsite(Facebook)************************************************************Regular ExpressionRegular Expression IntroductionYou have created a document and saved it to your hard disk. After few days again you want to update that document, but you forgot where you saved. Now you started searching for that document. Do you go to every folder in hard disk to search for it? No. You will just use search window to search the document by using name. Unfortunately you didnt find any document on that name. So what will you do?Here exactly the concept ofRegular Expressionwill come in to the picture.A Regular Expression is a string that provides a complex search phrase.If you create a word document then you will search for *.doc. Here the * indicates any name which are there in specified disk.As per the definition,*is a regular expression which provides a phrase to match any name of the document.Phraseis an expression consisting of one or more words.I have used above concept to tell you that Regular Expressions are not new to us (Testers). Some how we used it in regular activities but we dont know that these are Regular Expressions.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: 1. Defining the property values of an object in Descriptive programming for handling dynamic objects2.For parameterizing a step 3. creating checkpoints with varying valuesUsing Regular Expressions in QTP: Test for a pattern within a string. To check for existence of substring in a string.For example, you can test an input string to see if a telephone number pattern or a credit card number pattern occurs within the string. This is called data validation. Replace text. To find and replace a string with another string.You can use a regular expression to identify specific text in a document and either remove it completely or replace it with other text. Extract a substring from a string based upon a pattern match. To get a string based on pattern match.You want all the words starting with A from a document, In this case you will use regular expression which will create pattern match and will return all words starting with A.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:

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 crg) Matching One or More Specific Characters:

A plus sign (+) instructs QTP to match one or more occurrences of the preceding character.For example: ca+r Matches car and caaaaaar, but not cr. 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: 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)

Regular Expressions has 3 properties 1. Global2. pattern3. Ingnore caseRegular Expressions has 3 methods1. Execute 2. Test3. ReplaceA regular expression is a string that describes or matches a set of strings. It is often called a pattern as it describes set of strings.Regular Expression CharactersThe below table contains the complete list of regular expression characters and behavior of them.CharacterDescription

\Marks the next character as either a special character or a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".

^Matches the beginning of input.

$Matches the end of input.

*Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".

+Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".

?Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never".

.Matches any single character except a newline character.

(pattern)Matchespatternand remembers the match. The matched substring can be retrieved from the resultingMatchescollection, using Item[0]...[n]. To match parentheses characters ( ), use "\(" or "\)".

x|yMatches eitherxory. For example, "z|wood" matches "z" or "wood". "(z|w)oo" matches "zoo" or "wood".

{n}nis a nonnegative integer. Matches exactlyntimes. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".

{n,}nis a nonnegative integer. Matches at leastntimes. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".

{n,m}mandnare nonnegative integers. Matches at leastnand at mostmtimes. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".

[xyz]A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".

[^xyz]A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".

[a-z]A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".

[^m-z]A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".

\bMatches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".

\BMatches a non-word boundary. "ea*r\B" matches the "ear" in "never early".

\dMatches a digit character. Equivalent to [0-9].

\DMatches a non-digit character. Equivalent to [^0-9].

\fMatches a form-feed character.

\nMatches a newline character.

\rMatches a carriage return character.

\sMatches any white space including space, tab, form-feed, etc. Equivalent to "[\f\n\r\t\v]".

\SMatches any nonwhite space character. Equivalent to "[^\f\n\r\t\v]".

\tMatches a tab character.

\vMatches a vertical tab character.

\wMatches any word character including underscore. Equivalent to "[A-Za-z0-9_]".

\WMatches any non-word character. Equivalent to "[^A-Za-z0-9_]".

\numMatchesnum, wherenumis a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.

\nMatchesn, wherenis an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.

\xnMatchesn, wherenis a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in regular expressions.

We can extend a regular expression by combining or grouping multiple regular expression operators. In this case we should follow the order of precedence.Order of PrecedenceRegular expressions are interpreted from left to right. The order of precedence when building a Regular Expressions isOrderOperator(s)Description

1\Escape

2(), (?:), (?=), []Parentheses and Brackets

3*, +, ?, {n}, {n,}, {n,m}Quantifiers

4^, $, \anymetacharacterAnchors and Sequences

5|Alternation

Escape (\)There are so many special characters in regular expressions. I have to verify 2*2=4 is available in the main text. For that I have to specify regular expression pattern as 2*2=4. But * will work like a regular expression and the verification will get fail. In this case the * should be considered as a literal character instead regular expression.Back Slash (\) character is useful to treat a special character as a literal character. Provide the Back Slash (\) character in precede of special characters which you want to treat as literal character.In the above situation we should use 2\*2=4 in the pattern.List of Special Characters in Regular Expressions$, ( , ) , *, + , ., [ , ], ?, \, ^, {, |Parentheses (())Parentheses used to group the matches.Brackets ([])You can create a list of matching characters by placing one or more individual characters within square brackets ([]). When characters are enclosed in brackets, the list is called a bracket expression. Within brackets, as anywhere else, ordinary characters represent themselves, that is, they match an occurrence of themselves in the input text. Most special characters lose their meaning when they occur inside a bracket expression.ParenthesesandBracketswill be explained detailed inAlternation.QuantifiersQuantifiers are used to specify the number of occurrences to match against or when we dont have the quantity of the characters are there to match.Ex:If we need to match a word Zoooo then we should write regular expression like Zo{4}. 4 indicate the number of os in the word Zoooo.Suppose we dont know how many times o exist in the word, but we expect at least twoos should available in the word. Then the regular expression will be like thisZo{2,}Here{2,}tells that at least two times the character should exist.List of Quantifiers*, + , ?, {n}, {n,}, {n,m}AnchorsAnchors do not match any characters. They match a position. These are used to specify which part of the string should be matched. The part is either beginning or end of a line or word.Ex:If we are verifying the word QTP is starting withQor not then we use regular expression like ^Q.Here carot(^)is not matching the character Q but it is matching the position of Q. Thats whatAnchorsdo.List of Anchors^, $, \b, \BAlternation (|)Alternation allows us to use a choice between two or more matches. It can be used to match a single regular expression out of several possible regular expressions.Ex:The below Regular Expression is to match a Date.Format: MM/DD/YYYY

MM:(0[1-9]|1[0-2])Min month number is 1 and Max Month number is 12

DD:(0[1-9]|1[0-9]|2[0-9]|3[0-1])Min Date number is 1 and Max Month number is 31

YYYY:([0-9][0-9][0-9][1-9]|[1-9]000|[1-9][1-9]00|[1-9][1-9][1-9]0)Min Year number is 1 and Max Year number is 9999 (Assume)In the above regular expression we have usedParentheses,BracketsandAlternation.Bracketsused to match values between the specified ranges.0[1-9]means, this expression should match numbers from01to09.Alternationusedto match a single regular expression from the specified regular expression matches.0[1-9]|1[0-2]means,use any one of the regular expression to match.Parenthesesusedtogroup all regular expression matches.(0[1-9]|1[0-2])means,use any one of the regular expression to match from this Group.Scripting Regular ExpressionsFrom VBScript 5.0 Microsoft provided facility to use Regular Expressions in Scripting Techniques.By using this we can write scripts to Test for a pattern within a string, to replace text and to extract a substring from a string based upon a pattern match.Using Regular Expressions in Scripting Techniques'To use Regular Expressions in scripting first we should create Instance of Regular Expression Class. Set SampleRegExP = New RegExp 'Set the Search Pattern (Regular Expression) SampleRegExP.Pattern= H.* 'Specify the Case Sensitivity is true or false SampleRegExP.IgnoreCase= False 'Specify required search results (True is for all search Results, False is for only one) SampleRegExP.Global=True 'Execute Search conditions on a main stringSet Matches = SampleRegExP.Execute(Hi How Are You) 'Get the results by using a For LoopFor Each Match in MatchesMsgbox Match.FirstIndexMsgbox Match.ValueNext'Script to extract a substring from a string based upon a pattern match.'************************************************rExpression="H."MainString="Hi How Are You" Set SampleRegExP = New RegExpSampleRegExP.Pattern= rExpressionSampleRegExP.IgnoreCase= FalseSampleRegExP.Global=TrueSet Matches = SampleRegExP.Execute(MainString) For Each Match in MatchesMsgbox Match.FirstIndexMsgbox Match.ValueNext'************************************************'************************************************'Script to Replace string'************************************************rExpression="H."MainString="Hi How Are You"ReplacedString= "Hello"Set SampleRegExP = New RegExpSampleRegExP.Pattern= rExpressionSampleRegExP.IgnoreCase= FalseSampleRegExP.Global=True Msgbox SampleRegExP.Replace (MainString,ReplacedString)'************************************************'Script to Test a string existencerExpression="H."MainString="Hi How Are You" Set SampleRegExP = New RegExpSampleRegExP.Pattern= rExpressionSampleRegExP.IgnoreCase= FalseSampleRegExP.Global=True retVal = SampleRegExP.Test(MainString)If retVal ThenMsgbox "One or more matches were found."ElseMsgbox "No match was found."End If '************************************************Error Handling in QTPError handling refers to the anticipation, detection, and resolution of programming, application, and communications errors.Within every Script we have to think about possible exceptions and how to handle them. Especially in the uppermost layers of the script, it is important to handle all exceptions.In QTP you have handled the Error Exceptions in the following ways1) In QTP Run Settings2) In VbScript (On Error statements)3) Recovery Scenarios4) Through conditional coding in Test Script 1) In QTP Run SettingsGoto File > Settings > Run > when errors occurring during run sessionChoose one option in the drop down when error occurring during run session. It will use to prevent Errors during run session

2) In VbScript (On Error Statements)On Error Statements1. On Error Resume Next2. On Error Go to 03. Error ObjectOn Error Resume Next:On Error Resume Next statement enables the Error handling in the code.If there is error in the code "On error Resume Next" ignores it and continue with next line of code. Note: With On Error Resume Next error is not corrected, just ignored, and an error message is not displayedOn Error Go to 0:On error got to 0 statement disables error handling we have previiously enabled it by using On Error resume Next.Error ObjectWhenever there is a run-time error in the program, the properties of an Err object are filled with the information that helps to identify and handle the error.After an On Error Resume Next statement the Err object's properties are reset to zero or zero-length strings ("").Because the Err object is an intrinsic (basic / its part of every vbscript project you create) object with global scope there is no need to create an instance of it in your code. That is it does not need to be declared before it can be used.PropertiesPurpose

DescriptionContains a string describing the error.

NumberContains the Error number. It is the default Property, means Err.Number is same as Err

HelpFileContains path to the help file

HelpContextIts a Context ID within the helpfile. The HelpContext property is used to automatically display the Help topic identified

Source Contains a string expression that is usually the class name or programmatic ID of the object that caused the error.

LastDLLErrorContains last error code generated by DLL;Available only on 32 bit windows systems.

MethodsPurpose

ClearClears all property settings o