SlideShare a Scribd company logo
1 of 25
Descriptive Programming
Descriptive Programming
Entering / Providingobjectsinformationdirectly intothe test script is called Descriptive Programming.
In thismethod of script creation, we no needto have Object Repositories.
Advantages:
a) Descriptive Programming based Test scripts are faster in executionthanRepository based Test scripts.
b) Scriptsare portable (we can run these scripts from any machine easily)
c) Maintenanceiseasy (less amount of resources)
d) We can start Test Execution processeven thoughApplicationisnot ready.
Descriptive programmingisbasically 2 types.
1. Static Programming
2. Dynamic Programming
Static Programming
In thisstyle of script generation, we provide objectsinformation directly into the script.
Ex:
Invokeapplication “C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe”
dialog(“text:=Login”).Activate
dialog(“text:=Login”).Winedit(“attachedtext:=Agent Name:”).Set “asdf”
dialog(“text:=Login”).Winedit(“attachedtext:=Password:”).Set “mercury”
dialog(“text:=Login”).Winbutton(“text:=OK”,”width:=60″).Click
Note:
1. Dialog, WinEditand WinButton – Test Objects
2. text, attached text – Property names
3. Login, Agent Name:, Password:, OK – Property valuesor Logical Namesof the Object
4. Activate, Set, Setsecure, Click – Methods
Note2:
If we feel one property informationisnot sufficient for recognizing theobject uniquely, then we can provide more propertie sinformation by
separating with commas.
Note 3:
If we want to get objectsinformation (Test objects, propertiesand values), we can use object spy feature. Thisfeature isavailable inTools
Menu, in local repository and inrepository manager.
——————————————————————-
If we want maintain ‘Objects information’ in centralizedlocationthen we can use Constants.
Steps:
Creating Constants:
Const Login=”text:=Login”, Agent=”attached text:=Agent Name:”
Const Pwd =”attached text:=Password:”, Ok=”text:=OK”
Note: we can declare no of Constantsin a line by separating with Camas(,), if we take other line thenwe have to use Const Statement
again.
Creating a Libraryfile
Place Constantsin Notepad andsave as .vbs file
Associate the Library file to QTP(File->Settings->Resources-> Clickadd (+) icon-> Browse path of the Library file->ClickApply and clickOk
buttons
Otherwise, we can load the library fileduring run-time
Syntax:
ExecuteFile“Path of the Library file(.vbs)”
After that create the Test Script using Constants
Creating the Test Script using Constants:
Invokeapplication“C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe”
Dialog(Login).Activate
Dialog(Login).Winedit(Agent).Set “asdf”
Dialog(Login).Winedit(Pwd”).Set “mercury”
Dialog(Login).Winbutton(Ok).Click
Advantages:
If we maintain ObjectInformationin the centralized location, then we can handlemodificationseasily.
——————————————————————-
Dynamic Programming
In thisstyle of script generation, first we create description objects, provide propertiesinformationand use description o bjectsin the test
script.
Creating Properties Collection Objects
Set oLogin=description.Create
Set oAgent=description.Create
Set oPassword=description.Create
Set oOk=description.Create
Entering Properties Information into Objects
oLogin(“text”).value=”Login”
oLogin(“width”).value=320
oLogin(“height”).value=204
oAgent(“attached text”).value=”AgentName:”
oPassword(“attached text”).value=”Password:”
oOk(“text”).value=”OK”
Generating Tests using Properties collection Objects
Invokeapplication“C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe”
Dialog(oLogin).Activate
Dialog(oLogin).Winedit(oAgent).Set“asdf”
Dialog(oLogin).Winedit(oPassword).Set “mercury”
Dialog(oLogin).Winbutton(oOK).Click
Note1: Create Description objectsand put into onelibrary file, by associating that library file, we can gene ratetests.
Note2: Dynamic programming issome difficult in preparation thanstatic programmingbut maintenance isvery easy.
—————————————————-
In thisstyle of script creation also, we can maintainObjectsinformationin theCentralized locationby puttingcollection objectsin a Library
file.
Descriptive programming
In this post we will discuss:
Introduction to Descriptive Programming.
How to write Descriptive Programming?
When and Where to use Descriptive programming?
Some points to note with Descriptive Programming.
Introduction to Descriptive Programming:
Descriptive programming is used when we want to perform an operation on an object that is not present in the object repositor y.
T here can be various valid reason to do so. We will discuss them later in this article.
How to write Descriptive Programming?
T here are two ways in which descriptive programming can be used
1. By giving the description in form of the string arguments.
2. By creating properties collection object for the description.
1. By giving the description in form of the string arguments.
T his is a more commonly used method for Descriptive P rogramming.
Y ou can describe an object directly in a statement by specifying property:=value pairs describing the object instead of spe cifying an
object’s
name. T he general syntax is:
T estObject("PropertyName1:=PropertyValue1", "..." , "P ropertyNameX:=P ropertyValueX")
T estObject—the test object class could be WebEdit, WebRadioGroup etc….
P ropertyName:=P ropertyValue—the test object property and its value. Each property:=value pair should be separated by commas
and quotation
marks. Note that you can enter a variable name as the property value if you want to find an object based on property values y ou
retrieve during a run session.
C onsider the HTML Code given below:
<--! input type="”textbox”" name="”txt_Name”"-->
<--! input type="”radio”" name="”txt_Name”"-->
Now to refer to the textbox the statement would be as given below
Browser(“Browser”).Page(“Page”).WebEdit(“Name:=txt_Name”,”html tag:=INPUT”).set “T est”
A nd to refer to the radio button the statement would be as given below
Browser(“Browser”).Page(“Page”).WebRadioGroup(“Name:=txt_Name”,”html tag:=INPUT”).set “T est”
If we refer to them as a web element then we will have to distinguish between the 2 using the index property
Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html tag:=INPUT”,”Index:=0”).set “T est” ‘ Refers to the
textbox
Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html tag:=INPUT”,”Index:=1”).set “T est” ‘ Refers to the radio
button
T o determine which property and value pairs to use, you can use the O bject Spy:
1. Go to T ools -> O bject Spy.
2. Select the "Test O bject P roperties" radio button.
3. Spy on the desired object.
4. In the P roperties list, find and write down the properties and values that can be used to identify the object.
2. By creating properties collection object for the description.
P roperties collection also does the same thing as string arguments. T he only difference is t hat it "collects" all the properties of a
particular object in an instance of that object. Now that object can be referenced easily by using the instance, instead of writing
"string arguments" again and again. It is my observation that people find "string arguments" [1] method much easier and intuitive
to work with.
T o use this method you need first to create an empty description
Dim obj_Desc ‘Not necessary to declare
Set obj_Desc = Description.Create
Now we have a blank description in “obj_Desc”. Each description has 3 properties “Name”, “V alue” and “Regular Expression”.
obj_Desc(“html tag”).value= “INPUT”
When you use a property name for the first time the property is added to the collection and when you use it again the propert y is
modified. By default each property that is defined is a regular expression. Suppose if we have the following description
obj_Desc(“html tag”).value= “INPUT”
obj_Desc(“name”).value= “txt.*”
T his would mean an object with html tag as INPUT and name starting with txt. Now act ually that “.*” was considered as regular
expression. So, if you want the property “name” not to be recognized as a regular expression then you need to set the
“regularexpression” property as FALSE
obj_Desc(“html tag”).value= “INPUT”
obj_Desc(“name”).value= “txt.*”
obj_Desc(“name”).regularexpression= “txt.*”
T his is how we create a description. Now below is the way we can use it
Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “T est”
When we say .WebEdit(obj_Desc) we define one more property for our description that was not earlier defined that is it’s a text box
(because QTPs WebEdit boxes map to text boxes in a web page).
If we know that we have more than 1 element with same description on the page then we must define “index” property for the th at
description
C onsider the HTML code given below
<--! input type="”textbox”" name="”txt_Name”"-->
<--! input type="”textbox”" name="”txt_Name”"-->
Now the html code has two objects with same description. So distinguish between these 2 objects we will use the “index” property.
Here is the description for both the object
For 1st textbox:
obj_Desc(“html tag”).value= “INPUT”
obj_Desc(“name”).value= “txt_Name”
obj_Desc(“index”).value= “0”
For 2nd textbox:
obj_Desc(“html tag”).value= “INPUT”
obj_Desc(“name”).value= “txt_Name”
obj_Desc(“index”).value= “1”
C onsider the HTML Code given below:
<--! input type="”textbox”" name="”txt_Name”"-->
<--! input type="”radio”" name="”txt_Name”"-->
We can use the same description for both the objects and still distinguish be tween both of them
obj_Desc(“html tag”).value= “INPUT”
obj_Desc(“name”).value= “txt_Name”
When I want to refer to the textbox then I will use the inside a WebEdit object and to refer to the radio button I will use t he
description object with the WebRadioGroup object.
Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “T est” ‘Refers to the text box
Browser(“Browser”).Page(“Page”).WebRadioGroup(obj_Desc).set “T est” ‘Refers to the radio button
But if we use WebElement object for the description then we must define the “index” property because for a webelement the
current description would return two objects.
Getting C hild O bject:
We can use description object to get all the objects on the page that matches that specific description. Suppose we have to c heck
all the checkboxes present on a web page. So we will first create an object description for a checkboxe and then get all the
checkboxes from the page
Dim obj_C hkDesc
Set obj_C hkDesc=Description.Create
obj_C hkDesc(“html tag”).value = “INPUT”
obj_C hkDesc(“type”).value = “checkbox”
Dim allC heckboxes, singleCheckBox
Set allC heckboxes = Browse(“Browser”).P age(“Page”).C hildObjects(obj_ChkDesc)
For each singleCheckBox in allCheckboxes
singleCheckBox.Set “ON”
Next
T he above code will check all the check boxes present on the page. T o get all the child objects we need to specify an object
description.
If you wish to use string arguments [1], same thing can be accomplished by simple scripting.
C ode for that would be:
i=0
Do While Browse(“Browser”).P age(“Page”).WebCheckBox("html tag:=INPUT",type:=checkbox, "index:="&i).Exist
Browse(“Browser”).Page(“Page”).WebC heckBox("html tag:=INPUT",type:=checkbox, "index:="&i).Set "ON"
i=i+1
Loop
Possible Operation on Description Objects
C onsider the below code for all the solutions
Dim obj_C hkDesc
Set obj_C hkDesc=Description.Create
obj_C hkDesc(“html tag”).value = “INPUT”
obj_C hkDesc(“type”).value = “checkbox”
Q : How to get the no. of description defined in a collection
A : obj_C hkDesc.Count ‘Will return 2 in our case
Q : How to remove a description from the collection
A : obj_C hkDesc.remove “html tag” ‘would delete the html tag property from the collection
Q : How do I check if property exists or not in the collection?
A : T he answer is that it’s not possible. Because whenever we try to access a property which is not defined its automatically added
to the collection. T he only way to determine is to check its value that is use a if statement “if obj_C hkDesc(“html tag”).val ue =
empty then”.
Q : How to browse through all the properties of a properties collection?
A : T wo ways
1st:
For each desc in obj_C hkDesc
Name=desc.Name
V alue=desc.Value
RE = desc.regularexpression
Next
2nd:
For i=0 to obj_C hkDesc.count - 1
Name= obj_C hkDesc(i).Name
V alue= obj_C hkDesc(i).Value
RE = obj_C hkDesc(i).regularexpression
Next
Hierarchy of test description:
When using programmatic descriptions from a specific point within a test object hierarchy, you must continue to use programma tic
descriptions
from that point onward within the same statement. If you specify a test object by its object repository name after other objects in
the hierarchy have
been described using programmatic descriptions, Q uickTest cannot identify the object.
For example, you can use Browser(Desc1).Page(Desc1).Link(desc3), s ince it uses programmatic descriptions throughout the entire
test object hierarchy.
Y ou can also use Browser("Index").Page(Desc1).Link(desc3), since it uses programmatic descriptions from a certain point in th e
description (starting
from the P age object description).
However, you cannot use Browser(Desc1).P age(Desc1).Link("Example1"), since it uses programmatic descriptions for the Browser
and P age objects but
then attempts to use an object repository name for the Link test object (Q uickTest tries to locat e the Link object based on its name,
but cannot
locate it in the repository because the parent objects were specified using programmatic descriptions).
When and Where to use Descriptive programming?
Below are some of the situations when Descriptive P rogramming can be considered useful:
1. O ne place where DP can be of significant importance is when you are creating functions in an external file. Y ou can use th ese
function in various actions directly , eliminating the need of adding object(s) in object re pository for each action[If you are using
per action object repository]
2. T he objects in the application are dynamic in nature and need special handling to identify the object. T he best example wo uld be
of clicking a link which changes according to the us er of the application, Ex. “Logout <>”.
3. When object repository is getting huge due to the no. of objects being added. If the size of O bject repository increases t oo much
then it decreases the performance of Q TP while recognizing a object. [For Q TP8.2 a nd below M ercury recommends that OR size
should not be greater than 1.5M B]
4. When you don’t want to use object repository at all. Well the first question would be why not O bject repository? C onsider the
following scenario which would help understand why not O bject repository
Scenario 1: Suppose we have a web application that has not been developed yet.Now Q TP for recording the script and adding the
objects to repository needs the application to be up, that would mean waiting for the application to be depl oyed before we can start
of with making Q T P scripts. But if we know the descriptions of the objects that will be created then we can still start off with the
script writing for testing
Scenario 2: Suppose an application has 3 navigation buttons on each and every page. Let the buttons be “C ancel”, “Back” and
“Next”. Now recording action on these buttons would add 3 objects per page in the repository. For a 10 page flow this would m ean
30 objects which could have been represented just by using 3 objects. So i nstead of adding these 30 objects to the repository we
can just write 3 descriptions for the object and use it on any page.
5. M odification to a test case is needed but the O bject repository for the same is Read only or in shared mode i.e. changes m ay
affect other scripts as well.
6. When you want to take action on similar type of object i.e. suppose we have 20 textboxes on the page and there names are i n
the form txt_1, txt_2, txt_3 and so on. Now adding all 20 the O bject repository would not be a good programming approach.
QTP – Descriptive Programming (DP) Concepts 1
by Anshoo Arora on August 10, 2009 | QTP/DP, QTP/UFT | 138 COMMENTS
Introduction
Descriptiveprogramming has becomethe techniqueofchoicefor many QTP test developers. Wecan talk aboutits advantages and
disadvantages allday, but here, we’ll only discuss the concepts and comeup with our ownidea ofwhat itdoes better,andwhat it doesn’t :).
This is going tobe a very quick refresher beforewe moveon to its everyday application by completing an end-to-end testcase.
The idea behind descriptive programming is for automationdevelopers toinstruct QTP whichproperties they would liketo use to identify an
object, instead ofhaving QTP to choose themitself. Ifdonecorrectly, this canhelp createrobustness inscripts, ultimately requiring less
maintenance-timeand moredevelopmenttime.
Let’s begin.
But wait, beforewereally begin, wemustunderstand QTP’s Object Spy.It is aninbuilttoolthatenlists all ofthetest-object andruntime-object
properties. These properties aredifferentfor different types for objects.For example, an imagehas a property called ‘file name’whereas a
listbox doesn’t. Instead,a listbox has a special ‘all items’ property whereas theimagedoesn’t. This discussion will belimited to the usagetest-
object properties toidentify objects.Below are2 snapshots oftheObjectSpy:
p>
Object Spy Icon
Object Spy Window
Now, let’s open www.Google.comand usetheobject spy toretrieveall properties ofthesearch box:
Object Spy: WebEdit Properties
Notice theimageabove. Theeditboxhas a HTML TAG property with its corresponding value‘INPUT’. This means,theeditboxtakes someinput
from the user–whichis truebecausewedo setsomevaluein it! Italso has a ‘MAX LENGTH’ property, with a valueof’2048′. This means,you
can enter a maximumof2048 characters in it(the best sourceto seeallofthe Test-Objectproperties ofobjects is the QTP helpitself). Below
you will see an editBoxwhichcan contain a maximumof9 characters:
Test maxLength:
You can reallyuseallthese properties to identify this editbox,but,do wereally need touseallofthem? No. That is the most important idea
behind descriptiveprogramming –we onlyusewhatwe need. Below is howwe write descriptions for objects:
ObjectClassName("property:=value", "property:=value")
' ofcourse we're not limited to only 2 properties. We can write more:
ObjectClassName("property:=value", "property:=value", "property:=value")
Above, ObjectClassName (inWebapplications) can beBrowser,Page,Frame, WebEdit,Imageetc. Properties come fromtheleft column the
ObjectSpy column whereas values arein the right column. Wecan includeas many properties as we want, but inreality, weonly needto add a
few to uniquely identify theobject.Knowing whichproperties shouldsufficeto uniquely identify canobject willcomefrom e xperienceand
practice.Below is a descriptionI created for this editbox(WebEdit):
'ObjectClassName( "property1:=value1", "property2:=value2" )
WebEdit( "name:=q", "html tag:=INPUT" )
I already mentionedtheHTML TAG andits value INPUTabove. We’ve also addeda new property/value here: ‘name:=q’.Is this enoughto
uniquelyidentify theobject? Yes.But is it enoughto makeourscript work? No, sadly its not..andthat is because,we haven’t yet created
descriptions for its parent objects:Browser & Page. Below arethesnapshots ofthe spied browserand pageobjects:
Object Spy: Browser Properties
Object Spy: Page Properties
BROWSER DESCRIPTION
'ObjectClassName( "property1:=value1" )
Browser( "title:=Google" )
PAGE DESCRIPTION
Page( "title:=Google" )
Now, we will connect allthese descriptions and form a hierarchical tree:
Browser("title:=Google").Page("title:=Google").WebEdit("name:=q","html tag:=INPUT")
You might wonder whyI have omitted the WebTablebelowthePage andabovetheWebEdit object. In practice, wecan alsoskip thePage
object to identify theWebEdit. But, why didI skip the WebTableafter all!? When youexperiment morewith DP,you willdiscover that s ome
objects areembeddedin many WebTables, andit willbecomecumbersome ifwewere toincludeall WebTables in the hierarchy to get tothe
object of interest (thanks to the personwhothoughtthat willbea terrible idea!). Exampleofthepreviously mentionedscenario:
Object Spy: Multiple WebTables
To completethestatementabove, wewill addanevent. In QTP, events can bedescribed as actions on targetobjects. Forexample,a WebEdit
has a ‘Set’ event. weuse the‘Set’ method ofa WebEditto seta value:
Browser("title:=Google").Page("title:=Google").WebEdit("name:=q","html tag:=INPUT").Set "DP"
Set is a QTP event to put ina value in theeditbox.Different objects have differentevents. For example: anImagehas a ‘Click’ event associated
with it.
This, we did without using ObjectRepository. The sameconceptapplies to all objects regardless ofwhat your environment is. We perform
actions on child objects byaccessing their objecthierarchies.Let’s completetheaboveexampleby searching for our keywords (use thespy
again on thesearch button):
Browser("title:=Google").Page("title:=Google").WebEdit("name:=q", "html tag:=INPUT").Set "DP"
Browser("title:=Google").Page("title:=Google").WebButton("name:=Google Search").Click
This is how the samecode willlook likeifwe had recorded this process:
Browser("Google").Page("Google").WebEdit("q").Set "DP is great"
Browser("Google").Page("Google").WebButton("Google Search").Click
These properties are now storedin QTP’s Object Repository (OR). Thereis another way wecancreateobject descriptions, which is doneby
setting a reference:
' Creating Browser description
' "title:=Google"
Set oGoogBrowser = Description.Create
oGoogBrowser( "title" ).value = "Google"
' Creating Page description
' "title:=Google"
Set oGoogPage = Description.Create
oGoogPage( "title" ).Value = "Google"
'* Creating WebEdit description
' "html tag:=INPUt", "name:=q"
Set oGoogWebEdit = Description.Create
oGoogWebEdit( "html tag" ).Value = "INPUT"
oGoogWebEdit( "name" ).Value = "q"
Once we do theabove, wecan usethis descriptions inour script:
Browser(oGoogBrowser).Page(oGoogPage).WebEdit(oGoogWebEdit).Set "DP is great"
The only timeI usethis techniqueis to retriveobject collections through ChildObjects (wewill discuss this inthecoming tutorials).
Let’s do another example. Again,we will use Google,but instead ofsetting a value,we will click anobject. Youcan chooseany Link on the page;
I chose thelink ‘Images’:
Object Spy: Google Images Link
'ClassName("property:=value").ClassName("propert1:=value").ClassName("property:=value").Event
Browser("title:=Google").Page("title:=Google").Link("innertext:=Images", "html tag:=A").Click
This time,instead of‘Set’we used ‘Click’.Following is a listof events weperformon Web objects:
O B JE CT E VE NT
Image Click
WebButton Click
WebCheckBox Set
WebEdit Set
WebElement Click
WebList Select
WebRadioGroup Select
QTP – Descriptive Programming (DP) Concepts 2 (Regular Expressions)
by Anshoo Arora on August 10, 2009 | QTP/DP, QTP/UFT | 74 COMMENTS
A wildcard charactercan beusedto substitutefor any othercharacter or characters in a string.1 This means, wecan use a wildcard tomakeour
descriptions moregeneric.For example, iftheproperty ‘filename’ ofanImageis ‘getAllAttributes.JPG’, wecan usea wildcardseveral ways:
' Only using the first 2 words: getAll
Browser( "title:=MyTitle" ).Page( "title:=MyTitle" ).Image( "file name:=getAll.*" ).Click
' Using 1 word (Attributes) with the extension (JPG)
Browser( "title:=MyTitle" ).Page( "title:=MyTitle" ).Image( "file name:=.*Attributes.*JPG" ).Click
Let’s putthis technique intopractice.Let’s use Mercury Tours for this test.Let’s tryto identify thebanner image (banner2.gif) having the
following text embed: ‘onecoolsummer ARUBA’.
This image is the property of http://newtours.demoaut.com (HP/Mercury)
Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours")_
.Image("file name:=banner2.gif").Highlight
Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file
name:=banner2.*").Highlight
Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file
name:=banner.*").Highlight
Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file
name:=ban.*gif").Highlight
Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file name:=ban.*f").Highlight
Ofcourse, therearemoreways to identify thebanner image, butI’veonly usedtheabove5. Similarly,we canusethis wildcard characterfor the
Browser and Pageobjects:
' Without wildcard(s): 0.20 seconds
Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file
name:=banner2.gif").Click
' With wildcard(s): 0.30 seconds
Browser("title:=Welcome.*").Page("title:=.*Mercury Tours").Image("file name:=banner2.gif").Highlight
' 0.28 seconds
Browser("title:=Welcome:.*").Page("title:=Welcome.*").Image("file name:=banner2.*").Highlight
' 0.56 seconds
Browser("title:=.*Mercury Tours").Page("title:=.*: Mercury.*").Image("file name:=banner.*").Highlight
' 0.61 seconds
Browser("title:=.*Mercury Tour.*").Page("title:=Welcome:.*").Image("file name:=ban.*gif").Highlight
' 0.51 seconds
Browser("title:=.*: Mercury.*").Page("title:=.*Mercury Tour.*").Image("file name:=ban.*f").Highlight
You might notice a littledropin performancefor someofthe above statements. This is quiteobvious though. Using a realworldexample:
Scenario 1
If you were askedto deliver a letter toJohnand youhad thefollowing pieceof informationprovided:Building 184, Floor 5,Room120, Desk 9.
You would know thatyou firsthave to findBuilding A, then takean elevatorto the5th floor, find Room 120,and onceyou’re inside room 120,
John sits on Desk #9. This is quitestraight-forward andofcourse you’ll beableto quickly find John.
Scenario 2
In anotherscenario, ifyouwereaskedto deliver a letter toJohnwhois in Building 184and onthe5thfloor, howwould you findJohn? You
would haveto go toeachroomand ask for John, and makesureit is the correct John before delivering theletterto him. This might takelonger.
This is roughly whathappens in ourscripts. As our descriptions getmoreand moregeneric,thetimeit takes to identify the object increases.
Therefore, eventhough wildcardcharacters can simplify our work, weshould bea littlecarefulhow weusethem.
Regular-Expressions.Info is a good sourceto learnregular-expressions.We willnowdo the exactsametest wedidaboutwith Banner2.gif, but
this timeusing somemoreregexstylecharacters.
' Using the first few characters of the title and the first few characters of the image
Browser("title:=Welcw+D+w+").Page("title:=Welcw+D+w+").Image("file name:=banw+d+.w+").Highlight
' Using the last few characters of the title with first and last characters of the image
Browser("title:=w+D+w+ours").Page("title:=w+D+w+ours").Image("file name:=bw+2.gif").Highlight
' Same as above for Browser and Page, but '...' for image
Browser("title:=w+D+w+ours").Page("title:=w+D+w+ours").Image("file name:=bw+2....").Highlight
' Same as above, but replaced 'b' with a '.'
Browser("title:=w+D+w+ours").Page("title:=w+D+w+ours").Image("file name:=.w+2....").Highlight
In the proceeding articlewewill cover OrdinalIdentifiers and also see how to create a simpletestmodule for a login process.
QTP – Descriptive Programming (DP) Concepts 3 (Ordinal Identifiers)
by Anshoo Arora on August 10, 2009 | QTP/DP, QTP/UFT | 75 COMMENTS
This is thethird articlein the Descriptive Programming series, and willoutlinetheconcepts ofOrdinalIdentifiers used in QTP. We will also
create a simpletest module (step by step) for a loginprocess using only Descriptive Programming (DP).
Ordinal Identifiers – What are they?
Let me quote QTP Reference here:
An ordinal identifier assigns a numericalvalueto a testobject that indicates its orderor locationrelative to otherobjects with an otherwise
identicaldescription(objects thathave the samevalues for allproperties). This ordered value provides a backup mechanism thatenables
QuickTest tocreatea unique description torecognizean objectwhen the definedproperties arenotsufficient to doso.
Let’s break theabovedefinitionfrom Mercury/HPinto severalparts to clarify theconcept.
An ordinal identifier assigns a numericalvalueto a testobject
From the quoteabove,we canconcludethatanordinalidentifier is a numerical entity.In otherwords, its simply a numberthat is assigned toa
test object.
that indicates its order or locationrelativeto otherobjects with an otherwise identicaldescription(objects thathave the samevalues for all
properties)
This means,anOrdinal Identifier works quite differentlyin relation to the properties welearned inthe 1st partofthis series. This identifier, or a
property if you will, works according tothe order or location oftestobjects. Objects’ order and locationare uniquecharacteristics. For example,
in a coordinatesystem, generally only a singleobject exists on a given ‘x,y’ coordinate. Thus, an ordinal identifier willa lways beunique. Index
defines the order, andlocation defines location.
This ordered valueprovides a backupmechanism that enables QuickTestto create a uniquedescription to recognize an objectwhen the
defined properties arenotsufficient to doso.
The quote aboveis a good way to concludethis concept ofOrdinalIdentifiers inQTP. Since it is always uniquefor an object, itcan become
extremely usefulincluding these withobjects’ mandatory and assisstiveproperties to prevent falling intoobject recognition problems. The3
types of ordinal identifiers are: Location, Index and CreationTime (browser only).
Location Ordinal Identifier
Let’s use an exampleto understandhowtheLocation Identifier works.Consider the 4 WebEdits below:
Text Box 1: Text Box 2:
Text Box 3: Text Box 4:
All the edits abovehave exactlythesameproperties. This propertyworks vertically, from top tobottom, and left to right. Thus, ‘TextBox 1‘will
have a location valueof0, ‘Text Box3‘ willhave 1, ‘Text Box2‘ willhave2, and ‘TextBox 4‘will have3. Notethat VBScript is zero based, sothe
location propertywould startat0. This canbe verified by running thefollowing statements:
'Text Box 1
Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest","location:=0").Set "1"
'Text Box 3
Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest","location:=1").Set "2"
'Text Box 2
Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest","location:=2").Set "3"
'Text Box 4
Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest","location:=3").Set "4"
Text Box 1: location=0
Text Box 2: location=2
Text Box 3: location=1
Text Box 4: location=3
Index Ordinal Identifier
Index is quitesimilar to location, but itworks pertaining toappearance ofobjects inthesource code1. An object appearing priorin the source
code willhave a smallerIndex valueas comparedto another object that comes later in thesource. Thus,for thesame group ofeditboxes
above: ‘TextBox 1′ will haveanindexof0, ‘Text Box2′ willhave 1,‘Text Box3′ will have 2 and‘TextBox 4′ will have3. Let’s testour statements:
1 Credits go to Harishfor finding this error.
'Text Box 1
Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest", "index:=0").Set "1"
'Text Box 2
Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest", "index:=1").Set "2"
'Text Box 3
Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest", "index:=2").Set "3"
'Text Box 4
Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest", "index:=3").Set "4"
Text Box 1: index=0
Text Box 2: index=1
Text Box 3: index=2
Text Box 4: index=3
That was quite easy,wasn’tit? Now, let’s moveon to CreationTime,whichis an ordinal identifier strictlyreserved for the browser object.
CreationTime Ordinal Identifier
Again, let’s usethedescription given by HP/Mercury in QTP’s helpfile:
Ifthere areseveral openbrowsers,theonewith the lowest CreationTimeis thefirstonethat was opened andtheonewith the highest
CreationTime is the lastonethatwas opened.
That means,thefirst browser youopen willhave a creationtimeof0. The second browser will havea creationtime of1.The thirdbrowserwill
have a creationtime of2 andso on.
SystemUtil.Run "iexplore.exe", "http://www.HP.com" 'CreationTime 0
SystemUtil.Run "iexplore.exe", "http://www.AdvancedQTP.com" 'CreationTime 1
SystemUtil.Run "iexplore.exe", "http://www.LinkedIn.com" 'CreationTime 2
Browser( "creationtime:=" ).Highlight 'Highlight HP.com
Browser( "creationtime:=1" ).Highlight 'Highlight AdvancedQTP.com
Browser( "creationtime:=2" ).Highlight 'Highlight LinkedIn.com
When you run the above codein QTP, you willfind that thefirst browser QTP highlights on is HP.com, the second is AdvancedQTP.comand the
third is LinkedIn.com. Eventhis is quite simple,isn’tit?
As promised,we mustcreatea simplelogin process using the concepts wehave learnedsofar inthenext article.
QTP – Descriptive Programming (DP) 4 (Creating a Test Script)
by Anshoo Arora on August 10, 2009 | QTP/DP, QTP/UFT | 117 COMMENTS
This is thelastarticle in ourDescriptiveProgramming series and willcover a simplelogin process using 100% DP. I havepurposely createdthe
exampleto bevery high-level tomake sure its quit easy tounderstand.However, ifyou feel more examples on this conceptwillhelp, I’llbe
more thanhappy tocreatea PartV ofthis series withonly real-world examples ofDP inaction.
We will use the HP/Mercury Demo Website for this example.
Following is the process I amgoing tofollow tocomplete this process. In your applicationhowever, you can usetheprocess that best suits your
needs, but for the purposes ofthis lesson, I willkeep itquitebasic:
1. Launch Browser.
2. Check whether thecorrectbrowser opened.
3. Ensure the userName,passwordedits and theSign-Inbuttonexist.
4. Set the userName andpassword andClick Sign-In.
5. Make sure the browser navigated tothecorrect page.
Step 1: Launch Browser
'We will use SystemUtil.Run to launch our target browser
SystemUtil.Run "iexplore.exe", "http://newtours.demoaut.com/"
Step 2: Checking if the correct browser opened
The 2 new concepts in this step are:
1. Reporter Object: This objectis used tosendindividual reports to the test results. Inother words,when thetest ends, youcan seethe
reportedevents inyourTest results.
2. ExitTest: Autility statement availabletoQTP that enables itto completeexit a Test. Inother words,when this statementexecutes, the
test execution ends.
If Browser( "title:=Welcome: Mercury Tours" ).Exist( 15 ) Then
Reporter.ReportEvent micPass, "Step 1- Launch", "Correct browser was launched."
Else
Reporter.ReportEvent micFail, "Step 1- Launch", "Browser failed to launch."
ExitTest
End If
Step 3: Ensure the userName, password edits and the Sign-In button exist.
'Notice the use of the wildcard character below
If Browser("title:=Welcome:.*").Page("title:=Welcome.*").WebEdit("name:=userName").Exist(0) Then
'set username
If Browser("title:=Welcome:.*").Page("title:=Welcome.*").WebEdit("name:=password").Exist(0) Then
'set password
If Browser("title:=Welcome:.*").Page("title:=Welcome.*").Image("name:=login" ).Exist(0) Then
'click button
Else
'report that Sign-In button was not found
End If
Else
'report that the password edit was not found
End If
Else
'report that the userName edit was not found
End If
Step 4: Set the userName and password and Click Sign-In.
The following willcompletethesnippet above:
'Notice the use of the wildcard character below
With Browser("title:=Welcome:.*").Page("title:=Welcome.*")
If .WebEdit("name:=userName").Exist(0) Then
.WebEdit("name:=userName").Set "test"
If .WebEdit("name:=password").Exist(0) Then
.WebEdit("name:=password").Set "test"
If .Image("name:=login" ).Exist(0) Then
.Image("name:=login" ).Click
Else
Reporter.ReportEvent micFail, "Sign-In Button Error", "Button not found."
End If
Else
Reporter.ReportEvent micFail, "Password Edit Error", "EditBox not found."
End If
Else
Reporter.ReportEvent micFail, "UserName Edit Error", "EditBox not found."
End If
End With
Step 5: Make sure the browser navigated to the correct page
'Synchronize with a browser
Browser( "title:=.*" ).Sync
'Wait 1 second for browser with "Find a Flight" title to exist
If Browser( "title:=Find a Flight.*" ).Exist( 1 ) Then
Reporter.ReportEvent micPass, "Login", "Login successful"
Else
Reporter.ReportEvent micFail, "Login", "Login failed"
End If
PUTTING IT ALL TOGETHER
'We will use SystemUtil.Run to launch our target browser
SystemUtil.Run "iexplore.exe", "http://newtours.demoaut.com/"
If Browser( "title:=Welcome: Mercury Tours" ).Exist( 15 ) Then
Reporter.ReportEvent micPass, "Step 1- Launch", "Correct browser was launched."
Else
Reporter.ReportEvent micFail, "Step 1- Launch", "Browser failed to launch."
ExitTest
End If
'Notice the use of the wildcard character below
With Browser("title:=Welcome:.*").Page("title:=Welcome.*")
If .WebEdit("name:=userName").Exist(0) Then
.WebEdit("name:=userName").Set "test"
If .WebEdit("name:=password").Exist(0) Then
.WebEdit("name:=password").Set "test"
If .Image("name:=login").Exist(0) Then
.Image("name:=login").Click
Else
Reporter.ReportEvent micFail, "Sign-In Button Error", "Button not found."
End If
Else
Reporter.ReportEvent micFail, "Password Edit Error", "EditBox not found."
End If
Else
Reporter.ReportEvent micFail, "UserName Edit Error", "EditBox not found."
End If
End With
Browser( "title:=.*Mercury.*" ).Sync
If Browser( "title:=Find a Flight.*" ).Exist( 1 ) Then
Reporter.ReportEvent micPass, "Login", "Login successful"
Else
Reporter.ReportEvent micFail, "Login", "Login failed"
End If
If you have any doubtin thecontent above,please feelfreeto posta comment about it. I hope this articlehelps understandfurther the
principles of DescriptiveProgramming and using it inyoureverydaywork.

More Related Content

What's hot

Codegeneration With Xtend
Codegeneration With XtendCodegeneration With Xtend
Codegeneration With XtendSven Efftinge
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserHoward Lewis Ship
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84Mahmoud Samir Fayed
 
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Eelco Visser
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with XtextHolger Schill
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)lennartkats
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkitwlscaudill
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptMichael Girouard
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBOren Eini
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Juriy Zaytsev
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan Dolgushin
 

What's hot (20)

Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Codegeneration With Xtend
Codegeneration With XtendCodegeneration With Xtend
Codegeneration With Xtend
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
 
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
 
Spring data
Spring dataSpring data
Spring data
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with Xtext
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 
Dlr
DlrDlr
Dlr
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDB
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
 

Similar to descriptive programming

JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript WorkshopPamela Fox
 
Qtp training session IV
Qtp training session IVQtp training session IV
Qtp training session IVAisha Mazhar
 
Sphinx autodoc - automated api documentation - PyCon.KR 2015
Sphinx autodoc - automated api documentation - PyCon.KR 2015Sphinx autodoc - automated api documentation - PyCon.KR 2015
Sphinx autodoc - automated api documentation - PyCon.KR 2015Takayuki Shimizukawa
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second LanguageRob Dunn
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Takayuki Shimizukawa
 
Analyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics CompanyAnalyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics CompanyPVS-Studio
 
Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015Takayuki Shimizukawa
 
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)Takayuki Shimizukawa
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Basics of dictionary object
Basics of dictionary objectBasics of dictionary object
Basics of dictionary objectNilanjan Saha
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
Elasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibElasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibJen Aman
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive ShellGiovanni Lodi
 
Declarative Data Modeling in Python
Declarative Data Modeling in PythonDeclarative Data Modeling in Python
Declarative Data Modeling in PythonJoshua Forman
 

Similar to descriptive programming (20)

JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Qtp training session IV
Qtp training session IVQtp training session IV
Qtp training session IV
 
Sphinx autodoc - automated api documentation - PyCon.KR 2015
Sphinx autodoc - automated api documentation - PyCon.KR 2015Sphinx autodoc - automated api documentation - PyCon.KR 2015
Sphinx autodoc - automated api documentation - PyCon.KR 2015
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
 
QTP
QTPQTP
QTP
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
 
Analyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics CompanyAnalyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics Company
 
Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015
 
Objective c
Objective cObjective c
Objective c
 
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Basics of dictionary object
Basics of dictionary objectBasics of dictionary object
Basics of dictionary object
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
Angular Schematics
Angular SchematicsAngular Schematics
Angular Schematics
 
Elasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibElasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlib
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive Shell
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
Declarative Data Modeling in Python
Declarative Data Modeling in PythonDeclarative Data Modeling in Python
Declarative Data Modeling in Python
 

More from Anand Dhana

More from Anand Dhana (6)

bluetooth-security
bluetooth-securitybluetooth-security
bluetooth-security
 
bluetooth
bluetooth bluetooth
bluetooth
 
vbscripting
vbscriptingvbscripting
vbscripting
 
vb script
vb scriptvb script
vb script
 
loadrunner
loadrunnerloadrunner
loadrunner
 
vbscript-reference book
vbscript-reference bookvbscript-reference book
vbscript-reference book
 

Recently uploaded

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Recently uploaded (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 

descriptive programming

  • 1. Descriptive Programming Descriptive Programming Entering / Providingobjectsinformationdirectly intothe test script is called Descriptive Programming. In thismethod of script creation, we no needto have Object Repositories. Advantages: a) Descriptive Programming based Test scripts are faster in executionthanRepository based Test scripts. b) Scriptsare portable (we can run these scripts from any machine easily) c) Maintenanceiseasy (less amount of resources) d) We can start Test Execution processeven thoughApplicationisnot ready. Descriptive programmingisbasically 2 types. 1. Static Programming 2. Dynamic Programming Static Programming In thisstyle of script generation, we provide objectsinformation directly into the script. Ex: Invokeapplication “C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe” dialog(“text:=Login”).Activate dialog(“text:=Login”).Winedit(“attachedtext:=Agent Name:”).Set “asdf” dialog(“text:=Login”).Winedit(“attachedtext:=Password:”).Set “mercury” dialog(“text:=Login”).Winbutton(“text:=OK”,”width:=60″).Click Note: 1. Dialog, WinEditand WinButton – Test Objects 2. text, attached text – Property names 3. Login, Agent Name:, Password:, OK – Property valuesor Logical Namesof the Object 4. Activate, Set, Setsecure, Click – Methods Note2: If we feel one property informationisnot sufficient for recognizing theobject uniquely, then we can provide more propertie sinformation by separating with commas. Note 3: If we want to get objectsinformation (Test objects, propertiesand values), we can use object spy feature. Thisfeature isavailable inTools Menu, in local repository and inrepository manager. ——————————————————————- If we want maintain ‘Objects information’ in centralizedlocationthen we can use Constants. Steps: Creating Constants: Const Login=”text:=Login”, Agent=”attached text:=Agent Name:” Const Pwd =”attached text:=Password:”, Ok=”text:=OK” Note: we can declare no of Constantsin a line by separating with Camas(,), if we take other line thenwe have to use Const Statement again. Creating a Libraryfile Place Constantsin Notepad andsave as .vbs file Associate the Library file to QTP(File->Settings->Resources-> Clickadd (+) icon-> Browse path of the Library file->ClickApply and clickOk buttons Otherwise, we can load the library fileduring run-time Syntax: ExecuteFile“Path of the Library file(.vbs)” After that create the Test Script using Constants Creating the Test Script using Constants: Invokeapplication“C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe” Dialog(Login).Activate Dialog(Login).Winedit(Agent).Set “asdf” Dialog(Login).Winedit(Pwd”).Set “mercury” Dialog(Login).Winbutton(Ok).Click Advantages: If we maintain ObjectInformationin the centralized location, then we can handlemodificationseasily. ——————————————————————- Dynamic Programming In thisstyle of script generation, first we create description objects, provide propertiesinformationand use description o bjectsin the test script. Creating Properties Collection Objects Set oLogin=description.Create Set oAgent=description.Create Set oPassword=description.Create Set oOk=description.Create Entering Properties Information into Objects
  • 2. oLogin(“text”).value=”Login” oLogin(“width”).value=320 oLogin(“height”).value=204 oAgent(“attached text”).value=”AgentName:” oPassword(“attached text”).value=”Password:” oOk(“text”).value=”OK” Generating Tests using Properties collection Objects Invokeapplication“C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe” Dialog(oLogin).Activate Dialog(oLogin).Winedit(oAgent).Set“asdf” Dialog(oLogin).Winedit(oPassword).Set “mercury” Dialog(oLogin).Winbutton(oOK).Click Note1: Create Description objectsand put into onelibrary file, by associating that library file, we can gene ratetests. Note2: Dynamic programming issome difficult in preparation thanstatic programmingbut maintenance isvery easy. —————————————————- In thisstyle of script creation also, we can maintainObjectsinformationin theCentralized locationby puttingcollection objectsin a Library file. Descriptive programming In this post we will discuss: Introduction to Descriptive Programming. How to write Descriptive Programming? When and Where to use Descriptive programming? Some points to note with Descriptive Programming. Introduction to Descriptive Programming: Descriptive programming is used when we want to perform an operation on an object that is not present in the object repositor y. T here can be various valid reason to do so. We will discuss them later in this article. How to write Descriptive Programming? T here are two ways in which descriptive programming can be used 1. By giving the description in form of the string arguments. 2. By creating properties collection object for the description. 1. By giving the description in form of the string arguments. T his is a more commonly used method for Descriptive P rogramming. Y ou can describe an object directly in a statement by specifying property:=value pairs describing the object instead of spe cifying an object’s name. T he general syntax is: T estObject("PropertyName1:=PropertyValue1", "..." , "P ropertyNameX:=P ropertyValueX") T estObject—the test object class could be WebEdit, WebRadioGroup etc…. P ropertyName:=P ropertyValue—the test object property and its value. Each property:=value pair should be separated by commas and quotation marks. Note that you can enter a variable name as the property value if you want to find an object based on property values y ou retrieve during a run session. C onsider the HTML Code given below: <--! input type="”textbox”" name="”txt_Name”"--> <--! input type="”radio”" name="”txt_Name”"--> Now to refer to the textbox the statement would be as given below
  • 3. Browser(“Browser”).Page(“Page”).WebEdit(“Name:=txt_Name”,”html tag:=INPUT”).set “T est” A nd to refer to the radio button the statement would be as given below Browser(“Browser”).Page(“Page”).WebRadioGroup(“Name:=txt_Name”,”html tag:=INPUT”).set “T est” If we refer to them as a web element then we will have to distinguish between the 2 using the index property Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html tag:=INPUT”,”Index:=0”).set “T est” ‘ Refers to the textbox Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html tag:=INPUT”,”Index:=1”).set “T est” ‘ Refers to the radio button T o determine which property and value pairs to use, you can use the O bject Spy: 1. Go to T ools -> O bject Spy. 2. Select the "Test O bject P roperties" radio button. 3. Spy on the desired object. 4. In the P roperties list, find and write down the properties and values that can be used to identify the object. 2. By creating properties collection object for the description. P roperties collection also does the same thing as string arguments. T he only difference is t hat it "collects" all the properties of a particular object in an instance of that object. Now that object can be referenced easily by using the instance, instead of writing "string arguments" again and again. It is my observation that people find "string arguments" [1] method much easier and intuitive to work with. T o use this method you need first to create an empty description Dim obj_Desc ‘Not necessary to declare Set obj_Desc = Description.Create Now we have a blank description in “obj_Desc”. Each description has 3 properties “Name”, “V alue” and “Regular Expression”. obj_Desc(“html tag”).value= “INPUT” When you use a property name for the first time the property is added to the collection and when you use it again the propert y is modified. By default each property that is defined is a regular expression. Suppose if we have the following description obj_Desc(“html tag”).value= “INPUT” obj_Desc(“name”).value= “txt.*” T his would mean an object with html tag as INPUT and name starting with txt. Now act ually that “.*” was considered as regular expression. So, if you want the property “name” not to be recognized as a regular expression then you need to set the “regularexpression” property as FALSE obj_Desc(“html tag”).value= “INPUT” obj_Desc(“name”).value= “txt.*” obj_Desc(“name”).regularexpression= “txt.*” T his is how we create a description. Now below is the way we can use it Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “T est” When we say .WebEdit(obj_Desc) we define one more property for our description that was not earlier defined that is it’s a text box (because QTPs WebEdit boxes map to text boxes in a web page). If we know that we have more than 1 element with same description on the page then we must define “index” property for the th at description C onsider the HTML code given below <--! input type="”textbox”" name="”txt_Name”"--> <--! input type="”textbox”" name="”txt_Name”"--> Now the html code has two objects with same description. So distinguish between these 2 objects we will use the “index” property. Here is the description for both the object
  • 4. For 1st textbox: obj_Desc(“html tag”).value= “INPUT” obj_Desc(“name”).value= “txt_Name” obj_Desc(“index”).value= “0” For 2nd textbox: obj_Desc(“html tag”).value= “INPUT” obj_Desc(“name”).value= “txt_Name” obj_Desc(“index”).value= “1” C onsider the HTML Code given below: <--! input type="”textbox”" name="”txt_Name”"--> <--! input type="”radio”" name="”txt_Name”"--> We can use the same description for both the objects and still distinguish be tween both of them obj_Desc(“html tag”).value= “INPUT” obj_Desc(“name”).value= “txt_Name” When I want to refer to the textbox then I will use the inside a WebEdit object and to refer to the radio button I will use t he description object with the WebRadioGroup object. Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “T est” ‘Refers to the text box Browser(“Browser”).Page(“Page”).WebRadioGroup(obj_Desc).set “T est” ‘Refers to the radio button But if we use WebElement object for the description then we must define the “index” property because for a webelement the current description would return two objects. Getting C hild O bject: We can use description object to get all the objects on the page that matches that specific description. Suppose we have to c heck all the checkboxes present on a web page. So we will first create an object description for a checkboxe and then get all the checkboxes from the page Dim obj_C hkDesc Set obj_C hkDesc=Description.Create obj_C hkDesc(“html tag”).value = “INPUT” obj_C hkDesc(“type”).value = “checkbox” Dim allC heckboxes, singleCheckBox Set allC heckboxes = Browse(“Browser”).P age(“Page”).C hildObjects(obj_ChkDesc) For each singleCheckBox in allCheckboxes singleCheckBox.Set “ON” Next T he above code will check all the check boxes present on the page. T o get all the child objects we need to specify an object description. If you wish to use string arguments [1], same thing can be accomplished by simple scripting. C ode for that would be: i=0 Do While Browse(“Browser”).P age(“Page”).WebCheckBox("html tag:=INPUT",type:=checkbox, "index:="&i).Exist Browse(“Browser”).Page(“Page”).WebC heckBox("html tag:=INPUT",type:=checkbox, "index:="&i).Set "ON" i=i+1 Loop Possible Operation on Description Objects C onsider the below code for all the solutions Dim obj_C hkDesc
  • 5. Set obj_C hkDesc=Description.Create obj_C hkDesc(“html tag”).value = “INPUT” obj_C hkDesc(“type”).value = “checkbox” Q : How to get the no. of description defined in a collection A : obj_C hkDesc.Count ‘Will return 2 in our case Q : How to remove a description from the collection A : obj_C hkDesc.remove “html tag” ‘would delete the html tag property from the collection Q : How do I check if property exists or not in the collection? A : T he answer is that it’s not possible. Because whenever we try to access a property which is not defined its automatically added to the collection. T he only way to determine is to check its value that is use a if statement “if obj_C hkDesc(“html tag”).val ue = empty then”. Q : How to browse through all the properties of a properties collection? A : T wo ways 1st: For each desc in obj_C hkDesc Name=desc.Name V alue=desc.Value RE = desc.regularexpression Next 2nd: For i=0 to obj_C hkDesc.count - 1 Name= obj_C hkDesc(i).Name V alue= obj_C hkDesc(i).Value RE = obj_C hkDesc(i).regularexpression Next Hierarchy of test description: When using programmatic descriptions from a specific point within a test object hierarchy, you must continue to use programma tic descriptions from that point onward within the same statement. If you specify a test object by its object repository name after other objects in the hierarchy have been described using programmatic descriptions, Q uickTest cannot identify the object. For example, you can use Browser(Desc1).Page(Desc1).Link(desc3), s ince it uses programmatic descriptions throughout the entire test object hierarchy. Y ou can also use Browser("Index").Page(Desc1).Link(desc3), since it uses programmatic descriptions from a certain point in th e description (starting from the P age object description). However, you cannot use Browser(Desc1).P age(Desc1).Link("Example1"), since it uses programmatic descriptions for the Browser and P age objects but then attempts to use an object repository name for the Link test object (Q uickTest tries to locat e the Link object based on its name, but cannot locate it in the repository because the parent objects were specified using programmatic descriptions). When and Where to use Descriptive programming? Below are some of the situations when Descriptive P rogramming can be considered useful: 1. O ne place where DP can be of significant importance is when you are creating functions in an external file. Y ou can use th ese function in various actions directly , eliminating the need of adding object(s) in object re pository for each action[If you are using per action object repository] 2. T he objects in the application are dynamic in nature and need special handling to identify the object. T he best example wo uld be of clicking a link which changes according to the us er of the application, Ex. “Logout <>”. 3. When object repository is getting huge due to the no. of objects being added. If the size of O bject repository increases t oo much then it decreases the performance of Q TP while recognizing a object. [For Q TP8.2 a nd below M ercury recommends that OR size should not be greater than 1.5M B]
  • 6. 4. When you don’t want to use object repository at all. Well the first question would be why not O bject repository? C onsider the following scenario which would help understand why not O bject repository Scenario 1: Suppose we have a web application that has not been developed yet.Now Q TP for recording the script and adding the objects to repository needs the application to be up, that would mean waiting for the application to be depl oyed before we can start of with making Q T P scripts. But if we know the descriptions of the objects that will be created then we can still start off with the script writing for testing Scenario 2: Suppose an application has 3 navigation buttons on each and every page. Let the buttons be “C ancel”, “Back” and “Next”. Now recording action on these buttons would add 3 objects per page in the repository. For a 10 page flow this would m ean 30 objects which could have been represented just by using 3 objects. So i nstead of adding these 30 objects to the repository we can just write 3 descriptions for the object and use it on any page. 5. M odification to a test case is needed but the O bject repository for the same is Read only or in shared mode i.e. changes m ay affect other scripts as well. 6. When you want to take action on similar type of object i.e. suppose we have 20 textboxes on the page and there names are i n the form txt_1, txt_2, txt_3 and so on. Now adding all 20 the O bject repository would not be a good programming approach. QTP – Descriptive Programming (DP) Concepts 1 by Anshoo Arora on August 10, 2009 | QTP/DP, QTP/UFT | 138 COMMENTS Introduction Descriptiveprogramming has becomethe techniqueofchoicefor many QTP test developers. Wecan talk aboutits advantages and disadvantages allday, but here, we’ll only discuss the concepts and comeup with our ownidea ofwhat itdoes better,andwhat it doesn’t :). This is going tobe a very quick refresher beforewe moveon to its everyday application by completing an end-to-end testcase. The idea behind descriptive programming is for automationdevelopers toinstruct QTP whichproperties they would liketo use to identify an object, instead ofhaving QTP to choose themitself. Ifdonecorrectly, this canhelp createrobustness inscripts, ultimately requiring less maintenance-timeand moredevelopmenttime. Let’s begin. But wait, beforewereally begin, wemustunderstand QTP’s Object Spy.It is aninbuilttoolthatenlists all ofthetest-object andruntime-object properties. These properties aredifferentfor different types for objects.For example, an imagehas a property called ‘file name’whereas a listbox doesn’t. Instead,a listbox has a special ‘all items’ property whereas theimagedoesn’t. This discussion will belimited to the usagetest- object properties toidentify objects.Below are2 snapshots oftheObjectSpy: p> Object Spy Icon
  • 7. Object Spy Window Now, let’s open www.Google.comand usetheobject spy toretrieveall properties ofthesearch box:
  • 8. Object Spy: WebEdit Properties
  • 9. Notice theimageabove. Theeditboxhas a HTML TAG property with its corresponding value‘INPUT’. This means,theeditboxtakes someinput from the user–whichis truebecausewedo setsomevaluein it! Italso has a ‘MAX LENGTH’ property, with a valueof’2048′. This means,you can enter a maximumof2048 characters in it(the best sourceto seeallofthe Test-Objectproperties ofobjects is the QTP helpitself). Below you will see an editBoxwhichcan contain a maximumof9 characters: Test maxLength: You can reallyuseallthese properties to identify this editbox,but,do wereally need touseallofthem? No. That is the most important idea behind descriptiveprogramming –we onlyusewhatwe need. Below is howwe write descriptions for objects: ObjectClassName("property:=value", "property:=value") ' ofcourse we're not limited to only 2 properties. We can write more: ObjectClassName("property:=value", "property:=value", "property:=value") Above, ObjectClassName (inWebapplications) can beBrowser,Page,Frame, WebEdit,Imageetc. Properties come fromtheleft column the ObjectSpy column whereas values arein the right column. Wecan includeas many properties as we want, but inreality, weonly needto add a few to uniquely identify theobject.Knowing whichproperties shouldsufficeto uniquely identify canobject willcomefrom e xperienceand practice.Below is a descriptionI created for this editbox(WebEdit): 'ObjectClassName( "property1:=value1", "property2:=value2" ) WebEdit( "name:=q", "html tag:=INPUT" ) I already mentionedtheHTML TAG andits value INPUTabove. We’ve also addeda new property/value here: ‘name:=q’.Is this enoughto uniquelyidentify theobject? Yes.But is it enoughto makeourscript work? No, sadly its not..andthat is because,we haven’t yet created descriptions for its parent objects:Browser & Page. Below arethesnapshots ofthe spied browserand pageobjects:
  • 10. Object Spy: Browser Properties
  • 11. Object Spy: Page Properties BROWSER DESCRIPTION 'ObjectClassName( "property1:=value1" ) Browser( "title:=Google" )
  • 12. PAGE DESCRIPTION Page( "title:=Google" ) Now, we will connect allthese descriptions and form a hierarchical tree: Browser("title:=Google").Page("title:=Google").WebEdit("name:=q","html tag:=INPUT") You might wonder whyI have omitted the WebTablebelowthePage andabovetheWebEdit object. In practice, wecan alsoskip thePage object to identify theWebEdit. But, why didI skip the WebTableafter all!? When youexperiment morewith DP,you willdiscover that s ome objects areembeddedin many WebTables, andit willbecomecumbersome ifwewere toincludeall WebTables in the hierarchy to get tothe object of interest (thanks to the personwhothoughtthat willbea terrible idea!). Exampleofthepreviously mentionedscenario:
  • 13. Object Spy: Multiple WebTables To completethestatementabove, wewill addanevent. In QTP, events can bedescribed as actions on targetobjects. Forexample,a WebEdit has a ‘Set’ event. weuse the‘Set’ method ofa WebEditto seta value: Browser("title:=Google").Page("title:=Google").WebEdit("name:=q","html tag:=INPUT").Set "DP" Set is a QTP event to put ina value in theeditbox.Different objects have differentevents. For example: anImagehas a ‘Click’ event associated with it.
  • 14. This, we did without using ObjectRepository. The sameconceptapplies to all objects regardless ofwhat your environment is. We perform actions on child objects byaccessing their objecthierarchies.Let’s completetheaboveexampleby searching for our keywords (use thespy again on thesearch button): Browser("title:=Google").Page("title:=Google").WebEdit("name:=q", "html tag:=INPUT").Set "DP" Browser("title:=Google").Page("title:=Google").WebButton("name:=Google Search").Click This is how the samecode willlook likeifwe had recorded this process: Browser("Google").Page("Google").WebEdit("q").Set "DP is great" Browser("Google").Page("Google").WebButton("Google Search").Click These properties are now storedin QTP’s Object Repository (OR). Thereis another way wecancreateobject descriptions, which is doneby setting a reference: ' Creating Browser description ' "title:=Google" Set oGoogBrowser = Description.Create oGoogBrowser( "title" ).value = "Google" ' Creating Page description ' "title:=Google" Set oGoogPage = Description.Create oGoogPage( "title" ).Value = "Google" '* Creating WebEdit description ' "html tag:=INPUt", "name:=q" Set oGoogWebEdit = Description.Create oGoogWebEdit( "html tag" ).Value = "INPUT" oGoogWebEdit( "name" ).Value = "q" Once we do theabove, wecan usethis descriptions inour script: Browser(oGoogBrowser).Page(oGoogPage).WebEdit(oGoogWebEdit).Set "DP is great" The only timeI usethis techniqueis to retriveobject collections through ChildObjects (wewill discuss this inthecoming tutorials).
  • 15. Let’s do another example. Again,we will use Google,but instead ofsetting a value,we will click anobject. Youcan chooseany Link on the page; I chose thelink ‘Images’: Object Spy: Google Images Link 'ClassName("property:=value").ClassName("propert1:=value").ClassName("property:=value").Event Browser("title:=Google").Page("title:=Google").Link("innertext:=Images", "html tag:=A").Click This time,instead of‘Set’we used ‘Click’.Following is a listof events weperformon Web objects:
  • 16. O B JE CT E VE NT Image Click WebButton Click WebCheckBox Set WebEdit Set WebElement Click WebList Select WebRadioGroup Select QTP – Descriptive Programming (DP) Concepts 2 (Regular Expressions) by Anshoo Arora on August 10, 2009 | QTP/DP, QTP/UFT | 74 COMMENTS A wildcard charactercan beusedto substitutefor any othercharacter or characters in a string.1 This means, wecan use a wildcard tomakeour descriptions moregeneric.For example, iftheproperty ‘filename’ ofanImageis ‘getAllAttributes.JPG’, wecan usea wildcardseveral ways: ' Only using the first 2 words: getAll Browser( "title:=MyTitle" ).Page( "title:=MyTitle" ).Image( "file name:=getAll.*" ).Click ' Using 1 word (Attributes) with the extension (JPG) Browser( "title:=MyTitle" ).Page( "title:=MyTitle" ).Image( "file name:=.*Attributes.*JPG" ).Click Let’s putthis technique intopractice.Let’s use Mercury Tours for this test.Let’s tryto identify thebanner image (banner2.gif) having the following text embed: ‘onecoolsummer ARUBA’. This image is the property of http://newtours.demoaut.com (HP/Mercury) Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours")_ .Image("file name:=banner2.gif").Highlight
  • 17. Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file name:=banner2.*").Highlight Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file name:=banner.*").Highlight Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file name:=ban.*gif").Highlight Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file name:=ban.*f").Highlight Ofcourse, therearemoreways to identify thebanner image, butI’veonly usedtheabove5. Similarly,we canusethis wildcard characterfor the Browser and Pageobjects: ' Without wildcard(s): 0.20 seconds Browser("title:=Welcome: Mercury Tours").Page("title:=Welcome: Mercury Tours").Image("file name:=banner2.gif").Click ' With wildcard(s): 0.30 seconds Browser("title:=Welcome.*").Page("title:=.*Mercury Tours").Image("file name:=banner2.gif").Highlight ' 0.28 seconds Browser("title:=Welcome:.*").Page("title:=Welcome.*").Image("file name:=banner2.*").Highlight ' 0.56 seconds Browser("title:=.*Mercury Tours").Page("title:=.*: Mercury.*").Image("file name:=banner.*").Highlight ' 0.61 seconds Browser("title:=.*Mercury Tour.*").Page("title:=Welcome:.*").Image("file name:=ban.*gif").Highlight ' 0.51 seconds Browser("title:=.*: Mercury.*").Page("title:=.*Mercury Tour.*").Image("file name:=ban.*f").Highlight You might notice a littledropin performancefor someofthe above statements. This is quiteobvious though. Using a realworldexample: Scenario 1
  • 18. If you were askedto deliver a letter toJohnand youhad thefollowing pieceof informationprovided:Building 184, Floor 5,Room120, Desk 9. You would know thatyou firsthave to findBuilding A, then takean elevatorto the5th floor, find Room 120,and onceyou’re inside room 120, John sits on Desk #9. This is quitestraight-forward andofcourse you’ll beableto quickly find John. Scenario 2 In anotherscenario, ifyouwereaskedto deliver a letter toJohnwhois in Building 184and onthe5thfloor, howwould you findJohn? You would haveto go toeachroomand ask for John, and makesureit is the correct John before delivering theletterto him. This might takelonger. This is roughly whathappens in ourscripts. As our descriptions getmoreand moregeneric,thetimeit takes to identify the object increases. Therefore, eventhough wildcardcharacters can simplify our work, weshould bea littlecarefulhow weusethem. Regular-Expressions.Info is a good sourceto learnregular-expressions.We willnowdo the exactsametest wedidaboutwith Banner2.gif, but this timeusing somemoreregexstylecharacters. ' Using the first few characters of the title and the first few characters of the image Browser("title:=Welcw+D+w+").Page("title:=Welcw+D+w+").Image("file name:=banw+d+.w+").Highlight ' Using the last few characters of the title with first and last characters of the image Browser("title:=w+D+w+ours").Page("title:=w+D+w+ours").Image("file name:=bw+2.gif").Highlight ' Same as above for Browser and Page, but '...' for image Browser("title:=w+D+w+ours").Page("title:=w+D+w+ours").Image("file name:=bw+2....").Highlight ' Same as above, but replaced 'b' with a '.' Browser("title:=w+D+w+ours").Page("title:=w+D+w+ours").Image("file name:=.w+2....").Highlight In the proceeding articlewewill cover OrdinalIdentifiers and also see how to create a simpletestmodule for a login process. QTP – Descriptive Programming (DP) Concepts 3 (Ordinal Identifiers) by Anshoo Arora on August 10, 2009 | QTP/DP, QTP/UFT | 75 COMMENTS This is thethird articlein the Descriptive Programming series, and willoutlinetheconcepts ofOrdinalIdentifiers used in QTP. We will also create a simpletest module (step by step) for a loginprocess using only Descriptive Programming (DP). Ordinal Identifiers – What are they?
  • 19. Let me quote QTP Reference here: An ordinal identifier assigns a numericalvalueto a testobject that indicates its orderor locationrelative to otherobjects with an otherwise identicaldescription(objects thathave the samevalues for allproperties). This ordered value provides a backup mechanism thatenables QuickTest tocreatea unique description torecognizean objectwhen the definedproperties arenotsufficient to doso. Let’s break theabovedefinitionfrom Mercury/HPinto severalparts to clarify theconcept. An ordinal identifier assigns a numericalvalueto a testobject From the quoteabove,we canconcludethatanordinalidentifier is a numerical entity.In otherwords, its simply a numberthat is assigned toa test object. that indicates its order or locationrelativeto otherobjects with an otherwise identicaldescription(objects thathave the samevalues for all properties) This means,anOrdinal Identifier works quite differentlyin relation to the properties welearned inthe 1st partofthis series. This identifier, or a property if you will, works according tothe order or location oftestobjects. Objects’ order and locationare uniquecharacteristics. For example, in a coordinatesystem, generally only a singleobject exists on a given ‘x,y’ coordinate. Thus, an ordinal identifier willa lways beunique. Index defines the order, andlocation defines location. This ordered valueprovides a backupmechanism that enables QuickTestto create a uniquedescription to recognize an objectwhen the defined properties arenotsufficient to doso. The quote aboveis a good way to concludethis concept ofOrdinalIdentifiers inQTP. Since it is always uniquefor an object, itcan become extremely usefulincluding these withobjects’ mandatory and assisstiveproperties to prevent falling intoobject recognition problems. The3 types of ordinal identifiers are: Location, Index and CreationTime (browser only). Location Ordinal Identifier Let’s use an exampleto understandhowtheLocation Identifier works.Consider the 4 WebEdits below: Text Box 1: Text Box 2: Text Box 3: Text Box 4:
  • 20. All the edits abovehave exactlythesameproperties. This propertyworks vertically, from top tobottom, and left to right. Thus, ‘TextBox 1‘will have a location valueof0, ‘Text Box3‘ willhave 1, ‘Text Box2‘ willhave2, and ‘TextBox 4‘will have3. Notethat VBScript is zero based, sothe location propertywould startat0. This canbe verified by running thefollowing statements: 'Text Box 1 Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest","location:=0").Set "1" 'Text Box 3 Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest","location:=1").Set "2" 'Text Box 2 Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest","location:=2").Set "3" 'Text Box 4 Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest","location:=3").Set "4" Text Box 1: location=0 Text Box 2: location=2 Text Box 3: location=1 Text Box 4: location=3 Index Ordinal Identifier Index is quitesimilar to location, but itworks pertaining toappearance ofobjects inthesource code1. An object appearing priorin the source code willhave a smallerIndex valueas comparedto another object that comes later in thesource. Thus,for thesame group ofeditboxes above: ‘TextBox 1′ will haveanindexof0, ‘Text Box2′ willhave 1,‘Text Box3′ will have 2 and‘TextBox 4′ will have3. Let’s testour statements: 1 Credits go to Harishfor finding this error. 'Text Box 1 Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest", "index:=0").Set "1" 'Text Box 2 Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest", "index:=1").Set "2"
  • 21. 'Text Box 3 Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest", "index:=2").Set "3" 'Text Box 4 Browser("title:=.*Descriptive.*").Page("micclass:=Page").WebEdit("name:=dpTest", "index:=3").Set "4" Text Box 1: index=0 Text Box 2: index=1 Text Box 3: index=2 Text Box 4: index=3 That was quite easy,wasn’tit? Now, let’s moveon to CreationTime,whichis an ordinal identifier strictlyreserved for the browser object. CreationTime Ordinal Identifier Again, let’s usethedescription given by HP/Mercury in QTP’s helpfile: Ifthere areseveral openbrowsers,theonewith the lowest CreationTimeis thefirstonethat was opened andtheonewith the highest CreationTime is the lastonethatwas opened. That means,thefirst browser youopen willhave a creationtimeof0. The second browser will havea creationtime of1.The thirdbrowserwill have a creationtime of2 andso on. SystemUtil.Run "iexplore.exe", "http://www.HP.com" 'CreationTime 0 SystemUtil.Run "iexplore.exe", "http://www.AdvancedQTP.com" 'CreationTime 1 SystemUtil.Run "iexplore.exe", "http://www.LinkedIn.com" 'CreationTime 2 Browser( "creationtime:=" ).Highlight 'Highlight HP.com Browser( "creationtime:=1" ).Highlight 'Highlight AdvancedQTP.com Browser( "creationtime:=2" ).Highlight 'Highlight LinkedIn.com
  • 22. When you run the above codein QTP, you willfind that thefirst browser QTP highlights on is HP.com, the second is AdvancedQTP.comand the third is LinkedIn.com. Eventhis is quite simple,isn’tit? As promised,we mustcreatea simplelogin process using the concepts wehave learnedsofar inthenext article. QTP – Descriptive Programming (DP) 4 (Creating a Test Script) by Anshoo Arora on August 10, 2009 | QTP/DP, QTP/UFT | 117 COMMENTS This is thelastarticle in ourDescriptiveProgramming series and willcover a simplelogin process using 100% DP. I havepurposely createdthe exampleto bevery high-level tomake sure its quit easy tounderstand.However, ifyou feel more examples on this conceptwillhelp, I’llbe more thanhappy tocreatea PartV ofthis series withonly real-world examples ofDP inaction. We will use the HP/Mercury Demo Website for this example. Following is the process I amgoing tofollow tocomplete this process. In your applicationhowever, you can usetheprocess that best suits your needs, but for the purposes ofthis lesson, I willkeep itquitebasic: 1. Launch Browser. 2. Check whether thecorrectbrowser opened. 3. Ensure the userName,passwordedits and theSign-Inbuttonexist. 4. Set the userName andpassword andClick Sign-In. 5. Make sure the browser navigated tothecorrect page. Step 1: Launch Browser 'We will use SystemUtil.Run to launch our target browser SystemUtil.Run "iexplore.exe", "http://newtours.demoaut.com/" Step 2: Checking if the correct browser opened The 2 new concepts in this step are: 1. Reporter Object: This objectis used tosendindividual reports to the test results. Inother words,when thetest ends, youcan seethe reportedevents inyourTest results. 2. ExitTest: Autility statement availabletoQTP that enables itto completeexit a Test. Inother words,when this statementexecutes, the test execution ends. If Browser( "title:=Welcome: Mercury Tours" ).Exist( 15 ) Then Reporter.ReportEvent micPass, "Step 1- Launch", "Correct browser was launched."
  • 23. Else Reporter.ReportEvent micFail, "Step 1- Launch", "Browser failed to launch." ExitTest End If Step 3: Ensure the userName, password edits and the Sign-In button exist. 'Notice the use of the wildcard character below If Browser("title:=Welcome:.*").Page("title:=Welcome.*").WebEdit("name:=userName").Exist(0) Then 'set username If Browser("title:=Welcome:.*").Page("title:=Welcome.*").WebEdit("name:=password").Exist(0) Then 'set password If Browser("title:=Welcome:.*").Page("title:=Welcome.*").Image("name:=login" ).Exist(0) Then 'click button Else 'report that Sign-In button was not found End If Else 'report that the password edit was not found End If Else 'report that the userName edit was not found End If Step 4: Set the userName and password and Click Sign-In. The following willcompletethesnippet above: 'Notice the use of the wildcard character below With Browser("title:=Welcome:.*").Page("title:=Welcome.*") If .WebEdit("name:=userName").Exist(0) Then .WebEdit("name:=userName").Set "test" If .WebEdit("name:=password").Exist(0) Then .WebEdit("name:=password").Set "test" If .Image("name:=login" ).Exist(0) Then .Image("name:=login" ).Click Else Reporter.ReportEvent micFail, "Sign-In Button Error", "Button not found." End If
  • 24. Else Reporter.ReportEvent micFail, "Password Edit Error", "EditBox not found." End If Else Reporter.ReportEvent micFail, "UserName Edit Error", "EditBox not found." End If End With Step 5: Make sure the browser navigated to the correct page 'Synchronize with a browser Browser( "title:=.*" ).Sync 'Wait 1 second for browser with "Find a Flight" title to exist If Browser( "title:=Find a Flight.*" ).Exist( 1 ) Then Reporter.ReportEvent micPass, "Login", "Login successful" Else Reporter.ReportEvent micFail, "Login", "Login failed" End If PUTTING IT ALL TOGETHER 'We will use SystemUtil.Run to launch our target browser SystemUtil.Run "iexplore.exe", "http://newtours.demoaut.com/" If Browser( "title:=Welcome: Mercury Tours" ).Exist( 15 ) Then Reporter.ReportEvent micPass, "Step 1- Launch", "Correct browser was launched." Else Reporter.ReportEvent micFail, "Step 1- Launch", "Browser failed to launch." ExitTest End If 'Notice the use of the wildcard character below With Browser("title:=Welcome:.*").Page("title:=Welcome.*") If .WebEdit("name:=userName").Exist(0) Then .WebEdit("name:=userName").Set "test" If .WebEdit("name:=password").Exist(0) Then .WebEdit("name:=password").Set "test" If .Image("name:=login").Exist(0) Then
  • 25. .Image("name:=login").Click Else Reporter.ReportEvent micFail, "Sign-In Button Error", "Button not found." End If Else Reporter.ReportEvent micFail, "Password Edit Error", "EditBox not found." End If Else Reporter.ReportEvent micFail, "UserName Edit Error", "EditBox not found." End If End With Browser( "title:=.*Mercury.*" ).Sync If Browser( "title:=Find a Flight.*" ).Exist( 1 ) Then Reporter.ReportEvent micPass, "Login", "Login successful" Else Reporter.ReportEvent micFail, "Login", "Login failed" End If If you have any doubtin thecontent above,please feelfreeto posta comment about it. I hope this articlehelps understandfurther the principles of DescriptiveProgramming and using it inyoureverydaywork.