Qtp Advanced a Programmatic Approach

20
Advanced QTP – A programmatic approach Table Of Contents Introduction:............................................. 3 Why Expert View?..........................................3 1

Transcript of Qtp Advanced a Programmatic Approach

Page 1: Qtp Advanced a Programmatic Approach

Advanced QTP – A programmatic approach

Table Of Contents

Introduction:................................................................................................................3Why Expert View?........................................................................................................3Basic OOPS Concepts....................................................................................................3VB Script data Types:....................................................................................................3

Variant Sub types:..........................................................................................................4VB Script variables:........................................................................................................ 5Variable declaration:......................................................................................................5Types of Variables:.........................................................................................................5Multi dimensional arrays:..............................................................................................5

1

Page 2: Qtp Advanced a Programmatic Approach

Usage of Preserve keyword:..........................................................................................6Scope and life time of VB script variables:.....................................................................6

VB script operators:......................................................................................................7VB Script Conditional statements:................................................................................8Usage of Classes in VB script:.......................................................................................9Programmatic Description:.........................................................................................10

Static form of DP:.........................................................................................................11Dynamic Form of DP:...................................................................................................13

Working with child objects:........................................................................................13Pro’s and Cons of DP:.................................................................................................14Dictionary Object.......................................................................................................14

Advantages of using the “Dictionary Object”:..............................................................15References:................................................................................................................16

Introduction:

This material is mainly targeted for people who are well aware of QTP basics like recording and running a test case. Current times require users to have programming skills apart from basic record and playback to effectively automate an application.

Why Expert View?

A basic understanding of QTP, allows us to only record and playback a scenario. It does not allows us to allow us to handle synchronization issues, change in object properties during run-time nor does it perform any kind of computations and provide us with results.

2

Page 3: Qtp Advanced a Programmatic Approach

In brief, expert view helps us to build tests, with which we can handle the following

Synchronization issues due to page load or time taken to complete an operation Retrieve run time object properties i.e. obtaining the property of an object that

dynamically changes. Import test data (data driven testing) and export results from and to different data

sources. Perform comparisons, computations to come up with pass/fail criteria.

Any change made in the expert view will be correspondingly translated in the keyword view. All test actions, except the root Global action can be edited in the expert view.

To work with the expert view, one needs to have a basic understanding of the VB Scripting language, which is a programming language developed by Microsoft.

Basic OOPS Concepts

VB Scripting is an object oriented programming language and calls for basic understanding of OOPS concepts. The fundamentals of OOPS include an understanding of the 3 most important terms “Classes”, “Objects” and “Methods”.

Class: An entity that defines an object and its associated methods. Objects: An entity, which by itself has the following:

o Data: Refers to object properties.o Methods: The functions that can be used on the object

VB Script data Types:

VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript.

At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when used in a numeric context and as a string when you use it in a string context. That is, if you are working with data that looks like numbers, VBScript assumes that it is numbers and does what is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. You can always make numbers behave as strings by enclosing them in quotation marks (" ").

Variant Sub types:

3

Page 4: Qtp Advanced a Programmatic Approach

The different categories of information that can be contained in a Variant are called subtypes. Most of the time, you can just put the kind of data you want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains.The following table shows subtypes of data that a Variant can contain.

Subtype Description

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

Null Variant intentionally contains no valid data.

Boolean Contains either True or False. (The True keyword has a value equal to -1 and a False key word will have a value equal to 0)

Byte Contains integer in the range 0 to 255.

Integer Contains integer in the range -32,768 to 32,767.

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

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

Single Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.

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

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

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

Object Contains an object.

Error Contains an error number.

VB Script variables:

A variable is a placeholder which refers to a memory location where the intermediate data of a script is stored. In VB script you can get the value of the variable by referring its name.

All variables in VB script are of the fundamental data type discussed in the previous section called “Variant”

Variable declaration:

Variable declaration in VB script can be done whenever there is a need to declare one. However this practice is not a healthier one as the name of the variable can be misspelled at different

4

Page 5: Qtp Advanced a Programmatic Approach

places in the script. To avoid this one should use “option explicit” which will ensure that variable declarations are done explicitly in the script. “Option explicit” should be the first line of the script.

Note: When variables are initialized, a numeric variable is initialized to 0 and a string variable is initialized to a zero-length string (""). A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing.

Types of Variables:

There are two types of variables namely Scalar and Array variables. A scalar variable can hold a single value (can be an integer, string, object or a any of the variant sub types). We have one more variable type called Array variable using which one can create a series of variables. Array variables are created in the same way as scalar variables but in the case of Array variables, you should give the size of the Array variable.

Eg: Dim a ‘Scalar variableDim b(10) ‘ Array variable

In the above example “b” is an array variable which can hold 11 values i.e.., from 0 to 10. Please note that VB script is “0” based.

Multi dimensional arrays:

You can declare multiple dimensions by separating an array's size numbers in the parentheses with commas. In the following example, the arr1 variable is a two-dimensional array consisting of 3 rows and 4 columns:

Eg: Dim arr1(2,3)

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

You can also declare an array whose size changes during the time your script is running. This is called a dynamic array. The array is initially declared within a procedure using either the Dim statement or using the ReDim statement. However, for a dynamic array, no size or number of dimensions is placed inside the parentheses.

Eg: Dim arr2 ()Redim arr3 ()

“ReDim” is used to resize an array declared using Private, Public, or Dim statement.

5

Page 6: Qtp Advanced a Programmatic Approach

Usage of Preserve keyword:

When you resize an array there is a chance that the existing data in the array can be lost. We can prevent this by using Preserve key work when re-sizing a dynamic array using ReDim statement.

Eg: ReDim Array1 (10)ReDim Preserve Array1 (15)

In the above example, all the 11 values stored in Array1 are preserved and the capacity of the array is increased by 6.

However when you diminish the size of a dynamic array the values from the last index of the array would be lost.

If you use the Preserve keyword, you can resize only the last array dimension, and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.

Eg: ReDim Array2 (4,5,6)ReDim Preserve Array2 (4, 5, 9)

Scope and life time of VB script variables:

The scope of a variable depends on where it is defined. Following table gives the scope of variables declared in different places:

A variable declared inside a procedure The scope of the variable lies inside the procedure where it is defined. The lifetime of the variable ends after the last line of this procedure is executed

A Variable declared out of a procedure The scope of the variable extends to all the procedures in the current script as it is a script level variable. The life time of this variable ends when the script completes execution

Public variables Public <variable Name>. The scope of this variable extends through out the script

VB script operators:

6

Page 7: Qtp Advanced a Programmatic Approach

Like any other programming language VB script supports the following operations on Data. VB script has Arithmetic, logical and comparison operators.

Arithmetic operators:

Description Symbol

Exponentiation ^

Unary negation -

Multiplication *

Division /

Integer division \

Modulus arithmetic Mod

Addition +

Subtraction -

String concatenation &

Logical operators:

Description Symbol

Logical negation Not

Logical conjunction And

Logical disjunction Or

Logical exclusion Xor

Logical equivalence Eqv

Logical implication Imp

VB Script Conditional statements:

One use of conditional statements is to pass or fail a test step or to route the execution to a different path. For example, we can validate the run time state of an object using conditional statements and we can report the status of a test step. As in any programming language VB script supports the following conditional statements:

1. if –elseif2. Switch case

7

Page 8: Qtp Advanced a Programmatic Approach

Syntax of if – else:If <condition> then…….statements……………..…………………………….………………………..Elseif <condition> then ‘Please note that period is not allowed in between else and if

…………statements……………….…………………..Else……..statements……………………End ifExample:If Browser(oBrowser).Page(oPage).WebElement(oWebelement).Exist(5) then

sStatus = “Pass”reporter.reportevent micPass, “Test step name”, “test step description”

elseif then sStatus = “Fail”reporter.reportevent micFail, “Test step name”, “test step description”

elseExitTestIterationend if

Select case statements: A better way to choose between several alternatives is the Select Case statement.

Syntax: Select case <RO value>

Case “<value1>”…..statements……….…………………Case “<Value2>”……..statements………..………………Case Else ‘ This is smilar to default case in C…..statements……….…………..End Select

Example:Select case Browser(oBrowser).Page(oPage).Link(oLink).GetROProperty(“innerhtml”)

Case “Assignments”Browser(oBrowser).closeCase “Sessions”Browser(oBrowser).Page(oPage).Link(oLink).click

8

Page 9: Qtp Advanced a Programmatic Approach

Case ElseExitTestIteration

End Select

Usage of Classes in VB script:

Classes in QTP have a local scope with in the library files where the class is defined. To access a member function of a class from action script, one should call a function and in the definition of function construct a relation ship with the class. To put it in a more clear way:

Programmatic Description:

When a particular action is recorded, QTP stores the object in the Object Repository. During script playback, QTP finds the Object in Object Repository using object Logical Name and Object Hierarchy. QTP retrieves test object properties from OR. QTP searches actual application for the object with the same properties as the OR test object and performs user action.

Before we get into the concept of programmatic description, we need to know the pros and cons of using the Object Repository.PROS:

GUI Front end to examine all the objects in the repository Highlight in Application feature is great tool to walk the object tree No need to modify the script when object properties changes Easy to identify objects in AUT by Object Logical names Can be created independently from scripts

9

Action script calls a function which acts a constructor to the class defined a library

Class myClassFunction myFunctionMsgbox “in function”

End functionEnd class

Function cReateConstructor()Set x = new myClassx.mFunction()End Function

Page 10: Qtp Advanced a Programmatic Approach

CONS: Additional layer to maintain Unnecessary objects can be created Multiple users cannot concurrently save/write to the shared OR It won’t eliminate the need for Descriptive Programming in most of cases

Descriptive programming can be mainly used to bypass the OR. This is one of the key concepts in programming using the expert view, since the user can create objects similar to ones existing in the OR.

Descriptive programming can be used to encounter certain situations like:

1) One place where DP can be of significant importance is when you are creating functions in an external file. You can use these function in various actions directly, eliminating the need of adding object(s) in object repository for each action [If you are using per action object repository]

2) DP can be used when you want to perform the same operation on several objects with certain matching properties. For instance if you have a page where there are 100 checkboxes and the user has to click any one of them, it would be advisable if all these objects are not present in the OR. If the size of the OR increases, performance of QTP decreases. Moreover in this particular scenario, if OR is used, the error message, “Object’s description matches more than one of the objects currently displayed in your application" would be displayed.

3) DP is also useful in situations where the script has to handle dynamic objects. For instance, based on the details provided by the user in one page, a list box may or may not appear in the next page.

4) Modification to a test case is needed but the Object repository for the same is Read only or in shared mode i.e. changes may affect other scripts as well.

5) When using an Object Reference in an External Function, it is difficult to make sure if the relevant object has been defined in the Calling Action’s Object Repository or Even if it is defined, does it have the same Logical Name?

6) In certain cases, an object may change its hierarchy i.e. an object may appear under a different parent each time.

There are 2 approaches to DP. They are Static and Dynamic.

Static form of DP:

Static, as the name suggests, is directly providing a set of key (property) value pairs that define the object. The basic syntax is as follows:

<Object>(“<Property>: = <Value>”)

Below is an example of launcing an IE browser from the Start menu in Windows, navigating to the URL http://www.google.co.in/ and searching for the string “QTP”.

10

Page 11: Qtp Advanced a Programmatic Approach

Below is how the script would look if it was recorded.

Ex: 1 (using OR)

1) SystemUtil.Run "Internet","","","open"2) Browser("Browser").Page("Page").Sync3) Browser("Browser").Navigate "http://www.google.co.in/"4) Browser("Browser").Page("Google").WebEdit("q").Set "QTP"5) Browser("Browser").Page("Google").WebEdit("q").Submit

This is how the script would look, if static method of descriptive programming is employed.

Ex: 2 (static)

1) SystemUtil.Run "Internet","","","open"2) Browser("Title:=Browser").Page("Title:=Page").Sync3) Browser(“Title:=Browser”). Navigate http://www.google.co.in/4) Browser(“Title:=Browser”).Page(“Name:=Google”).WebEdit(“Name:=q”).Set “QTP”5) Browser(“Title:=Browser”).Page(“Name:=Google”).WebEdit(“Name:=q”).Submit

It is evident that DP has been employed from the 3rd step. When using DP from a specific point in the test, the user must continue to use DP from that point onwards. If a test object is specified by its OR name after other objects in the hierarchy have been specified using DP, QTP will not be able to identify the object.

For e.g. Browser(“Browser”).Page(“Title:=Google”).WebEdit(“Name:=q”).Set “QTP”

The following statement can be used if the “Browser” is present in the OR.

However, the statement stated below, can’t be used.

Browser(“Title:=Browser”).Page(“Title:=Google”).WebEdit(“q”).Set “QTP”

In this case, the user has started to use DP. When QTP comes across the part WebEdit(“q”), it will try to find the object in OR and the statement will fail.

Static form of DP can be also used to specify multiple properties.

For e.g. Browser(“Title:=Browser”).Page(“Title:=Google”).WebEdit(“Name:=q”, height:=400).Submit

This would attempt to identify the webEdit object with logical name “q” and height 400.

By now all of you might be wondering how it’s possible for a person who is going to code with DP to know the peoperties and values of the web/window objects. This is mainly provided in a

11

Page 12: Qtp Advanced a Programmatic Approach

data sheet by the developers, else a simple way would be to use the “Object Spy” tool to highlight the object in the application and learn it’s properties.

Furthermore, DP also recognizes regular expressions, if the user is not aware of the exact value of the property.

e.g. Browser(“Title:=Browser”).Page(“Title:=*Google*”).WebEdit(“Name:=q”, “innerhtml:=q”).Submit

This would attempt to find the page with title “Google” preceded and followed by any number of characters.

Incase the statement Browser(“Title:=Browser”).Page(“Title:=Google”), is used several times in the script, the user can assign the value to a variable and use this variable henceforth.

The script in that case would be as follows:

1) SystemUtil.Run "Internet","","","open"2) Browser("Title:=Browser").Page("Name:=Page").Sync3) Browser(“Title:=Browser”). Navigate http://www.google.co.in/4) Set myBrowser = Browser(“Title:=Browser”).Page(“Name:=Google”)5) myBrowser. WebEdit(“Name:=q”).Set “QTP”6) myBrowser. WebEdit(“Name:=q”).Submit

Static form of descriptive programming, though easier has few drawbacks and the dynamic method provides more flexibility and robustness.

Dynamic Form of DP:

In the Dynamic method, user will have to define a description object. A description object is a collection of property objects, where a property object specifies a property name and value.

Creation of the description object is done using the “Description.Create” statement. Once this is done, the user can go ahead and specify multiple properties and values to the object. Ex 3: (dynamic)

1) SystemUtil.Run "Internet","","","open"2) Browser("Browser").Page("Page").Sync3) Browser("Browser").Navigate "http://www.google.co.in/"3) Set myObj=Description.create()4) myObj(“micclass”).Value= “Browser”5) myObj(“Title”).Value= “Browser”6) Set myObj1=Description.create()7) myObj1(“micclass”).Value= “Page”8) myObj(“Title”).Value= “Google”9) Set myObj2=Description.create()10) myObj2(”micclass”).Value= “WebEdit”

12

Page 13: Qtp Advanced a Programmatic Approach

11) myObj2(“Text”).Value=”q”12) Set myObj3=Description.create()13) myObj3(“Text”).Value=”Submit”14) myObj3(“micclass”).Value= “WebButton”12) Browser(“myObj”).Page(“myObj1”).WebEdit(“myObj2”).Set “QTP”13) Browser(“myObj”).Page(“myObj1”).WebButton(“myObj3”).Click

Working with child objects:

The example sited below, would help get the count of the number of edit boxes present in the site “http://labs.google.com/sets”.

1) SystemUtil.Run "Internet","","","open"2) Browser("Browser").Page("Page").Sync3) Browser("Browser").Navigate http://labs.google.com/sets4) Set editBox = Description.create()5) editBox(“micclass”).Value =”WebEdit”6) Set Edits = Browser("Google Sets").Page("Google Sets").ChildObjects(editBox)7) MsgBox "Number of Edits: " & Edits.Count

When this script is executed, the string “Number of Edits: <no>” would be displayed in a message box.

The following script would provide an insight of how to dynamically handle the edit boxes in the application1) SystemUtil.Run "Internet","","","open"2) Browser("Browser").Page("Page").Sync3) Browser("Browser").Navigate http://labs.google.com/sets4) Set editBox = Description.create()5) editBox(“micclass”).Value = “WebEdit”6) Set Edits = Browser("Google Sets").Page("Google Sets").ChildObjects(editBox)7) Edits(0).Set “edit box 1”

In this example the index “0” is used to refer to the first edit box. QTP enters the string “edit box 1” in the first edit box.

The following is an example to enter text in all the edit boxes in one stretch

1) SystemUtil.Run "Internet","","","open"2) Browser("Browser").Page("Page").Sync3) Browser("Browser").Navigate http://labs.google.com/sets4) Set editBox = Description.create()5) editBox(“micclass”).Value = “WebEdit”6) Set Edits = Browser("Google Sets").Page("Google Sets").ChildObjects(editBox)7) count = Edits.Count8) For i = 0 to count

13

Page 14: Qtp Advanced a Programmatic Approach

9) Edits(i).Set “edit box” &(i+1)10) Next

These scripts would work irrespective of the number of edit boxes present in the page, as the dynamic count is retrieved from the script.

Pro’s and Cons of DP:

PROS: It’s a white box Compatible with different QTP versions Code portability is high Easy to mass update

CONS: Lower Code Readability and requires more comments, like “what object is accessed” Potentially slower to create To highlight an object in the application requires utilizing the “Highlight” method

Dictionary Object

Dictionary object is similar to an associative array. Every unique key presnt in the dictionary object has a corresponding value.

Advantages of using the “Dictionary Object”:

1) One advantage of using a dictionary object is that the values assigned to the variables can be accessed from all actions (local and external).2) Any amount of run time values can be stored to and retrieved from the dictionary object.3) We can use this as one of the parameterization techniques to pass values in QTP.

The class which is used to create the dictionary object is called “Scripting.Dictionary”.

A simple example is shown below to illustrate the usage of the dictionary object.

1) Set dictObj = CreateObject(“Scripting.Dictionary”)2) dictObj.Add “a”, 13) msgBox dictObj(“a”)

This would display the value “1” in the message box. The first 2 statements can be present in one action say Action 1. If the 3rd statement is executed from another action say Action 2, it would still work as dictionary objects are accessible from all actions.

14

Page 15: Qtp Advanced a Programmatic Approach

Some of the methods associated with the dictionary object are:

1) Items Method (object.Items( ) ) Returns an array containing all items in the dictionary object.2) Exists Method (object.Exists(key)) Returns true if a specified key exists in the Dictionary object, false if it does not.3) Keys Method (object.Keys( )) Returns an array containing all existing keys in a Dictionary object.4) Remove Method (object.Remove(key)) Removes a key, item pair from a Dictionary object. 5) RemoveAll Mthod (object.RemoveAll)) The RemoveAll method removes all key, item pairs from a Dictionary object. Example: This example creates a scripting.dictionary object and this scripting.dictionary object holds the parameters of a web object. The properties of the web object are set using this.

Using this approach can reduce the number of functions to declare and initiate a web object.

Dim GUIElementPublic a ‘Here a hold a scripting.dictionary object. This variable scope is set to public so that this variable ‘can be passed as a parameter to a function written in a different library.

Set a = CreateObject("Scripting.Dictionary")Set GUIElement = CreateObject("Scripting.Dictionary")GUIElement.Add "oBrowser", "Base camp (software) -"GUIElement.Add "oPage”, "Basecamp (software) -"GUIElement.Add "micclass", "WebElement" GUIElement.Add "innertext", "Features"GUIElement.Add "html tag", "SPAN"GUIElement.Add "Class", "toctext"act1 = "highlight"‘ Getting the keys of the scripting.dictionary GUIKeys= GUIElement.Keys

‘Below line will create an object

Set GUIObjects = description.Create

‘The below loop will set the properties of the objects in one shot.

For i = 2 to GUIElement.count-1GUIObjects (GUIKeys(i)).value = GUIElement(GUIKeys(i))Next

Browser(GUIElement(GUIKeys(0))).Page(GUIElement(GUIKeys(1))).Link(GUIObjects).highlight

15

Page 16: Qtp Advanced a Programmatic Approach

References:

1. MSDN website

16