Descriptive Programming In QTP

This article provides the details about:
  • Introduction to Descriptive Programming 
  •  Advantages of Descriptive Programming
  • Writing Descriptive Programming
  • When and Where to use the Descriptive Programming
  • Points to note with Descriptive Programming

Introduction to Descriptive Programming:
Descriptive programming is mainly used to perform the actions on objects which are not present in the object repository or we can simply tell that the entering/providing the object information directly into the test script is called Descriptive Programming.

Advantages of Descriptive Programming:
01.Maintenance is easy as the resources are less.
02.Script are portable as we can run the scripts from any machine.
03.We can start the test execution process before the application is ready.

Wring Descriptive Programming:
We have 2 ways to write the Descriptive programs.

01.Static Programming / Giving the description in the form of string arguments.
02.Dynamic Programming / Creating properties collection object for the description.

01.Static Programming:
This is most commonly used method in which the object description is directly passed into the script by specifying the "property:=value" pairs.It directly describes the object instead of specifying an object's name.
 

Syntax:TestObject("PropertyName1:=PropertyValue1","....","PropertyNameX:=PropertyValueX")

Example:
InvokeApplication "c:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("text:=Login").Activate
Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set "STC"
Dialog("text:=Login").WinEdit("attached text:=Password:").SetSecure password
Dialog("text:=Login").WinButton("text=Login").Click

Note:
Dialog,WinEdit,WinButton  - Test objects
text, attached text - Property Names
Login,Agent Name:, Password:, - Property Values - Represents the logical names of the objects

If we feel that the property information is not sufficient to identify the object uniquely we can add more property information.If we want to get the object names we can use object spy feature which is present in the object repository manager.
If we want to maintain the objects information in a centralized location then we can use Constants.
Example:
Const Login="text:=Login",Agent ="attached text:=Agent Name:"
Const Pwd ="attached text:=Password:", WBut ="text:=OK"

Note:We can declare n-number of contants in a single line separated by comma(,). But we need to use the word Const if we are going for a new line.

Creating Library:
01.Copy the above declared constants to a notepad and save it as a .vbs file.
02.Associate the vbs file to File> Settings> Resource> Click (+) icon> Browse the path of the vbs file and select the vbs file and then click on Apply, OK buttons or the library file can be loaded dynamically.

Syntax: ExecuteFile "path of the vbs file"
Example Of Creating Script using constants:
InvokeApplication("c:\Program Files\HP\QuickTest Professional\
Dialog(Login).Activate
Dialog(Login).WebEdit(Agent).Set "STC"
Dialog(Login).WebEdit(Pwd).SetSecure password
Dialog(Login).WinButton(OK)

Advantages of the static programming: The main advantage of using library in static programming is that the changes can be easily done as the variable are declared in a common location.

02.Dynamic Programming:
This is also similar to the static programming. But the only difference is that it collects all the properties of a particular object in an instance of that object.By using that the object can be referenced easily by using the instance instead of the string arguments.

Steps:
01.Create the description of the object.
Syntax:Set Variable=Description.Creare
Ex: Set Login = Description.Create
02.Enter properties information into the description of the object.
Syntax: Variable("Property Name").value ="Property Value"
Ex:Login("text").value = "Login"
03.Generating statements using description objects
Syntax:TestObject(Description Object").Method
Ex:Dialog(Login).Activate

Creating propeties Collection Of Objects:
Set oLogin = Description.Create
Set oPassword = Description.Create
Set oUname = Description.Createc
Set oOK = Descrption.Creae

Enter the properties information into objetcs:
oUname("attached text").value="Agent Name:"
oPassword("attached text').value ="Password:"
oOK("text").value="OK"

Generating Tests using properties collection objects:
InvokeApplication "c:\Program Files\ HP\ QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog(oLogin).activate
Dialog(oLogin).WinEdit(oUname).Set "STC"
Dialog(oLogin).WinEdit(oPassword).SetSecure password
Dialog(oLogin).WinButton(oOK).click
 

We can create the library files like static programming by following the below mentioned steps.

01.Create description objects and put into one library, by associating that library file,we can generate tests.
02.Dynamic programming is little bit difficult in preparation that the static programming but maintenance is easy.

QTP Settings Global Configuration

This article explains the details about the object identification and configuration.
 

As we know that there are around 25-30 object properties are available for each object in QTP. But QTP recognizes them by using only 2 to 3 properties.

By default QTP has certain configuration for each environment. We can add more properties if we feel that the default properties are not enough to identify the object.

In this article am going to explain the various object identification configurations available in QTP.

01.Normal Identification:
In this type of configuration,QTP uses two types properties to identify the object uniquely.
   a. Mandatory Properties
   b. Assistive Properties
In this configuration,QTP learns all mandatory properties at a time and thinks whether these properties are sufficient to identify the object uniquely. If it feels the properties are sufficient to identify the object uniquely then it stops learning.Otherwise,it learns the first assistive property once and stops and thinks and keep on repeating the steps until the object is uniquely identified.At the end of the assistive properties if QTP feels that the properties are not sufficient it finally goes to Ordinal Identifier.

02.Smart Identification:
In this type of configuration, QTP uses two types of properties to identify the object uniquely.
  a.Base filter properties
  b.Optional properties
This is an optional configuration.If we feel that the normal configuration is not enough to identify the object we can go for Smart Identification configuration. In this QTP learns all base filter properties at a time and thinks whether the properties are sufficient to recognize the object uniquely.If QTP feels the properties are sufficient then it stop learning.Otherwise, it goes to the optional filter properties and learns one by one.Then QTP keep on repeating the same step if it feel the properties are not sufficient. At the end of the assistive properties if QTP feels that the properties are not sufficient it finally goes to ordinal identifier.

03.Ordinal Identifiers:

We have 3 types of Ordinal Identifiers in QTP.
   a.Index
   b.Creation Time
   c.Location

Index: This one is based on the sequence of the programs. It starts from Zero.
Creation Time:This one is based on the loading time of the web objects.It starts from Zero.
Location: This one is based on the object location on the AUT. It starts from Zero.

Settings:
Since QTP is a stand alone application, it's is not possible to configure the settings as Global. But QTP is providing a feature called "Generate Script" to configure the settings as Global.
 

01.The settings are available in 3 areas.
    a.File> Settings
    b.Tools> Options
    c.Tools> Object Identification
02.Configure the required settings and generate scripts.
03.The script should be stored in VBS format and shared with the team members.
04.Launch the generated script across n-number of PCs to get the same settings.

How to record a script in QTP?

This article explains the steps to be followed to record a script in QTP. Recording script in QTP is very useful for the beginners. We have to follow a certain steps to record a script.

01.Launch the QTP tool.
02.Click on Record button or Press F3 on QTP tool and observe that a pop up window is opened. This window will be opened automatically whenever the "Record" button is pressed.
03.Observe that the pop up window is opened with "Record and Run Settings" tab for each environment based on the add in configured/selected.
  Assume that we have Oracle, SAP add ins are configured along with the default Windows and Web environments.So, the pop up will be opened with Record and Run Settings tabs for Web,Windows, Oracle and SAP environments provided that the add ins are loaded when QTP launched.
04.For any environment the record and run settings are classified into two generic groups.


  • Record and Run on ANY window belonging to the particular environment.
  • Record and Run on a SPECIFIC window belonging to the particular environment. This option is recommended.
05. QTP will remember the settings for the entire record session until the record settings are manually changed by the Automation Engineer.
06.Click on "OK" button and observe that the disclaimer is updated as "Recording" in right bottom of the QTP tool bar.
07. Then launch the application to which the script to be recorded.Perform some action on the application and observe that the script is recorded in the form of VBScript in Expert View and in the form of Object Tables in Keyword view.
08.Once the action is performed on the Application just press on "Stop" or "F4" button and observe that the script recording is stopped.
09.Then Save the script.
10.Playback and check the script to make sure that the script is rerunning without any issue.





Insert Call To Existing Action in QTP

This article explains the details about the call to existing action in QTP. We can insert call to the existing/ reusable action stored in the current test or stored in external test. The action will be copied to the current test in read only format. We can view the steps of the action in action view, but we can't modify them.

The called action's object repository is also read only.If the called action has data in the Data Table,we can select whether we want the data from the action's data sheet to be imported as local,editable or read only from the original action.But the columns and data from the called action's global date sheet is always imported into the calling test as a local, editable copy.

Assume that we need to modify the called external action. TO to this, we need to open the original action from the test in which it resides and make the necessary changes. This modifications will be reflected in all the tests which are call that action. If we use the original action's data when you call an external action,then the changes made to the original action's data are applied as well.

Note: We can view the location of the original action in the General tab of the action properties dialog box.

Steps to be followed to insert a call to an existing action:

01.Navigate to Insert> Call To Existing Action from Expert/Keyword view or right click at any step> Action> Insert Call To Existing.
02.Observe that a window is opened with a combo boxes named as From and Action.
03.From combo box represents the list of tests which contains the resalable action.
04.We can select some other actions by using the browse button which is located just adjacent to From combo box.
05.Action combo box displays all reusable actions in the test we selected.
06.Assume that we selected any one of the action.When we select the action, its type(Reusable Action) and description,if one exists, are displayed.It'll be helpful for us to identify the action you want to call.

Note:External actions that the test calls are also displayed in the list.If the action we want to call is already called from within the selected test,we can select it from the list of actions.This creates another call to the original action.

07.Next step is to decide the insertion place. We can insert either at the end of the test or after the current step.

08.Click on OK button and observe that the action is inserted into the test flow. We can move our action call to another location in our test by dragging it to the desired location.

Note:We can create an additional call to any reusable or external action in our test by pressing Ctrl while you drag and drop the action to another location at a parallel (sibling) level within your test scripts.

Call To Copy Of Action in QTP

 
This article explains about the call to copy of action and the steps to be followed.
 
We need to remember the following points when using "Call To Copy Of Action" in QTP.

01.When we insert call to copy of an action in a test, the original action is completely copied to the current test.

02.Complete action represents the various checkpoint, parameters, copied actions data table and any defined parameters.

03.If the copied action has objects in Local Object repository, the copied action's local object repository is also copied with the action.

04.The copied action is inserted to the current test as an independent.

05.The copied action will be non reusable even though the original action was reusable.

06.Once the action is copied to the current test, we can perform the operations like add, modify and delete.

07.Changes made to the copied action will not have any impact on the original actions and also the changes made to the actual action will not have any impact on the copied action.

Steps to create a copy of an action:

We need to follow certain steps to copy the action to current test.

01.Make sure that the selected Test is opened.[Ex: Test1].
02.We can navigate to the insert call to copy option by using any one of the following step.

    Method#01: Navigate to Insert> Call To Copy of Action.
    Method#02: Navigate to Keyword view> Selection the Action>Right Click> Insert Call to copy of action.
    Method#03: Navigate to Keyword view> Selection the Action>Right Click> Action> Insert Call to copy of action.

03.A window will be opened once the option "Insert Call To Copy Of Action" is selected.The opened window will have 2 combo boxes. One is named as "From" and another one is named as "Action".

04.The From combo box will have the list of Tests available. We can select a particular Test which contains the action to be copied or we can select a particular test by clicking on the browse button which is located just adjacent to the combo box.

Note: Assume that the browse button is clicked and the Test which contains the Action to be copied is selected. Now the system will ask for the path. We can choose either absolute and relative path.

06.Once the test is selected, we need to select the action to be copied.To do this, we need to click on the Action combo box which is located just below the From combo box.

07.Once the action is selected,the type of copied action[Usable/Non-Reusable] action will also be displayed and also we can find a text box "Exit New Action Properties". We have to select this option if we want to make some changes the copied action.

 Note:Assume that we didn't select "Edit New Action Properties" check box when selecting the action. We can do this later by navigating to Keyword View> Right Click> Action> Action Properties tab.

08.We can also find two more options named as "At The End Of the test" and "After the Current" step. We can select any one of these two options.

09.Once everything is finalized click OK and observe that the action is inserted into the test as a call to independent, non-reusable action.

10.We can move our action call to another location by dragging it to the desired location.

Different Ways To Get And Count Objects In QTP

Getting and counting the number of objects on a web page is important factor as part of Automation testing. This article explains the different ways available to get and count the objects.

Descriptive Programming:
This approach uses Description Object, which contains a mask for objects we would to get.
 
Code Snippet:
 Set oDesc = Description.Create
 oDesc("micClass").Value="Link"
 Set Links = Browser("aaa").Page("bbb").Page("ccc").ChildObjects(oDesc)
 MsgBox "Total Links" &Links.count

The method ChildObjects returns the collection of child objects matched the description ("micclass" is "Link") and containted within the object Page("ccc").

Object QTP property Collections:
As we know that QTP can work with Document Object Model(DOM).
 
Code Snippet:
 Set Links = Browser("aaa").Page("bbb").Page("ccc").Objects.Links
 MsgBox "Links Count" & Links.Length
 We used Object property of a page object which represents the HTML Document in a given browser. The HTML document contains different collections like forms, frames, images, linls. etc. We used Length property to get the number of items in the collection.

Object QTP Property & GetElementByTagName:
We can get access to the HTML Document by using Object property of the page and use its GetElementByTagName method to get the number of links on the page.
 
Code Snippet:
Set Links = Browser("aaa").Page("bbb").Object.GetElementByTagName("a")
MsgBox "Total Links" & Links.Length
 
We can use the above methods for finding the images,webedits, list of objects on a web page.

Capturing Tool Tip Of A Link In QTP

As we know that the Tool tip or infotip or a hint is a common graphical user interface element. It's used in conjunction with a cursor,usually a pointer.The user hovers the pointer over an item without clicking it, and a tooltip may appear - a small "hover box" with information about the item being hovered over.

Capturing Toop Tip(TT) in QTP is not a difficult task. We need to follow some steps to achieve this.

01. Place the mouse cursor over the link
02. Wait for tool tip
03. Get Text of the shown tool tip

Use the following code snippet to capture the text of a tool tip.

'Place the mouse cursor over the link
Browser("aaa").Page("bbb").WebElement("text:=Link Name").FireEven "onmouseover"
Wait 3
'Grab the tool tip
TT=Window("nativeclass:=tooltips_class32").GetRoProperty("text")

Please read the following steps which explains the details about the above code snippet.

01.We use FireEvent("onmouseover") to simulate mouse placing over the link.
02.Function Wait waits for 3 seconds for a tool tip.
03.To get tool tip we used the "("nativeclass:=tooltips_class32").GetROProperty("text")"

We can compare the captured tool tip with the expected if required. I hope this article is helpful in capturing the Tool tip of any link

VBScript Syntax Rules And Guidelines

Case Sensitive:
VBScript is not case sensitive.It means that it doesn't differentiate between upper case and lower case spelling of words, variables, objects and methods names or constants.

For example, Browser("aaa").Page("bbb").WebList("today").Select "131"
Browser("aaa").Page("bbb").WebList("Today").Select "131"will be treated in same way by QTP.

Text Strings:
When a value is entered as a text string, we should add quotation mark before and after the string.But we need to remember that the numbers also should be surrounded by quoatation marks, beacuse it's a text string that represent a number not a numeric value when the number is entered into a text box.

One more should be considered that the variables should not be surrounded by quotation marks.

For example: Browser("aaa").Page("bbb").WaitProperty("variable name", variable,20000)

Variables:
We can use the variable to store strings,integers,arrays and objects.Using variables is very helpful to make the scripts more readable and flexible.

Parenthesis:
To achieve the desired result and to avoid errors,it's important that we use parenthesis() correctly in our statements.

Indentation:
We can indent or out-dent our script to reflect the logical structure of the nesting of the statements.

Comments:
We can add the comments before writing a line or at the end of the statement.We have to use apostrophe(') to represent the comments.It's recommended to add the comments wherever possible, to make our scripts easier to understand and maintain.

Spaces:
We can add spaces in our script to improve clarity. These spaces are ignored by VBScript.

QTP Driver Script

Actually we are using VBScript in most of the areas in QTP. But the Driver Script is the only QTP script, reated to all are VBscript files(.VBS).



Driver script is mainly useful to organize the Tests Execution and stores Test Logs in the specified file/folder.

Example:

adding sheets to runtime data table
datatable.AddSheet ("Module")
datatable.AddSheet ("Testcase")
datatable.AddSheet ("Teststep")

'Adding data sheets to runtime data table

Tcrowcount=datatable.GetSheet ("Testcase").getrowcount
        For j=1 to Tcrowcount step 1
           datatable.SetCurrentRow (j)
           moduleid1=datatable.Value(4,"Testcase")
           tcexe=datatable.Value(3,"Testcase")
           If moduleid=moduleid1 and Ucase(tcexe)="Y" Then
               TcId=datatable.Value(1,"Testcase")
               Tsrowcount=datatable.GetSheet("Teststep").getrowcount
               For k= 1 to Tsrowcount step 1
               datatable.SetCurrentRow(k)
               Tcid1=Datatable.Value(5,"Teststep")
                   If TcId= TcId1 Then
                       keyword= datatable.Value(3,"Teststep")
                       Select Case keyword
                       Case "ln"
                       res=Login()
                       datatable.Value(6,"Teststep")=res
                       Case "ca"
                           close_app
                       Case "op"
                           res=Openord()
                           datatable.Value(6,"Teststep")=res
                
                        End Select
                    End If
                Next
            End If
        Next
    End If
Next
datatable.ExportSheet "D:\Automation\Testlog\results.xls","Teststep"

Sample Initialization Script:

Initialization Script launches QTP Tool and Calls Driver Script, Driver Script execute Tests and Stores Results.
Finally   Initialization Script Closes QTP tool

Option Explicit
Dim qtApp
set qtApp=createobject("QuickTest.Application")
qtApp.Launch
qtApp.Visible=True
qtApp.Open "D:\Automation\Testscripts\Driver"
qtApp.Test.Run
qtApp.Quit

Input And Output Operations in QTP

Am going to explain some of the input and output functions used in Test Automation script which will be useful in debugging the script as well as giving the input dynamically at run time.

InputBox Function:
This function is used to give the user input at run time.The behavior will be,
01.Displays a prompt will be displayed in a dialog box.
02.Waits for the user input text/click.
03.Returns the content of the text box.

Example:
Dim input
input=InputBox("Enter your name:")
MsgBox("You Entered:" & input)

MsgBox Function:
This function is mainly useful when debugging the script.The behavior will be,
01.Displays a message in dialog box.
02.Waits for the user to click a button
03.Returns a value indicating which button the user clicked.

Example:
Dim output
output =MsgBox("Hello World!",70,"MsgBox Example!")
Output variable contains either 1 or 2 depending on which button is clicked.

Dynamic Handling Of Object Repositories in QTP

This article gives the details about the dynamic handling of Object Repositories.Dynamic Handling of Object Respositories represents the Finding the path of the object repository,Loading the Object Repository and Removing the Object repository during run time.

Dynamic Handling is very helpful to improve the QTP performance.To do this, QTP is providing an object called "RepositoriesCollection".

Loading Object Repository:
Use the following code snippet to load a specific Object Repository.

RepositoriesCollection.Add "Path of the repository file"

Finding Object repository:
Use the following code snippet to find a specific object repository.

RepositoriesCollection.Find("Path of the Object repository")

Removing Object Repositories:
Use the following code snippet to remove the Object Repository during run time.

RepositoriesCollection.Remove(position)

We can remove all the loaded Object Repositories by using the following code snippet.

RepositoriesCollection.RemoveAll

Example:
OrPath="C:\Automation\ObjectRepository\Login.tsr"
RepositoriesCollection.Add(OrPath)
SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set "softwaretestingcommunity"
Dialog("Login").WinEdit("Password:").SetSecure "mercury"
Dialog("Login").WinButton("OK").Click
pos=RepositoriesCollection.Fin(OrPath)
RepositoriesCollection.Remove(pos)
RepositoriesCollection.RemoveAll

Database Connections In QTP

Database connection is a facility in computer service which allows the client software to interact with Database irrespective of the Database location. It means that we can access the database from any of the system.


I am going to give the code snippets which will be useful when writing database connection scripts.


SQL Server Connection Strings:
Standard Security:
"Driver="SQLServer",Server= Your_Server_Name;Database=Your_DB_Name;Uid=Your_User_Name;Pwd=Your_Password;"
Trusted Connection:
"Driver="SQLServer"Server="Your_SQL_Server;Database=Your_Database_Name;Trusted_Connection=Yes;"
SQL OLE DB Strings:
Standard Security:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Data_Base_Name;Uid=Your_user_name;Pwd=Your_Password;'
Trusted Connection:
"Provider=SQLOLEDB;Data Sourcer=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
SQL SqlConnection .NET strings:
Standard Security:
"Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" < br>2. "Server=Your_Server_Name;Database=Your_Database_Name;UserID=Your_Username;Password=Your_Password;Trusted_Connection=False"Trusted connection:
1."Data Source=Your_Server_Name;InitialCatalog=Your_Database_Name;Integrated Security=SSPI;"
2."Server=Your_Server_Name;Database=Your_Database_Name;Trusted_Connection=True;"




MS Access connection strings:
MS Access ODBC connection strings
Standard Security:
"Driver= {MicrosoftAccessDriver(*.mdb)};DBQ=C:\App1\Your_Database_Name.mdb;Uid=Your_Username;Pwd=Your_Password;"
Workgroup:
"Driver={Microsoft Access Driver (*.mdb)}; Dbq=C:\App1\Your_Database_Name.mdb; SystemDB=C:\App1\Your_Database_Name.mdw;"
Exclusive "Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\App1\Your_Database_Name.mdb; Exclusive=1; Uid=Your_Username; Pwd=Your_Password;"
MS Access OLE DB & OleDbConnection (.NET framework) connection strings
Open connection to Access database:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; User Id=admin; Password="
Open connection to Access database using Workgroup (System database):
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; Jet OLEDB:System Database=c:\App1\Your_System_Database_Name.mdw"
Open connection to password protected Access database:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; Jet OLEDB:Database Password=Your_Password"
Open connection to Access database located on a network share:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\Server_Name\Share_Name\Share_Path\Your_Database_Name.mdb"
Open connection to Access database located on a remote server:
"Provider=MS Remote; Remote Server=http://Your-Remote-Server-IP; Remote Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb"


MySQL connection strings
MySQL ODBC connection strings
Open connection to local MySQL database using MySQL ODBC 3.51 Driver
"Provider=MSDASQL; DRIVER={MySQL ODBC 3.51Driver}; SERVER= localhost; DATABASE=Your_MySQL_Database; UID= Your_Username; PASSWORD=Your_Password; OPTION=3"
MySQL OLE DB & OleDbConnection (.NET framework) connection strings
Open connection to MySQL database:
"Provider=MySQLProv;Data Source=Your_MySQL_Database;User Id=Your_Username; Password=Your_Password;"


Oracle connection strings:
Oracle ODBC connection strings:
Open connection to Oracle database using ODBC
"Driver= {Microsoft ODBCforOracle};Server=Your_Oracle_Server.world;Uid=Your_Username;Pwd=Your_Password;"
Oracle OLE DB & OleDbConnection (.NET framework) connection strings
Open connection to Oracle database with standard security:
"Provider=MSDAORA;Data Source= Your_Oracle_Database;UserId=Your_Username;Password=Your_Password;"
 "Provider= OraOLEDB.Oracle;Your_Oracle_Database;UserId=Your_Username;Password=Your_Password;"


Open trusted connection to Oracle database
"Provider= OraOLEDB.Oracle;DataSource=Your_Oracle_Database;OSAuthent=1;"