Visual Basic Guidelines by V8r41E6

VIEWS: 13 PAGES: 30

									    QTP Scripting Guidelines




QTP Scripting Guidelines
                                                                                                                                                     QTP Scripting Guidelines


                                                            QTP Scripting Guidelines

                                                                           Table of Contents

Topic                                                                                                                                                                     Page No.
INTRODUCTION............................................................................................................................................................. 3
Purpose ............................................................................................................................................................................... 3
Scope of the Guideline ...................................................................................................................................................... 3
NAMING CONVENTIONS ............................................................................................................................................. 3
        Constant Naming Conventions .................................................................................................................................................... 3
Naming Functions ............................................................................................................................................................... 5
Functions and Procedures ................................................................................................................................................... 6
Creating strings for MsgBox, InputBox and SQL queries .................................................................................................. 7
IF and CASE Statements ..................................................................................................................................................... 7
Inter Module Communication ............................................................................................................................................. 8
Comments ........................................................................................................................................................................... 8
Inserting Comments ............................................................................................................................................................ 8
Adding Comments .............................................................................................................................................................. 9
Creating an Action Template ............................................................................................................................................ 10
Error Handling .................................................................................................................................................................. 13
Checkpoints....................................................................................................................................................................... 14
Checkpoints....................................................................................................................................................................... 15
IMPORTING THE DATA SHEET PROGRAMMATICALLY ................................................................................ 15

EXPORT THE DATA SHEET PROGRAMMATICALLY........................................................................................ 16

REGULAR EXPRESSION ............................................................................................................................................ 16

TESTING REPOSITORY FOLDER STRUCTURE ................................................................................................... 17

FORMULAS.................................................................................................................................................................... 17

APPLICATION PRE-REQUISITES FOR SCRIPT GENERATION .....ERROR! BOOKMARK NOT DEFINED.21

ADDING FILES TO RESOURCES .............................................................................................................................. 19

SPLITTING ACTIONS .................................................................................................................................................. 20

COMMAND TO STOP THE EXECUTION OF SCRIPT .......................................................................................... 21

CHECKING RETURN VALUES.................................................................................................................................. 22

RETURN VALUES FROM A FUNCTION ................................................................................................................. 23

SYNCHRONIZATION POINT ..................................................................................................................................... 24
Exporting and Loading User-Defined Environment Variables ......................................................................................... 27
LIMITATIONS OF QTP .............................................................................ERROR! BOOKMARK NOT DEFINED.36

GENERATING AUTOMATION SCRIPTS ................................................................................................................ 29

SETTING RUN TESTING OPTIONS ........................................................ERROR! BOOKMARK NOT DEFINED.44



                                                                                                                                                                        Page 2 of 30
                                                                                          QTP Scripting Guidelines


Introduction
Purpose                    This document is a compendium of conventions and programming guidelines
                           that can be gainfully used while developing Test Scripts for projects using
                           Quick Test Professional from Mercury. The tool reference is 6.5 and above.


Scope of the               The conventions suggested in this document are brief and suggestive and are
Guideline                  specific for QTP test case automation.

The topics covered in this guideline are:

       Naming conventions
       Regular Expressions
       Function naming conventions
       Comments
       QTP Settings
       Checkpoints
       Folder structure
       Creating formulas in Datatables



Naming Conventions
        Coding standards are language-specific programming rules that greatly reduce the probability of
introducing errors into your applications, regardless of which software development model (iterative,
waterfall, extreme programming, and so on) is being used to create that application

Coding conventions are designed to help you write code using Microsoft Visual Basic Script. Coding
conventions can include the following:
       Naming conventions for objects, variables, and procedures

       Commenting conventions

       Text formatting and indenting guidelines
The main reason for using a consistent set of coding conventions is to standardize the structure and coding
style of a script or set of scripts so that you and others can easily read and understand the code. Using good
coding conventions results in clear, precise, and readable source code that is consistent with other language
conventions and is intuitive.

Constant Naming Conventions
Constants, if used, are implemented as variables and distinguished from other variables using all uppercase
characters. Multiple words are separated using the underscore ( _ ) character. For example:
       USER_LIST_MAX

       NEW_LINE
Variable Naming Conventions ** Note: Variables should be defined in Hungarian Notation


                                                                                                      Page 3 of 30
                                                                                       QTP Scripting Guidelines

To enhance readability and consistency, use the following prefixes with descriptive names for variables in
your VBScript code.

Subtype        Prefix Example
Boolean        bln     blnFound
                       bytRasterDat
Byte           byt
                       a
Date(Time)     dtm     dtmStart
Double         dbl     dblTolerance
Error          err     errOrderNum
Integer        int     intQuantity
Long           lng     lngDistance
Object         obj     objCurrent
Single         sng     sngAverage
String         str     strFirstName



There are a number of qualifiers that are commonly used when dealing with a set of things (as in an array or
table). Consistent use of standard modifiers can significantly aid in code maintenance. Here is a list of
common modifiers and their meaning when applied to sets of things:

                Qualifier     Description                                Example
                Count         the number of items in a set               SelectedCount
                Min           the minimum value in a set                 BalanceMin
                Max           the maximum value in a set                 RateHigh
                First         the first element of a set                 CustomerFirst
                Last          the last element of a set                  InvoiceLast
                Cur           the current element of a set               ReportCur
                Next          the next element of a set                  AuthorNext
                Prev          the previous element of a set              DatePrev


 Naming Convention

 QTP Script Name

 Scenario Name                    Script Name


 S010-010 Main Sales                                               Combination of
 Process                          S010_010                         transaction codes

                                  Action Name
                                  Transaction Code like NA01

 Data Table                       Name
 Global Sheet                     Scenario ID
 Local Data Sheet Name            Transaction Code
                                                                                                   Page 4 of 30
                                                                                            QTP Scripting Guidelines

                                   Transaction Code_Attribute
 Attribute Name                    name                                NZ01_Purchaseorder

 Variables
 Variables should be defined in Hungarian Notation
 Subtype                        Prefix                                 Example
 Boolean                        bln                                    blnFound
                                                                       dtmPurchaseorde
 Date(Time)                        dtm                                 r

 Double                            dbl                                 dblTolerance

 Integer                           int                                 intQuantity



Naming Functions


All Function should begin with a brief comment describing what they do. This description should not
describe the implementation details (how it does it) because these often change over time, resulting in
unnecessary comment maintenance work, or worse, erroneous comments. The code itself and any necessary
inline comments describe the implementation.

Arguments passed to a Function should be described when their purpose is not obvious and when the
Function expects the arguments to be in a specific range. Return values for functions and variables that are
changed by a procedure, especially through reference arguments, should also be described at the beginning
of each procedure.

Function header comments should include the following section headings. For examples, see the
"Formatting Your Code" section that follows.

Section Heading               Comment Contents
Purpose                       What the procedure does (not how).
                              List of any external variable, control, or other element whose state affects this
Assumption
                              procedure.
Effects                       List of the procedure's effect on each external variable, control, or other element.
                              Explanation of each argument that is not obvious. Each argument should be on a
Inputs
                              separate line with inline comments.
Return Values                 Explanation of the value returned.

Remember the following points:
          Every important variable declaration should include an inline comment describing the use of the
           variable being declared.

          Variables, controls, and procedures should be named clearly to ensure that inline comments are only
           needed for complex implementation details.


                                                                                                        Page 5 of 30
                                                                                            QTP Scripting Guidelines

At the beginning of your script, you should include an overview that describes the script, enumerating
objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of
pseudocode describing the algorithm can be helpful.




Functions and               The arguments of a function should be declared with ByVal. This ensures that
Procedures                  arguments are passed by Value rather than by reference, thus preventing
                            modification of arguments within a function. Arguments should be passed by
                            reference only when required

Alternatively, one can use CALL and enclose the arguments within parenthesis (This ensures that arguments
are always passed by value)

       Argument types in functions should be explicitly declared. If not declared, they are treated as
Variant type

       The data type of the value returned by the function also should be explicitly declared as far as
possible. Otherwise, it is treated as a variant type

      When making a function call, the values returned by the function should be checked before
proceeding further. This should cover cases of errors

      Within a function, if an error occurs, the return value should be set to NULL. This ensures that
wherever the return value is used will also evaluate to NULL. This makes error handling easier

       Static variables should be used to pass flags etc., from one procedure to another

       Declaring a procedure as static automatically makes all variables within the procedure as static. This
should be avoided. Variables should be declared as static only when required

       Local variables are stored in a stack which has limited space. To avoid running out of stack space,
local variables should be used judiciously

Guidelines when coding function:

When you work with functions in QTP there are 2 types of function

        1) Built in function
        2) User define function

Built in functions are stored in library we have to simply call that function in our scripts.

User define functions are created using QTP/VB script in expert view.
You can declare function like.

        Function Function_Name1
               Logic1        Function Body
                    2
        End Function_Name1


                                                                                                        Page 6 of 30
                                                                                        QTP Scripting Guidelines

        Function Function_Name2
               Logic1
                    2        Function Body
        End Function_Name2

Using Call Function we can execute the Function

        Call Function_Name1
        Call Function_Name2

We can make our own reusable function library using .vbs file. We can keep all the function in one file and
call this file in our script expert view.

Using execute file statement.

        ExecuteFile “path \ file name”
        Call Function_Name1
        Call Function_Name2 (Parameter_1, Parameter_2)

Or we can store these .vbs file in our resource file then no need to use ExecuteFile statement in script. We
have to only call these functions in our script.

        Call Function_Name1
        Call Function_Name2 (Parameter_1, Parameter_2)


Creating strings for      When creating a long string, use the underscore line-continuation character to
MsgBox, InputBox          create multiple lines of code so that reading or debugging the string would be
                          easy. This technique is particularly useful when displaying a message box
and SQL queries           (MsgBox) or input box (InputBox) or when creating an SQL string.

        For example :
1. Dim Msg As String
Msg = "This is a paragraph that will be " _
         & "in a message box. The text is" _
 & " broken into several lines of code" _
   & " in the source code, making it easier" _
   & " for the programmer to read and debug."
   MsgBox Msg

2. Dim QRY As String
    QRY = "SELECT *" _
    & " FROM Titles" _
    & " WHERE [Year Published] > 1988"
    TitlesQry.SQL = QRY


IF and CASE               Two formats are supported while using IF statements. These are :
Statements
        IF (Condition) THEN
               (Statements)
        ENDIF
                                                                                                    Page 7 of 30
                                                                                        QTP Scripting Guidelines



        IF (Condition) THEN (Statements)

It is evident that the second format dose not have an ENDIF and is less readable. Hence, only the first format
should be used.

       Make sure that you branch correctly on equality. A very common mistake is to use > instead of >=
        or vice versa
       Put the normal case after the If rather than after the Else. Create the condition so that the Then
        clause corresponds to normal processing

      Care should be taken to ensure than an ELSE statement covers cases where none of the conditions are
true. Certain fatal errors may be missed by not having a ELSE statement

ELSEIF should be used with care. If it is being used to select one out of several conditions then it may be
advisable to use SELECT CASE instead

When using SELECT CASE, care should be taken to include CASE ELSE to cover cases not explicitly
handled

       When using the SELECT CASE, put the normal case first

To make case insensitive String comparisons, the Option COMPARE TEXT should be used in the modules

Inter Module
Communication

The only other alternative is through global variables.


Comments                   Comments should be used liberally in the code. In particular comments MUST
                           be used in the following :

        Inserting Comments
            A comment is a line or part of a line in a test script that is preceded by an
               apostrophe ('). When you run a test, QuickTest does not process comments.
               Use comments to explain sections of a test script in order to improve
               readability and to make tests easier to update.
               A comment statement is added to your test. If you are working in the Tree
                View, the icon indicates a comment. In the Expert View, a comment is
                specified with an apostrophe (‘).
               By default, comments are displayed in green in the Expert View. You can customize the
                appearance of comments in the Editor Options dialog box.

                To set highlighting preferences for script elements:
                1. Choose Tools > Editor Options. The Editor Options dialog box opens to the Options
                   tab. Click the Highlighting tab.

                2. Select a script element from the Element list.
                                                                                                    Page 8 of 30
                                                                                  QTP Scripting Guidelines

        3. For each script element you select, choose from the following options:

    Options                                             Description

Foreground       Sets the color applied to the text of the script element.

Background       Sets the color that is displayed behind the script element.

Text             Sets the text attributes applied to the script element. You can select Bold, Italic,
attributes       Underline, or a combination of these attributes.

Use defaults     Applies the background and foreground colors of the default style to the selected
for              style.

Font             Sets the font of the script element.

Size             Set the size, in points, of the script element.

Charset          Sets the character subset of the selected font.

        An example of each change you apply is displayed in the pane at the bottom of the
        dialog box.
        4. Click OK to apply the changes and close the dialog box.




   You can also add a comment line using VBScript’s Rem statement.

    Ex: Rem Window("Flight Reservation").Close
    In VBScript we don’t have separately Multi line comments. If we want to put multi line
    comments we use apostrophe (‘) only in multiple lines.


Adding Comments
        While programming, you can add comments to your tests.

    To add a comment:
    1. In the test tree, select a step and choose Insert > Step > Comment, or right-click a step and

        choose Insert Step > Comment. The Insert Comment dialog box opens.

    2. Type a comment and click OK.

    A comment statement is added to your test. If you are working in the Tree View, the

         icon indicates a comment. In the Expert View, a comment is specified with an
    apostrophe (‘).
   If you want to add the same comment to every action that you create, you can add the comment
    to an action template.

                                                                                              Page 9 of 30
                                                                                      QTP Scripting Guidelines

           Creating an Action Template
           If you want to include one or more statements in every new action in your test, you can
           create an action template. For example, if you always enter your name as the author of an
           action, you can add this comment line to your action template.

           To create an action template:
           1. Create a text file containing the comments, function calls, and other statements that you
              want to include in your action template.

           2. Save the text file as ActionTemplate.mst in your <QuickTest Installation Folder>\dat
              folder.

               Note: Only the filename ActionTemplate.mst is recognized as an action template.




1) Functions

Functions should have the following included in the comments:

1. Name of the function
2. Author of the function
3. The purpose of the function
4. The description of each of the parameters
5. The description of each of the return values
6. Specifics i.e. detailed description of the function
7. Amendment History: Modification date, person to modify, reasons for modifications (e.g. Change
Request or Defect reference), description of modification


'*********************************************************
‘Function Name: intFindUser
‘Author: Syam
' Purpose: Locates the first occurrence of a specified user in the User List array.
' Input Parameters: strUserList (): the list of users to be searched.
'                    strTargetUser: the name of the user to search for.
' Returns: The index of the first occurrence of the strTargetUser
'          in the strUserList array.
'          If the target user is not found, return -1.
'*********************************************************




‘ Amendment History
'*********************************************************
‘Modification date: 08/10/2004(MM/DD/YYYY)
‘Person to modify: Syam
                                                                                                 Page 10 of 30
                                                                                    QTP Scripting Guidelines

' Reasons for modifications: Change Request
' Description of modification: Added New temporary variable j for assigning new values.
'*********************************************************

Function intFindUser (strUserList (), strTargetUser)
  Dim i ' Defining Loop counter i.
  Dim j ‘Defining temporary variable j for assigning new values.
  Dim blnFound ' Defining flag blnFound.
  intFindUser = -1
  i = 0 ' Initialize loop counter
  Do While i <= Unbound(strUserList) and Not blnFound
    If strUserList(i) = strTargetUser Then
      blnFound = True ' Set flag to True
      intFindUser = i ' Set return value to loop count
    End If
    i = i + 1 ' Increment loop counter
  Loop
End Function ‘End Function “intFindUser“



2) Subroutines

Subroutines should have the following included in the comments:

    1.   Name of the subroutine
    2.   Author of the subroutine
    3.   The purpose of the subroutine
    4.   The description of each of the parameters
    5.   Amendment History: Modification date, person to modify, reasons for modifications ( e.g. Change
         Request or Defect reference ), description of modification

'*********************************************************
‘Subroutine Name: BinarySearch
‘Author: Syam
' Purpose: Checking Binary Search with the given input.
' Input Parameters: lower: compares with upper value.
'                   upper: compares with lower value.
'*********************************************************


‘ Amendment History
'*********************************************************
‘Modification date: 08/10/2004(MM/DD/YYYY)
‘Person to modify: Syam
‘Reasons for modifications: Change Request
‘Description of modification: Added New message box in Else condition.
'*********************************************************

                                                                                               Page 11 of 30
                                                                                       QTP Scripting Guidelines

sub BinarySearch(lower, upper)

        If lower > upper Then
              msgbox (False)
        Exit sub

        Else
                msgbox (True)
      End If
End sub


3) Blocks of code

All blocks of code should be commented. In-line comments should not state the obvious. Provide
meaningful comments describing what you are doing, why you have chosen a particular option, any external
factors that need to be known etc.

1)Function SubMatchTest(inpStr)
  Dim oRe, oMatch, oMatches
  Set oRe = New RegExp
  ' Look for an e-mail address
  oRe.Pattern = "(\w+)@(\w+)\.(\w+)"
  ' Get the Matches collection
  Set oMatches = oRe.Execute(inpStr)
  ' Get the first item in the Matches collection
  Set oMatch = oMatches(0)
  ' Create the results string.
  ' The Match object is the entire match - dragon@xyzzy.com
  retStr = "Email address is: " & oMatch & vbNewline
  ' Get the sub-matched parts of the address.
  retStr = retStr & "Email alias is: " & oMatch.SubMatches(0) ' dragon
  retStr = retStr & vbNewline
  retStr = retStr & "Organization is: " & oMatch. SubMatches(1)' xyzzy
  SubMatchTest = retStr
 End Function


2)
‘Checking expected tickets are displayed in the tickets text box or not.

Window("Flight Reservation").WinEdit("Tickets:").Check
CheckPoint ("2")
Window("Flight Reservation").WinEdit("Tickets:").Set "2"


4) Variables

All variables other than simple variables like counters should be described in comments. It is also important
that even in case of simple variable the name should be indicative of the purpose of that variable.

                Dim intMarks as int      ‘intMarks contains marks
                Dim strGrade as str      ‘StrGrade contains the Grade corresponding to
                                         ‘ the marks

                If intMarks > 90 Then
                       StrGrade=A
                Else
                       StrGrade=B
                                                                                                  Page 12 of 30
                                                                                        QTP Scripting Guidelines

                   End If
                            Msgbox (StrGrade, “Grade”) ‘ Displays Grade

5) Exits

           All exits out of a subroutine or function should be clearly commented


           sub BinarySearch(lower,upper)

                    If lower > upper Then
                   msgbox (False)
                           Exit sub
                   Else
                          msgbox (True)
                   End If

           End sub ‘ End of BinarySearch(lower, upper) subroutine

6) Loops

Where loops are nested, it is necessary to comment clearly the logic and conditions when the loop is exited.

‘This Conditional Statement will display the Message corresponding to the value

If value = 0 Then
    MsgBox value
  ElseIf value = 1 Then
    MsgBox value
  ElseIf value = 2 then
    Msgbox value
  Else
    Msgbox "Value out of range!"
 End If


Error Handling

 All the sub routines/ functions should have error handling.

 The statement ‘On Error GoTo line’ should be included. If you don't use an On Error statement, any
run-time error that occurs is fatal.

 If On Error Resume Next is used, you can place the error-handling routine where the error would occur,
rather than transferring control to another location within the procedure.

 The On Error Resume Next construct is preferable to On Error GoTo when handling errors generated
during access to other objects. Checking Err after each interaction with an object removes ambiguity about
which object was accessed by the code. You can be sure which object placed the error code in Err.Number,
as well as which object originally generated the error (the object specified in Err.Source).


                                                                                                   Page 13 of 30
                                                                                          QTP Scripting Guidelines

 An On Error Resume Next statement becomes inactive when another procedure is called, so you should
execute an On Error Resume Next statement in each called routine if you want inline error handling within
that routine.

 On Error GoTo 0 is used to disable error handling in the current procedure.

 Error-handling routines rely on the value in the Number property of the Err object to determine the cause
of the error. The error-handling routine should test or save relevant property values in the Err object before
any other error can occur or before a procedure that might cause an error is called. The property values in
the Err object reflect only the most recent error. The error message associated with Err.Number is
contained in Err.Description.

 All errors should be trapped and relevant message boxes should be displayed with the correct style (like
information, exclamation, critical etc.,).

 For expected errors like Connect Failed, Insert Failed, Delete Failed etc., messages should be taken from
the common list of error numbers and messages. For the application specific errors, the developer has to
provide a proper standardized message.

 The general format is
Sub XXX(Param 1, Param 2)
  On Error GoTo ErrorHandler
  ...
  Exit Sub
ErrorHandler:
  Error checking routine. . .
End Sub

 System errors during calls to dynamic-link libraries (DLL) do not raise exceptions and cannot be trapped
with Visual Basic error trapping. When calling DLL functions, you should check each return value for
success or failure (according to the API specifications), and in the event of a failure, check the value in the
Err object's LastDLLError property.


Checkpoints


                             Description                                          Use In
 Checkpoint Type                                       Example of Use
                                                                                Applications
Standard               Checks values of an        Check that a Push button          Yes
Checkpoint             object’s properties        is enabled or disabled.

                       Checks the property
                                                  Check that the image
Image Checkpoint       values of
                                                  source file is correct.
                       an image

                       Checks information in a Check that the value in a            Yes
Table Checkpoint
                       table                   table cell is correct.
                       Checks the               Check how long a Web
Page checkpoint
                       characteristics of a Web page takes to load or if a

                                                                                                     Page 14 of 30
                                                                                       QTP Scripting Guidelines


                      page                        Web page contains
                                                  broken links.
                      Checks that a text string   Check whether the             Yes
Text /                is displayed in the         expected text string is
Text Area             appropriate place in a      displayed in the expected
Checkpoint            Web page or                 location on a Web page or
                      application window          dialog box.

                      Checks an area of a
                      Web page
                      or application after        Check that a Web page
Bitmap Checkpoint     capturing                   (or any portion of it) is
                      it as a bitmap              displayed as expected.



                      Checks the contents of                                    Yes
Database              databases accessed by       Check that the value in a
Checkpoint            an application or Web       database query is correct.
                      site
                                                  Check if the images on a
                      Identifies areas of a
                                                  Web page include ALT
Accessibility         Web site
                                                  properties, required by the
Checkpoint            to check for Section
                                                  W3C Web Content
                      508 compliancy
                                                  Accessibility Guidelines.

                                                  Note: XML file
                                                  checkpoints are used to
                      Checks the data content     check a specified XML
XML Checkpoint        of                          file; XML application
                      XML documents               checkpoints are used to
                                                  check an XML document
                                                  within a Web page.


Checkpoints
                While working on QTP with will require to add following checkpoints.
                    Standard Checkpoint
                    Text / Text area Checkpoint
                    Table Checkpoint
                    Database Checkpoint




Importing the
data sheet
                                                                                                  Page 15 of 30
                                                                                          QTP Scripting Guidelines


programmatically



While importing the data sheet programmatically one can import the sheet into program.
By the following command one can enter the data.

datatable.ImportSheet [""],[],[""]

First bracket signifies the workbook name
Second bracket signifies on which sheet the operation has to be done
Third signifies the Global or local sheet where the data has to be entered.

e.g.
datatable.ImportSheet "C:\name.xls",1,"global"




Export the data
sheet
programmatically


While exporting the data sheet programmatically one can export the sheet from the program.By the
following command one can enter the data the from the data sheet to the file path specified by us.

DataTable.ExportSheet(FileName, DTSheet)
DataTable.ExportSheet "C:\name.xls" ,1



Regular expression


Regular expressions enable QuickTest to identify objects and text strings with varying values. A regular
expression is a string that specifies a complex search phrase. By using special characters such as a period (.),
asterisk (*), caret (^), and brackets ([ ]), one can define the conditions of the search.


       (*)----- All the matched characters will be displayed

       ([])---- All the characters within the range will be displayed

       (^)---- Matches the beginning of input

       (.)-----Matches a single line except the new line character



                                                                                                     Page 16 of 30
                                                                                      QTP Scripting Guidelines

Method 1
   ToolsObject RepositorySelect the variable to make regular expressionconstant/icon near the
   constant button check the regular expression box press OkPress Ok.


Method 2
   Select the object in tree view/expert view  right click select object propertiesselect the constant
   /icon near the constant buttoncheck the regular expression boxpress Okpress Ok



Testing
Repository Folder
Structure



     Local Machine
     Network Central Repository

On local machine QTP professional will store recorded scripts, documentation and communication in
different folder.

C:\Unilever_Proj\Module_name\Resourse_Lib
C:\Unilever_Proj\Module_name\Script1….Script2
C:\Unilever_Proj\Module_name\Report1….Report2
C:\Unilever_Proj\Module_name\Documentation
C:\Unilever_Proj\Communication

Central Repository will use to store all the QTP script, documentation and overall project level
communication. Users having read permission on all folders and on Shared Folder R/W permission. Only 1
person having R/W permission on all the folder.

…\Unilever_Proj\Shared_Folder
…\Unilever_Proj\Module_name\Resourse_Lib
…\Unilever_Proj\Module_name\Script1….Script2
…\Unilever_Proj\Module_name\Report1….Report2
…\Unilever_Proj\Module_name\Documentation
…\Unilever_Proj\Communication



Formulas



We can use the Formulas in the following topics.
   1. Using Formulas to create Parameterization Data
   2. Using Formulas in Check points.
   3. Using Formulas in the Data Table
                                                                                                 Page 17 of 30
                                                                                            QTP Scripting Guidelines



    1. Using Formulas to create Parameterization Data:
We can enter formulas rather than fixed values in the cells of a parameter column.

For example, suppose you want to parameterize the value for a Cell in the table that requires a date value no
earlier than today’s dates. You can set the cells in the Date column to the date format, and enter the =NOW()

Example:

Step 1:

Select A1 cell and Give the formula as: =Now()

Value for the formula: 8/10/2004 [d/mm/yyyy]

Excel formula into the first row to set the value to today’s date for the first iteration

(Note: We can format the cell based on the requirement.

Right click the cell  Format Cells  Date  Select the Required format. )

Step 2:

Then you can use another formula in the rest of the rows in order to enter the above date plus one day, as
shown below. By using this formula you can run the test on any day and the dates will always be valid.

Select A2 Cell and give the formula as: = (A1+1)

Value for the formula: 9/10/2004

    2. Using Formulas in Check points.
You can use a formula in a checkpoint to confirm that an object created on-the-fly (dynamically generated)
in an application contains the value it should for a given context

For example: Flight application

Step 1: insert a record.

Step 2: Put Standard Check point on Total Price.

ToolsStandard Check point Checkpoint Properties Screen Select Parameter option Click Edit
parameter option  In Advanced Configuration  select Use Data Table formula.  Click OK

Then two columns will be added in a Data table. Which are as follows:

             1) Total : TRUE/FALSE

             2) Total Price: $190.20


    3Using Formulas in the Data Table

    You can use any Microsoft Excel formula in your Data Table. This enables you to create contextually
    relevant data during the test run


                                                                                                       Page 18 of 30
                                                                                         QTP Scripting Guidelines

    Examples:

    =(A1+B1)
    =SUM(A1:F1) <range>
    =AVERAGE(A2:F2)
    =COUNT(A1,B2,A3)
    =IF(A1>78,"Pass","Fail")

When you use formulas in a Data Table to compare values (generally in a checkpoint), the values you
compare must be of the same type, i.e. integers, strings, etc. When you extract values from different places
in your applications using different functions, the values may not be of the same type. Although these values
may look identical on the screen, a comparison of them will fail,

for example, 8.2 is not equal to “8.2”. You can use the TEXT and VALUE functions to convert values from
one type to another as follows:

       TEXT(value) returns the textual equivalent of a numeric value, so that, for example,
        TEXT(8.2)="8.2".

       VALUE(string) returns the numeric value of a string, so that, for example, VALUE("8.2")=8.2.




                             The list of Library files associated with the Test can be included for a
Adding Files to            particular test through resources.
Resources



Purpose:

         The main purpose of adding Files to Resources is that when ever there is a Reusable Code, This
code can be kept in a File and that File can be added to the Resources of the particular Test where that code
is required.

There are Two ways to add files to Resources:

    1. Adding Files as Resources using menu options.
    2. Adding Files as Resources using Script.

    1. Adding Files as Resources using menu options.

        Different Steps for adding a file as a Resource to a Script:

        1.      Open a new Test or an existing Test Script.
        2.      Click on “Test” Menu Option and select “Settings” sub option.
        3.      A new “Test Setting” window appears, from there select “Resources” Tab.
        4.      Click “+” button in the “Resources” Tab and specify the path of the Files
                to be included.
                                                                                                    Page 19 of 30
                                                                                          QTP Scripting Guidelines



                         Thus the Files are Added to the Resources using menu options.

    2. Adding Files as Resources using Script:

        Different Steps for adding a file as a Resource to a Script:

              1. Create a ‘.vbs’ file and write the reusable code’s required as functions
                  in the file.
              2. Create a Test and just call the function for executing the reusable code.
             3. Open a new Script and create an application object using following code:

                 Dim qtApp ‘As QuickTest.Application ' Declare the Application object variable

                 Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object

                 qtApp.Launch ' Start QuickTest
                 qtApp.ActivateView "ExpertView" ' Display the Expert View
                 qtApp.Visible = True ' Make the QuickTest window visible

       4.       Open the Test here as follows:
                 qtApp.Open "C:\ Test1"
        5.       Add the following Code in order to add ‘.vbs’ file as resource, so that the Test
                Calling that particular function can be run:

                 Set qtLibraries = qtApp.Test.Settings.Resources.Libraries ' Get the_
                         ‘ libraries collection object

                         If qtLibraries.Find("C:\adding.vbs") = -1 Then
                         qtLibraries.Add "C:\ adding.vbs", 1
                 End If
        6.       Run the Test as follows:

                 Set qtTest1 = qtApp.Test
                 qtTest1.Run


        Thus the Files are Added to the Resources




                            Splitting an existing action into two sibling actions or into parent-child
Splitting Actions           nested actions.



Purpose:

The Purpose of Splitting actions is that when a part of the action should be made reusable, If we set total
action as reusable then the whole code in the action can be reused, but that should not happen. So, using


                                                                                                     Page 20 of 30
                                                                                          QTP Scripting Guidelines

split action we can split the action into two where the reusable code can be kept in one part, so that only that
part can be reused.

The Steps followed to Split an Action is as follows:
    1.        Select the step before which you want the new (second) action to begin.

    2.        Choose Step > Split Action, click the Split Action button, select Action > Split. The Split
              Action dialog box opens.

    3.        Choose one of the following options:

              Independent of each other—Splits the selected action into two sibling actions.

              Nested (the second action is called by the first)—Splits the selected action into a parent action
              whose last step calls the second, child action.

                         If you wish, modify the name and description of the two actions in the Name and
              Description boxes.

Following are the options which when disabled splitting can’t be done:

              1.   when an external action is selected

              2.   when the first line of the action is selected

              3.   while recording a test

              4.   while running a test

              5.   when you are working with a read-only test




                              The Command to stop the execution of the Script is ExitRun.
Command to stop ExitRun is the Command which Exits the test, regardless of its iteration
the execution of attributes.
script


Purpose:

When ever there is a possibility of occurrence of an Error or a Popup message which is unknown, then
application may get struck, when this situation arise there should be a mechanism where the Test needs to be
rerun, then using an ExitRun command we can quit from the present run and rerun the Test again.


Description
                                                                                                     Page 21 of 30
                                                                                      QTP Scripting Guidelines

Exits the test, regardless of its iteration attributes.

Note: The ExitRun statement and its return value are displayed in the Test Results.
Syntax

ExitRun(RetVal)

Argumen
                Type     Description
   t
             Varian    The return
RetVal
             t         value.

Example
The current example, exits the test and returns the value 0.

ExitRun(0)




                             This explains checking the return values from a checkpoint and also from
Checking Return              a synchronization point
values


Purpose:

The return values can be used to have a control over the script.


Return value: Checkpoint

To retrieve the return value of a checkpoint, you must add parentheses around the name of the checkpoint in
the statement.

For instance:
Dialog("Login").WinEdit("Agent Name:").Set "sssss"
a=Dialog("Login").WinEdit("Agent Name:").Check (CheckPoint("Agent Name:_2"))
Dialog("Login").WinEdit("Password:").SetSecure "40ce86b995224f97d0b562"
'Dialog("Login").WinEdit("Password:").Check CheckPoint("Password:_2")
Dialog("Login").WinEdit("Password:").Type micReturn
Window("Flight Reservation").Close

The return value of a checkpoint is of Boolean Type.




                                                                                                 Page 22 of 30
                                                                                        QTP Scripting Guidelines

Return value: Synchronization point

The waitproperty method used for synchronization returns TRUE if the property achieves the value and
returns FALSE if the timeout is reached before the property achieves the value.

Here too the arguments for the waitproperty method must be placed in the parenthesis.

For instance:
a=Window("Flight Reservation").WinEdit("Tickets:").WaitProperty ("enabled", 1,
10000)




                            This explains how to return value from a function.
Return values from
a function


For example consider the following snippet which explains how to return value from a function.

QTP script

ExecuteFile "C:\test.vbs"

msgbox subtract(30,15)

msgbox multiply(30,15)

msgbox divide(30,15)


Test.vbs file

function subtract(a,b)
  subtract=a-b
end function

function multiply(a,b)
  multiply=a*b
end function

                                                                                                   Page 23 of 30
                                                                                        QTP Scripting Guidelines

function divide(a,b)
  divide=a/b
end function

The thumb rule when you want to return a value from a function is to assign the value to be returned to the
function name. Here in the function subtract a-b value is assigned to the function name subtract and in the
script just mention the function name after including the ExecuteFile statement.




                            . This explains different ways of adding synchronization point and also
Synchronization             the recommended method of synchronizing.
point


Purpose:

Sometimes during test run, the application may not always respond with the same speed as the tool. For
example, it might take a few seconds:

For a progress bar to complete 100%
For a button to get enabled.

When this happens the running test fails due to run-time errors.

This kind of timing problems can be solved by making QTP to wait until the application finishes its task.
This concept is called synchronization. By synchronization we manipulate the speed of the tool and ensure
that the application and QTP are in sync with each other.


Ways of Synchronizing
   By adding Exist or Wait statements that instruct Quick Test to wait until an object exists or to wait a
       specified amount of time before continuing the test.
For example, the following statements instruct QuickTest to wait up to 20 seconds for the Flights
Table dialog box to open.

                                                                                                   Page 24 of 30
                                                                                           QTP Scripting Guidelines


y=Window("Flight Reservation").Dialog("Flights Table").Exist

if y=0

        Wait (2)

End if
         By inserting synchronization point, which instructs QuickTest to pause the test until an object
          property achieves the value you specify. When you insert a synchronization point into your test,
          QuickTest generates a WaitProperty statement in the Expert View.

Syntax: WaitProperty(Property Name, Property Value [, Timeout])
Property Name: The name of the property whose value is checked. This is of string type.
Property Value: The value to be achieved before continuing to the next step. This is of       variant type.
Timeout[optional]: The time, in milliseconds, after which QuickTest continues to the next step if the
specified value is not achieved. If no value is specified, QuickTest uses the time set in the Object
Synchronization Timeout option in the Run tab of the Test Settings dialog box.

         You can also increase the default timeout settings in the Test Settings and Options dialog boxes in
          order to instruct QuickTest to allow more time for certain events to occur.

Do’s and Don’ts
Though synchronization can be achieved using any of the above mentioned 3 ways. There are certain
disadvantages with them.
1. By adding wait statements explicitly we are making the tool to wait for specified no. of milliseconds for
an event to occur. The event may take place well ahead of the mentioned time. Then the tool waits
unnecessarily for an event which has already occurred. Consequently test run time increases.
2. By increasing the default timeout settings; if the event does not complete in the specified milliseconds,
then timeout occurs and QuickTest attempts to continue with the next step and the script fails. This method
is recommended only when one can identify the safest timeout before which the expected action is
performed.
3. The recommended way of synchronizing is by inserting a synchronization point. But this can be done
only when critical points in the application where synchronization is required is identified.




                                                                                                      Page 25 of 30
                                                                                            QTP Scripting Guidelines




Creation of                 INI files are a plain text file set up to store and retrieve settings.

INI file

Creation of INI file
         INI file is a plain text file set up to store and retrieve settings. These could be the user's personal
settings for running your program, or small pieces of data which need to be saved externally from the
program, such as the number of times or number of days that your program has been run. .INI files are not
for storing large amounts of data.


When we are working with QTP when you want to initialize run time parameters we have to set all the
parameters in .ini file.

Ini file control parameters like
       User-Defined Internal—variables that you define within the test. They are saved with the test and
        accessible only within the test in which they were defined.

       User-Defined External—variables that you pre-defined in the active external environment variables
        file. You can create as many files as you want and select an appropriate file for each test. Note that
        external environment variable values are designated as read-only within the test.

To create an external environment variables file:
    1. Open any text editor.
                                                                                                       Page 26 of 30
                                                                                        QTP Scripting Guidelines

   2. Type [Environment] on the first line.

   3. Type one variable-value pair on each line in the format—variable=value.

   4. Save the file in a location that is accessible from the QuickTest machine. The file must be a text file,
      but you can use any file name extension.

For example:

[Environment]

Param1=10

Param2=20



To select the active external environment-variables file:
   1. Choose Test > Settings to open the Test Settings dialog box.

   2. Click the Environment tab.

   3. Select the Load variables and values from external file (reloaded each test run) check box.

   4. Use the browse button or enter the full path of the external environment- variables file you want to
      use with your test.

To insert an external user-defined environment variable:
   1. In the Edit value section of the Object Properties, Object Repository, Method Arguments, or
      Checkpoint Properties dialog box, click Other as the type of parameter you want to use.

   2. Click the Edit Parameter Options button next to the parameter type box. The
   Parameter

      Options dialog box opens.

        Select Environment as the Parameter Type.

        Select the external user-defined parameter you want to use from the Name box. The variable
         type of the selected parameter is displayed below the Value box. The current value is displayed
         in the Value box.

        Note: If you modify the external user-defined parameter name, you create a new internal
         user-defined parameter. The external parameter still exists and cannot be modified from
         this dialog box.
        Click OK to close the dialog box
Exporting and Loading User-Defined Environment Variables



                                                                                                   Page 27 of 30
                                                                                      QTP Scripting Guidelines

         You have the option to export your user-defined, environment variables to an external text
file for use with other tests. You can then load the exported environment variable file into any test.
Internal environment variables are available only to the test in which they are defined.

To export user-defined environment variables:
   1. In the Environment tab of the Test Settings dialog box, click the Export button. The Save User-
      Defined Variables dialog box opens, enabling you to export the current list of user-defined variables
      and values to a text file.

   2. Choose the folder in which you want to save the file.

   3. Type a name for the text file in the File name box.

       Note: By default, QuickTest creates the file with an .ini extension. You can save it with
       another extension by typing the file name and extension in the File name box.
   4. Click Save to save your file.




                                                                                                 Page 28 of 30
                                                                                 QTP Scripting Guidelines


Generating Automation Scripts
The Properties tab of the Test Settings dialog box, the General tab of the Options dialog box, and
the Object Identification dialog box each contain a Generate Script button. Clicking this button
generates a automation script file (.vbs) containing the current settings from the corresponding
dialog box.

You can run the generated script as is to open QuickTest with the exact configuration of the
QuickTest application that generated the script, or you can copy and paste selected lines from the
generated files into your own automation script. You can see here the code generates for example.



For Example:

Dim App 'As Application

Set App = CreateObject("QuickTest.Application")

App.Launch

App.Visible = True

App.Test.Settings.Launchers("Web").Active = False

App.Test.Settings.Launchers("Web").Browser = 1

App.Test.Settings.Launchers("Web").Address = "http://newtours.mercuryinteractive.com "

App.Test.Settings.Launchers("Web").CloseOnExit = True

App.Test.Settings.Launchers("Windows Applications").Active = True

App.Test.Settings.Launchers("Windows Applications").Applications.RemoveAll

App.Test.Settings.Run.IterationMode = "rngAll"

App.Test.Settings.Run.StartIteration = 1

App.Test.Settings.Run.EndIteration = 1

App.Test.Settings.Run.ObjectSyncTimeOut = 20000

App.Test.Settings.Run.DisableSmartIdentification = False

App.Test.Settings.Run.OnError = "Dialog"

App.Test.Settings.Resources.DataTablePath = "<Default>"

App.Test.Settings.Resources.ObjectRepositoryPath = "<Per-action>"

App.Test.Settings.CaptureForTestResults = "Always"



                                                                                            Page 29 of 30
                                                  QTP Scripting Guidelines




App.Test.Settings.Resources.Libraries.RemoveAll




                                                             Page 30 of 30

								
To top