QTP Functions
QTP Functions
Class 1
Class Main
private objTesting
'Call objTesting.add1
End Class
Class 2
Class Testing
Private a
End Class
Script
'private objTesting
'Call objTesting.add1
Set objTesting=objMain.getTestingReference
objTesting.add1
Posted by Arun Justin Kulandairaj at 1:53 PM 1 comments
1)
QTP has some issues in identifying object in Descriptive programming..
2)
While debugging QTP scripts from QC, some time QTP will get hangged.., it is a
known issue and even mercury knows about it.
it happends even in 9.1 also
3)Check points...
Checkpoints are hidden inside OR file and we dont have option of exporting /
importing from 1 place to other.. if we change approach it will land in problem
4)
Problem in identifying objects in case of very think client. some time identifying
objects will be problem .. specialy for list objects..in Java env
5)
QTP doesn't support drag and drop objects on web
6)
7)
spell check
Function CheckSpellErrors(Var)
Set obj = CreateObject("Word.Application")
obj.WordBasic.FileNew
obj.WordBasic.Insert Var
Set SpellErrCollection = obj.ActiveDocument.SpellingErrors
For each element in SpellErrCollection
CreateObject("wscript.shell").popup element,1,"Spell Error"
Next
NoofErrors = obj.ActiveDocument.SpellingErrors.Count
obj.Documents.Close (False)
obj.Quit
Set SpellErrCollection = Nothing
Set obj = Nothing
CheckSpellErrors = NoofErrors
End Function
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Open a HTML File for Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
g_iPass_Count = 0
g_iFail_Count = 0
g_sFileName = sFileName
g_iImage_Capture = iImageCapture
Set g_objFS = CreateObject("Scripting.FileSystemObject")
Set g_objReport = g_objFS.OpenTextFile(g_sFileName, 2, True)
g_objReport.Write "<$$HTML><$$BODY><$$TABLE BORDER=0
CELLPADDING=3 CELLSPACING=1 WIDTH=100%>"
g_objReport.Write "<$$TR COLS=2><$$TD BGCOLOR=WHITE WIDTH=6%><$
$IMG
SRC='https://webaccess.kdc.capitalone.com/GetAccess/images/logo_sso.gif'><$
/$TD><$$TD WIDTH=94% BGCOLOR=WHITE><$FONT FACE=VERDANA
COLOR=NAVY SIZE=2><$$B> Helix ProphIT Automation - " & Date & " - " &
Time & " on Machine " & Environment.Value("LocalHostName") &
"<$$/B><$$/FONT><$$/TD><$$/TR><$$/TABLE>"
g_objReport.Write "<$$TABLE BORDER=0 BGCOLOR=BLACK
CELLPADDING=3 CELLSPACING=1 WIDTH=100%>"
g_objReport.Close
Set g_objFS = Nothing
Set g_objReport = Nothing
g_tStart_Time = Now()
End Sub
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Insert a Section to Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Insert a Step to Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Insert a Result to Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
If sResult="PASS" Then
g_iPass_Count = g_iPass_Count + 1
If g_iImage_Capture=2 Then
l_sFile = Environment("ResultDir") & "\Screen" & g_iCapture_Count & ".png"
Desktop.CaptureBitmap l_sFile
g_iCapture_Count = g_iCapture_Count + 1
g_objReport.Write "<$$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$$FONT FACE=VERDANA SIZE=2>" & sDesc & "<$$/FONT><$
$/TD><$$TD BGCOLOR=#EEEEEE WIDTH=25%><$$FONT FACE=VERDANA
SIZE=2>" & sExpected & "<$$/FONT><$$/TD><$$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=WINGDINGS SIZE=4>2<$/FONT><$FONT
FACE=VERDANA SIZE=2><$A HREF='" & l_sFile & "'>" & sActual &
"<$/A><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=7%><$FONT
FACE='WINGDINGS 2' SIZE=5 COLOR=GREEN>P<$/FONT><$FONT
FACE=VERDANA SIZE=2 COLOR=GREEN><$B>" & sResult &
"<$/B><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=18%><$FONT
FACE=VERDANA SIZE=2>" & sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micPass,sDesc,sActual
Else
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" & sDesc &
"<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=25%><$FONT
FACE=VERDANA SIZE=2>" & sExpected & "<$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" &
sActual & "<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=7%><$FONT
FACE='WINGDINGS 2' SIZE=5 COLOR=GREEN>P<$/FONT><$FONT
FACE=VERDANA SIZE=2 COLOR=GREEN><$B>" & sResult &
"<$/B><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=18%><$FONT
FACE=VERDANA SIZE=2>" & sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micPass,sDesc,sActual
End If
ElseIf sResult="FAIL" Then
g_iFail_Count = g_iFail_Count + 1
If g_iImage_Capture=1 Or g_iImage_Capture=2 Then
l_sFile = Environment("ResultDir") & "\Screen" & g_iCapture_Count & ".png"
Desktop.CaptureBitmap l_sFile
g_iCapture_Count = g_iCapture_Count + 1
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" & sDesc &
"<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=25%><$FONT
FACE=VERDANA SIZE=2>" & sExpected & "<$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=25%><$FONT FACE=WINGDINGS
SIZE=4>2<$/FONT><$FONT FACE=VERDANA SIZE=2><$A HREF='" & l_sFile
& "'>" & sActual & "<$/A><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE
WIDTH=7%><$FONT FACE='WINGDINGS 2' SIZE=5
COLOR=RED>O<$/FONT><$FONT FACE=VERDANA SIZE=2
COLOR=RED><$B>" & sResult & "<$/B><$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=18%><$FONT FACE=VERDANA SIZE=2>" &
sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micFail,sDesc,sActual
Else
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" & sDesc &
"<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=25%><$FONT
FACE=VERDANA SIZE=2>" & sExpected & "<$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" &
sActual & "<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=7%><$FONT
FACE='WINGDINGS 2' SIZE=5 COLOR=RED>O<$/FONT><$FONT
FACE=VERDANA SIZE=2 COLOR=RED><$B>" & sResult &
"<$/B><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=18%><$FONT
FACE=VERDANA SIZE=2>" & sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micFail,sDesc,sActual
End If
Else
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" & sDesc &
"<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=25%><$FONT
FACE=VERDANA SIZE=2>" & sExpected & "<$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" &
sActual & "<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=7%><$FONT
FACE='WINGDINGS 2' SIZE=5 COLOR=RED>O<$/FONT><$FONT
FACE=VERDANA SIZE=2 COLOR=BLACK><$B>" & sResult &
"<$/B><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=18%><$FONT
FACE=VERDANA SIZE=2>" & sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micGeneral,sDesc,sActual
End If
g_objReport.Close
Set g_objFS = Nothing
Set g_objReport = Nothing
End Sub
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Close Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Show Report Log in Browser Window
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
Public Function
fnSynchroniseObjects(objPage,objObjectToSynchronise,intWaitValue)
Dim blnResult
blnWaitProprtyValue=CBool(blnWaitProprtyValue)
intWaitValue=(Int(intWaitValue)*1000)
objPage.Sync
End Function
Posted by Arun Justin Kulandairaj at 3:20 PM 0 comments
fnVerifyHeadingText = True
'''''''''' Creating a web element object for Heading'''''''''''''
Set objDescWebElem = Description.Create()
objDescWebElem("micclass").Value = "WebElement"
objDescWebElem("innertext").Value = Trim(strHeading)
objDescWebElem("outertext").Value = Trim(strHeading)
objDescWebElem("html tag").Value="SPAN"
''''''''''Verify Heading''''''''''''''''''''''''''''''''
If objFrame.Exist(4) Then
Set objWEHeading = objFrame.ChildObjects(objDescWebElem)
If (objWEHeading.Count <= 0) Then
fnVerifyHeadingText = False
End If
Else
fnVerifyHeadingText = False
End If
End Function
Posted by Arun Justin Kulandairaj at 3:20 PM 0 comments
Older Posts
Descriptive Programming
Introduction to Descriptive Programming.
How to write Descriptive Programming?
When and Where to use Descriptive programming?
Some points to note with Descriptive Programming.
TestObject("PropertyName1:=PropertyValue1", "..." ,
"PropertyNameX:=PropertyValueX")
Browser(“Browser”).Page(“Page”).WebEdit(“Name:=txt_Name”,”html
tag:=INPUT”).set “Test”
And 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 “Test”
Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html
tag:=INPUT”,”Index:=0”).set “Test” ‘ Refers to the textbox
Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html
tag:=INPUT”,”Index:=1”).set “Test” ‘ Refers to the radio button
To determine which property and value pairs to use, you can use the Object
Spy:
1. Go to Tools -> Object Spy.
2. Select the "Test Object Properties" radio button.
3. Spy on the desired object.
4. In the Properties list, find and write down the properties and values that can
be used to identify the object.
Properties collection also does the same thing as string arguments. The only
difference is that 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.
When you use a property name for the first time the property is added to the
collection and when you use it again the property is modified. By default each
property that is defined is a regular expression. Suppose if we have the
following description
This would mean an object with html tag as INPUT and name starting with txt.
Now actually 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
This is how we create a description. Now below is the way we can use it
Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “Test”
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 that description
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
We can use the same description for both the objects and still distinguish
between 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 the description object with the
WebRadioGroup object.
We can use description object to get all the objects on the page that matches
that specific description. Suppose we have to check 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_ChkDesc
Set obj_ChkDesc=Description.Create
obj_ChkDesc(“html tag”).value = “INPUT”
obj_ChkDesc(“type”).value = “checkbox”
Set allCheckboxes =
Browse(“Browser”).Page(“Page”).ChildObjects(obj_ChkDesc)
singleCheckBox.Set “ON”
Next
The above code will check all the check boxes present on the page. To 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.
i=0
Do While Browse(“Browser”).Page(“Page”).WebCheckBox("html
tag:=INPUT",type:=checkbox, "index:="&i).Exist
Browse(“Browser”).Page(“Page”).WebCheckBox("html
tag:=INPUT",type:=checkbox, "index:="&i).Set "ON"
i=i+1
Loop
Set obj_ChkDesc=Description.Create
obj_ChkDesc(“html tag”).value = “INPUT”
obj_ChkDesc(“type”).value = “checkbox”
2. The objects in the application are dynamic in nature and need special
handling to identify the object. The best example would be of clicking a link
which changes according to the user of the application, Ex. “Logout <>”.
3. When object repository is getting huge due to the no. of objects being
added. If the size of Object repository increases too much then it decreases the
performance of QTP while recognizing a object. [For QTP8.2 and below
Mercury recommends that OR size should not be greater than 1.5MB]
4. When you don’t want to use object repository at all. Well the first question
would be why not Object repository? Consider the following scenario which
would help understand why not Object repository
Scenario 1: Suppose we have a web application that has not been developed
yet.Now QTP 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 deployed before we can start of with making QTP 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 “Cancel”, “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 mean 30 objects which could have been represented just by
using 3 objects. So instead of adding these 30 objects to the repository we can
just write 3 descriptions for the object and use it on any page.
5. Modification to a test case is needed but the Object repository for the same
is Read only or in shared mode i.e. changes may affect other scripts as well.
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 in the form txt_1, txt_2, txt_3
and so on. Now adding all 20 the Object repository would not be a good
programming approach.
POSTED BY RAJ VELUR AT 4:13 AM 2 COMMENTS
LABELS: DESCRIPTIVE, PROGRAMMING
There are some very important methods and properties associated with it.
ReporterEvent Method:
I think this is a very common method used with Reporter object. I am sure even
if you have worked on QTP for a relatively short period, you would have come
across this.
Its syntax:
0 or micPass: If this step runs test passes which is shown in test report.
1 or micFail: If this step runs test fails which is shown in test report.
2 or micDone: Used to send message to the test report and does not affect
status of test.
3 or micWarning: Again, used to send warning message to the test report and
does not affect status of test.
and
and
Details are the user defined details for the given step.
For Example:
Filter property
There can be situations where we don't want the full status displayed on the
test report. This property can be used to selectively filter the status of your
tests.
Its syntax:
Reporter.Filter = NewMode
0 or rfEnableAll: This is the default mode. All reported events are displayed in
the Test Results.
ReportPath Property
This is used to get the path in which current test results are stored.
Its syntax:
Path_of_Results = Reporter.ReportPath
RunStatus Property
Its syntax:
Reporter.RunStatus
For Example:
What is FSO?
FSO stands for File System Object. This is used to support text file creation and
manipulation through the TextStream object and is contained in the Scripting
type library (Scrrun.dll)
The FSO Object Model has a rich set of properties, methods and events to
process folders and files.
We first create a FSO object using CreateObject and then create a text file
using CreateTextFile.
For Example: Suppose you want to create a file called "test.txt" located in C:
file_location = "C:\file_location"
We would use the same example for the rest of this post.
//3rd argument is "True" if new file has to be created if the specified file
doesn’t exist else false, blank signify false.
For example:
data = file.ReadLine()
msgbox data
Loop
You can use Write() or WriteLine() Methods to write text into a file. The
difference between the Write() and WriteLine() Method is that the latter
automatically inserts a new line character while the former doesn’t insert a
new line character.
For example:
This is a place to get all your qtp questions and answers solved.
while
Foe Example:
file_location = "C:\file_location"
fso.DeleteFile(file_location)
qtp,textfile,read,write,delete
POSTED BY RAJ VELUR AT 4:04 AM 2 COMMENTS
LABELS: FILEHANDLING
QTP Tips
Does QuickTest Professional support Macintosh operating systems?
No, QTP will not run on this OS.
What to do if you are not able to run QTP from quality center?
This is for especially for new users with QTP.
Check that you have selected Allow other mercury products to run tests and
components from Tools--> Options--> Run Tab.
File Name
Description
Type
Test.tsp
Test settings
Binary
Do not edit
Default.xls
Excel similar
Parameters.mtr
Parameterization information
Binary
Do not edit
Action
Default.cfg
Load test configuration file
Text
Do not edit
Default.prm
Load test configuration file
Text
Do not edit
Default.usp
Load test configuration file
Text
Do not edit
.usr
Load test configuration file
Text
Do not edit
Thick_usr.dat
Load test configuration file
Text
Do not edit
Thin_usr.dat
Load test configuration file
Text
Do not edit
Files within Action folder:
File Name
Description
Type
Script.mts
Action script
Text
Resource.mtr
Object Repository
Binary
Do not edit
Snapshots
Folder
Do not edit
There are few more files extensions like
.MTB Batch File
.LCK Locked
The code below will uninstall AutoCAD 2005 as well as Express Tools. Copy the code
below into Notepad and give the file the extension vbs.
Note : here strService is Services Name which you are going to start. you get this
name from control panel\Administrative Tools\Services... and right click and
select properties on the Service , here you can find Service Name.
Kill the Process if the process is under System not in User Using QTP
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cmd /k cd\ & cd c:\windows\system32 & taskkill /F /IM
ProcessName.exe"
''''' like "services.exe"
Posted by Kamesh at 4:43 AM 0 comments
Find out all the drives including Caption,size from one machine
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _ "SELECT * FROM
Win32_DiskDrive",,48)
For Each objItem in colItems
msgbox "Caption: " & objItem.Caption
msgbox "DeviceID: " & objItem.DeviceID
msgbox "Partitions: " & objItem.Partitions
msgbox "Size: " & objItem.Size
Next
End If
' Add recovery scenarios
Next
' Enable the recovery mechanism (with default, on errors, setting)
qtTestRecovery.Enabled = True
'Ensure that the recovery mechanism is set to be activated only after errors
qtTestRecovery.SetActivationMode "OnError"
how to get the column values and column header through QTP from Infragistics
UltraGrid(If Applications are developed using Net advantage Controls)
rowcount=WpfWindow("Eclipsys Gateway My").SwfWindow("Custom
View").SwfTable("grFilter").GetNAProperty("Rows.Count")
'Then to access each row:
For I = 0 TO rowcount-1
Set currentRow = WpfWindow("Eclipsys Gateway My").SwfWindow("Custom
View").SwfTable("grFilter").GetNAProperty("Rows["+CSTR(I)+"]")
' To get a specific cell text for the current row
cellText =WpfWindow("Eclipsys Gateway My").SwfWindow("Custom
View").SwfTable("grFilter").GetNAProperty("Rows["+CSTR(I)+"].Cells[3].Text")
msgbox cellText
Next
iColIndex = 2
strColKey = "value"
SET grid = WpfWindow("Eclipsys Gateway My").SwfWindow("Custom
View").SwfTable("grFilter")
msgbox
grid.GetNAProperty("DisplayLayout.Bands[0].Columns["+CSTR(iColIndex)
+"].Header.Caption")
msgbox grid.GetNAProperty("DisplayLayout.Bands[0].Columns["+strColKey
+"].Header.Caption")
Posted by Kamesh at 4:04 AM 0 comments
This section gives the introduction about test automation framework, various
types of the framework and the analysis of the best suitable framework for the
application under test (the application under test is referred as AUT). This also includes
the detailed description of the format of the input (the input to the framework is referred
as the test tables) that is given to our test automation framework.
The test automation tool vendors market their product as the main feature of the
tool is the ability to capture the user actions and later to playback them. Here is the basic
paradigm for GUI-based automated regression testing – the so called Record/Playback
method (also called as Capture/Replay approach)
2. Using the capture feature of the automation testing tool record the user actions. The
result is a macro-like script where each user action is presented.
3. Enhance the recorded script with verification points, where some property or data is
verified against an existing baseline. Add delay and wait states points where the different
actions are synchronized.
4. Playback the scripts and observe the results in the log of the test management tool.
The basic drawback in this method is the scripts resulting from this method
contain hard-coded values which must change if anything at all changes in our AUT. The
costs associated with maintaining such scripts are astronomical, and unacceptable.
These scripts are not reliable, even if the application has not changed, and often fail on
replay (pop-up windows, messages, and other things can happen that did not happen
when the test was recorded).
If the tester makes an error entering data, etc., the test must be re-recorded. If
the application changes the test must be re-recorded. All that is being tested are things
that already work. Areas that have errors are encountered in the recording process
(which is manual testing, after all). These bugs are reported, but a script cannot be
recorded until the software is corrected. So logically nothing is tested by this approach.
Play with WinRunner by recording and playing it back. Refer the WinRunner
Tutorial & WinRunner User Guide
<!--[if !vml]-->
<!--[endif]-->
The test script modularity framework is the most basic of the frameworks. It's a
well-known programming strategy to build an abstraction layer in front of a component to
hide the component from the rest of the application. This insulates the application from
modifications in the component and provides modularity in the application design. When
working with test scripts (in any language or proprietary environment) this can be
achieved by creating small, independent scripts that represent modules, sections, and
functions of the application-under-test. Then these small scripts are taken and combined
them in a hierarchical fashion to construct larger tests. The use of this framework will
yield a higher degree of modularization and add to the overall maintainability of the test
scripts.
The test library architecture framework is very similar to the test script modularity
framework and offers the same advantages, but it divides the application-under-test into
procedures and functions (or objects and methods depending on the implementation
language) instead of scripts. This framework requires the creation of library files
(SQABasic libraries, APIs, DLLs, and such) that represent modules, sections, and
functions of the application-under-test. These library files are then called directly from
the test case script. Much like script modularization this framework also yields a high
degree of modularization and adds to the overall maintainability of the tests.
A data-driven framework is where test input and output values are read from data
files (ODBC sources, CVS files, Excel files, DAO objects, ADO objects, and such) and
are loaded into variables in captured or manually coded scripts. In this framework,
variables are used for both input values and output verification values. Navigation
through the program, reading of the data files, and logging of test status and information
are all coded in the test script. This is similar to table-driven testing (which is discussed
shortly) in that the test case is contained in the data file and not in the script; the script is
just a "driver," or delivery mechanism, for the data. In data-driven testing, only test data
is contained in the data files.
This requires the development of data tables and keywords, independent of the
test automation tool used to execute them and the test script code that "drives" the
application-under-test and the data. Keyword-driven tests look very similar to manual
test cases. In a keyword-driven test, the functionality of the application-under-test is
documented in a table as well as in step-by-step instructions for each test. In this
method, the entire process is data-driven, including functionality.
1.2.4.1 Example
In order to open a window, the following table is devised, and it can be used for
any other application, just it requires just changing the window name.
Once creating the test tables, a driver script or a set of scripts is written that
reads in each step executes the step based on the keyword contained the Action field,
performs error checking, and logs any relevant information.
This allows data driven scripts to take advantage of the powerful libraries and
utilities that usually accompany a keyword driven architecture. The framework utilities
can make the data driven scripts more compact and less prone to failure than they
otherwise would have been.
The utilities can also facilitate the gradual and manageable conversion of existing
scripts to keyword driven equivalents when and where that appears desirable. On the
other hand, the framework can use scripts to perform some tasks that might be too
difficult to re-implement in a pure keyword driven approach, or where the keyword driven
capabilities are not yet in place. The following sections describe its architecture, merits
and demerits.
<!--[if !vml]-->
<!--[endif]-->
The framework is defined by the Core Data Driven Engine, the Component
Functions, and the Support Libraries. While the Support Libraries provide generic
routines useful even outside the context of a keyword driven framework, the core engine
and component functions are highly dependent on the existence of all three elements.
The test execution starts with the LAUNCH TEST(1) script. This script invokes
the Core Data Driven Engine by providing one or more High-Level Test Tables to
CycleDriver(2). CycleDriver processes these test tables invoking the SuiteDriver(3) for
each Intermediate-Level Test Table it encounters. SuiteDriver processes these
intermediate-level tables invoking StepDriver(4) for each Low-Level Test Table it
encounters. As StepDriver processes these low-level tables it attempts to keep the
application in synch with the test. When StepDriver encounters a low-level command for
a specific component, it determines what Type of component is involved and invokes the
corresponding Component Function(5) module to handle the task.
The Application Map is referred to App Map. This App Map in WRAFS is the
Application Map file created from GUI Map of WinRunner
<!--[if !vml]--><!--[endif]-->
All of these elements of the framework rely on the information provided in the
App Map to interface or bridge the automation framework with the application being
tested. The App Map is the only means by which the framework could identify the
objects in the application under test. Each of these elements is described in more detail
in the following sections. The following figure shows the diagrammatic representation of
the Hybrid Test Automation Framework.
Array Basics
Some basic info about creating and using arrays.
' The easiest way create an array is to simply declare it as follows
Dim strCustomers()
' Another method is to define a variable and then set it as an array afterwards
Dim strStaff
strStaff = Array("Alan","Brian","Chris")
' Yet another way is to use the split command to create and populate the array
Dim strProductArray
strProductArray = "Keyboards,Laptops,Monitors"
strProductArray = Split(strProductArray, ",")
' To itterate through the contents of an array you can use the For Each loop
Dim strItem
For Each strItem In strProductArray
MsgBox strItem
Next
' This will also itterate through the loop
Dim intCount
For intCount = LBound(strProductArray) To UBound(strProductArray)
Msgbox strProductArray(intCount)
Next
' This will itterate through the array backwards
For intCount = UBound(strProductArray) To LBound(strProductArray) Step -1
Msgbox strProductArray(intCount)
Next
' To add extra data to an array use Redim Preserve
Redim Preserve strProductArray(3)
strProductArray(3) = "Mice"
' To store the contents of an array into one string, use Join
Msgbox Join(strProductArray, ",")
' To delete the contents of an array, use the Erase command
Erase strProductArray
Date Manipulation Examples
Some date manipulation functions.
' calculate the minimum Date of Birth for someone who is 18 years old
strMinDoB = DateAdd("yyyy", -18, Date)
MsgBox strMinDob
' show the number of years difference between strMinDob and today
MsgBox DateDiff("yyyy", strMinDob, Date)
' set the object properties so it looks only for web check boxes
objDescription("micclass").Value = "WebCheckBox"
Next
Compare Arrays
Compare the contents of two arrays.
' Example usage
sA = Array("A", "B", "D")
sB = Array("A", "C", "B")
Dim intA1
Dim intA2
Dim blnMatched
' arrays are different size, so return false and exit function
CompareArrays = False
Exit Function
End if
' if the element was not found in array two, return false and exit function
If Not blnMatched then
CompareArrays = False
Exit Function
End If
' if the function got this far, then the arrays contain the same data
CompareArrays = True
' =============================================================
' function: CustomReportEntry
' desc : Creates a customized entry in the result file, you
' can use standard HTML tags in the message.
' params : strStatus is the result, micPass, micFail etc
' strStepName is the name of the step
' strMessage is the failure message, this can contain
' html tags
' returns : Void
' =============================================================
Function CustomReportEntry(strStatus, strStepName, strMessage)
' create a dictionary object
Set objDict = CreateObject("Scripting.Dictionary")
First thing to do is open Visual Basic and create a new Active X DLL project...
Before we add any code, we should give the Project and the Class Library
sensible names.
Now we can add a function to our Library. For this example I'm going to use a
very
basic function which will simply display a message box with a given parameter
value...
Next thing we need to do is create the DLL, this can be done from the File
menu in Visual Basic...
Note that during the development of the DLL, you can simply press F5 to run
the code in Visual
Basic. We can then still call the function from QTP, this allows us to put break-
points inside
the Visual Basic code and do some debugging.
Another thing to note is that when you finish the DLL and want to use it on
other machines,
you will need to register the DLL on the system. This can be done by simply
dragging and dropping
the DLL onto the file "RegSvr32.exe", which can be found in your Windows\
System32 folder.
Now that we have our new library ready, we can call the functions from QTP...
Dim objDLL
Using methods like this will open up several new doors for your automation by
allowing you to
execute code which isn't as easy to implement in VB Script as it is in other
languages.
' =============================================================
' Sub : ExecuteDosCommand
' desc : Run a single-line DOS command
' params : Command to run
' returns : void
' =============================================================
Sub ExecuteDosCommand(strCommand)
Dim objShell
End If
' export the data table
DataTable.ExportSheet strFile, strSheet
' destroy the object
Set objFS = Nothing
End Function 'ExportDataSheet
' =============================================================
' function: RegularExpExample
' desc : Example of how to use the regular expression object
' to find text within a string
' params : strPattern is the regular expression
' strString is the string to use the expression on
' returns : An example string showing the results of the search
' =============================================================
Function RegularExpExample(strPattern, strString)
' set global flag so we search all of the string, instead of just searching
' for the first occurrence
objRegEx.Global = True
Next
RegularExpExample = strRet
End If
' export the data table
DataTable.Export strFile
' destroy the object
Set objFS = Nothing
End Function 'ExportDataTable
Export Data Sheet
Export a data sheet at runtime.
' =============================================================
' function: ExportDataSheet
' desc : Exports a data sheet
' params : strFile - full path to save the exported xls, note
' that any existing xls will be deleted
' strSheet - sheet to export
' returns : void
' =============================================================
Function ExportDataSheet(strFile, strSheet)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the xls doesn't already exist
If objFS.FileExists(strFile) Then
' delete it if it exists
ObjFS.DeleteFile strFile
End If
' export the data table
DataTable.ExportSheet strFile, strSheet
' destroy the object
Set objFS = Nothing
End Function 'ExportDataShee
' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)
Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol
' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)
File Browser
Opens a standard dialog which allows the user to choose a file.
' =============================================================
' function : FileBrowser
' desc : Opens a standard Open File Dialog
' params : strTitle - the title to apply to the dialog
' strFilter - the filter to apply to the dialog
' returns : The selected file, including path
' =============================================================
Public Function FileBrowser(strTitle, strFilter)
Dim objDialog
' create a common dialog object
Set objDialog = CreateObject("MSComDlg.CommonDialog")
' set the properties and display the dialog
With objDialog
.DialogTitle = strTitle
.Filter = strFilter
.MaxFileSize = 260
.ShowOpen
End With
' return the selected file
FileBrowser = objDialog.FileName
' destroy the object
Set objDialog = Nothing
Else
End If
Folder Exists
Check to see if a local or network folder exists.
' =============================================================
' function: CheckFolderExists
' desc : Checks to see if a folder exists
' params : strFolder - full path of the folder to find
' returns : True if folder exists, False otherwise
' =============================================================
Function CheckFolderExists(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FolderExists(strFolder) Then
' file exists, return true
CheckFolderExists = True
Else
End If
' destroy the object
Set objFS = Nothing
Create Folder
Create a local or network folder.
' =============================================================
' function: FolderCreate
' desc : Creates a folder
' params : strFolderPath - the folder to create (full path)
' returns : void
' =============================================================
Function FolderCreate(strFolderPath)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' create the folder
If Not objFS.FolderExists(strFolderPath) Then
objFS.CreateFolder strFolderPath
End If
' destroy the object
Set objFS = Nothing
Delete Folder
Delete a local or network folder.
' =============================================================
' function: FolderDelete
' desc : Deletes a folder and all of it's contents
' params : strFolder - the folder to delete
' returns : void
' =============================================================
Function FolderDelete(strFolder)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Delete Folder", "Unable to Delete Folder '"&
strFolder &"', It Does Not Exist"
Else
' delete the folder
objFS.DeleteFolder strFolder
End If
' destroy the object
Set objFS = Nothing
End If
End If
' destroy the object
Set objFS = Nothing
End If
' destroy the object
Set objFS = Nothing
Else
End If
' destroy the object
Set objFS = Nothing
Const ForReading = 1
Write to a File
Example of how to write text to a file.
' =============================================================
' function: AppendFile
' desc : Writes a line of text to a text file, text file is
' created if it doesn't already exist
' params : strFileName is the name of the file to write to
' strLine is the text to write to the file
' returns : void
' =============================================================
Function AppendFile(strFileName, strLine)
Dim objFS
Const ForAppending = 8
' =============================================================
' function: UniqueFileName
' desc : Creates a unique file name
' params : strType - file extension
' returns : unique file name of specified type
' =============================================================
Function UniqueFileName(strType)
dim strReturn
' make sure there is a dot before the type
If left(strType,1) <> "." then strType = "." & strType
' create the file name using the date & time, and remove the / and : chars
strReturn = day(date) & month(date) & year(date) & hour(time) & minute(time)
& second(time) & strType
Compare Files
Compare the contents of two text files.
' =============================================================
' function: CompareFiles
' desc : Compares two text files
' params : strFile1 is the first file
' strFile2 is the second file
' returns : True if they are the same, False otherwise
' =============================================================
Function CompareFiles(strFile1, strFile2)
Dim objFS
Dim objFileA, objFileB
Dim strLineA, strLineB
dim intCompareResult
' repeat the following until we hit the end of one of the files
Do While ((objFileA.AtEndOfStream <> True) OR (objFileB.AtEndOfStream <>
True))
' if function got this far, means files are the same, so return True
CompareFiles = True
' =============================================================
' function: CreateDesktopShortcut
' desc : Creates a shortcut on the desktop
' params : strTargetPath is the full path to the file you
' are creating the shortcut to, i.e. c:\doc\me.txt
' strLinkName is the name of the shortcut, as it
' appears on the desktop
' strDesc is the description to set within the shortcut
' returns : void
' =============================================================
Sub CreateDesktopShortcut(strTargetPath, strLinkName, strDesc)
' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)
Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol
' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)
' set the object properties so it looks only for web check boxes
objDescription("micclass").Value = "WebCheckBox"
End If
Next
' =============================================================
' function: GetIPAddress
' desc : Returns the IP address of the PC
' params : Void
' returns : IP Address
' =============================================================
Function GetIPAddress()
Next
End If
Next
Dim objNet
' =============================================================
' function: GetSystemVariable
' desc : Get the value of a system variable
' params : strSysVar is the variable name
' returns : Content of variable name
' =============================================================
Function GetSystemVariable(strSysVar)
Dim objRegEx
' =============================================================
' function: WriteLog
' desc : Writes a message to a log file. File is created
' inside a Log folder of the current directory
' params : strCode is a code to prefix the message with
' strMessage is the message to add to the file
' returns : void
' =============================================================
Function WriteLog(strCode, strMessage)
Dim objFS
Dim objFile
Dim objFolder
Dim strFileName
' is there a log folder in the directory that we are currently working
If Not objFS.FolderExists(objFS.GetAbsolutePathName(".") & "\log") Then
' set a name for the log file using year, month and day values
strFileName = objFS.GetAbsolutePathName(".") & "\log\" & year(date) &
month(date) & day(date) & ".log"
Loop Basics
Some basic information about various loop types.
' Loops allow you to run a group of statements repeatidly.
'
' There are four types of loop available, all very easy to
' use and understand. This code sample will explain how
' to use each type of loop.
'
' Do...Loop
' Check these two examples of Do...While, there is one major difference
' between them. In Example A the cose will check the value of intCounter
' before it enters the loop, but in Example B the code will enter the
' loop regardless of the value of intCounter.
' Example A
intCounter = 0
Do While intCounter < 5
intCounter = intCounter + 1
MsgBox intCounter
Loop
' Example B
intCounter = 0
Do
intCounter = intCounter + 1
MsgBox intCounter
Loop While intCounter <5
' Example B
intCounter = 0
Do
intCounter = intCounter + 1
MsgBox intCounter
Loop Until intCounter = 6
' For...Next
' For...Next Loops will execute a series of statements until a specific counter
value
' is reached.
For iCounter = 1 To 5
MsgBox iCounter
Next
' You can add a Step keyword to define how much the counter should increase
with each
' itteration of the loop
For iCounter = 1 To 10 Step 2
MsgBox iCounter
Next
' For...Each
' Another variation on the For...Next loop is the For...Each loop. The For...Each
' loop is used to execute a series of statements for each object in a collection,
' i.e. each element of an array. For example...
Dim strPeopleList
Dim strPerson
strPeopleList = Array("Alan", "Bob", "Craig", "Dan")
For Each strPerson in strPeopleList
MsgBox strPerson
Next
' While...Wend Loops
'
' This type of loop will execute a series of statements as long as
' a given condition is true.
' Note: It's advisable to avoid using this type of loop, you should
' us the Do...Loop instead
' Here's an example anyway...
iCounter = 0
While iCounter < 5
iCounter = iCounter + 1
Msgbox iCounter
Wend
Minimize QTP
Minimize the main QTP window.
' =============================================================
' function: MinimizeQTP
' desc : Minimize QTP window
' params : None
' returns : void
' =============================================================
Function MinimizeQTP()
dim objQTP
Move File
Move a file from one location to another.
' =============================================================
' function: FileMove
' desc : Moves a file from one location to another
' params : strFile - full path to the source file
' strTarget - the folder to move the file to
' returns : void
' =============================================================
Function FileMove(strFile, strTarget)
Dim objFS
Else
objFS.CreateFolder(strTarget)
End If
End If
End If
End If
' destroy the object
Set objFS = Nothing
Capture Screenshot
Capture and save a PNG of the entire screen.
' =============================================================
' function: ScreenShot
' desc : Creates a png of the entire screen
' params : n/a
' returns : name of saved png
' =============================================================
Function ScreenShot()
dim strPNG
dim objDesktop
' set a unique file name using the date/time
strPNG = "C:\Screenshot_" & day(date) & month(date) & year(date) & _
& hour(time) & minute(time) & second(time) & ".png"
' desktop object
Set objDesktop = Desktop
' capture a png of the desktop
obj.CaptureBitmap strPNG, true
' return the file name
ScreenShot = strPNG
' destroy the object
Set objDesktop = Nothing
End Function 'ScreenShot
' =============================================================
' function : SetWithDebug
' desc : Sets the value of an edit box with additional logging
' =============================================================
Function SetWithDebug(objEdit, strValue)
End Function
Registering a Procedure
Register a procedure with an object class.
' =============================================================
' function : GetItemsCountFunction
' desc : Returns the number of items from a weblist
' =============================================================
Function GetItemsCountFunction(objWebList)
End Function
Query a Database
Simple example of how to query an access database.
dim objDB
dim objRS
dim intCounter
' create a database and recordset objects
Set objDB = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.RecordSet")
' configure the connection
objDB.Provider="Microsoft.Jet.OLEDB.4.0"
objDB.Open "c:\MyTestDatabase.mdb"
' count the number of records in the employee table
objRS.Open "SELECT COUNT(*) from Employee" , objDB
Msgbox "There are " & objRS.Fields(0).Value & " records in the employee table."
' destroy the objects
Set objDB = Nothing
Set objRS = Nothing
Read a Text File
Example of how to read a text file line-by-line.
' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)
Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol
' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)
' =============================================================
' function : RegistryRead
' desc : Read a value from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to read, i.e.
' "Software\Test\Automation"
' returns : Value from the registry key
' =============================================================
Function RegistryRead(strRoot, strPath)
' create the shell object
Set objShell = CreateObject("WScript.Shell")
Registering a Procedure
Register a procedure with an object class.
' =============================================================
' function : GetItemsCountFunction
' desc : Returns the number of items from a weblist
' =============================================================
Function GetItemsCountFunction(objWebList)
Replace Method
Using the replace method to find and replace text in a string.
' =============================================================
' function: ReplaceText
' desc : Uses a regular expression to replace text within a string
' params : strString is the string to perform the replacement on
' strPattern is the regular expression
' strReplacement is the replacement string
' returns : The finished string
' =============================================================
Function ReplaceText(strString, strPattern, strReplacement)
Dim objRegEx
' =============================================================
' Sub : RegistryWrite
' desc : Writes a key value to the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to create, i.e.
' "Software\Test\Automation"
' strValue is the value to write in the key
' returns : void
' =============================================================
Function RegistryWrite(strRoot, strPath, strValue)
' =============================================================
' function : RegistryRead
' desc : Read a value from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to read, i.e.
' "Software\Test\Automation"
' returns : Value from the registry key
' =============================================================
Function RegistryRead(strRoot, strPath)
' =============================================================
' function: RegistryDelete
' desc : Deletes a key from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to delete, i.e.
' "Software\Test\Automation"
' returns : void
' =============================================================
Function RegistryDelete(strRoot, strPath)
' =============================================================
' function: CustomReportEntry
' desc : Creates a customized entry in the result file, you
' can use standard HTML tags in the message.
' params : strStatus is the result, micPass, micFail etc
' strStepName is the name of the step
' strMessage is the failure message, this can contain
' html tags
' returns : Void
' =============================================================
Function CustomReportEntry(strStatus, strStepName, strMessage)
' =============================================================
' function: WriteLog
' desc : Writes a message to a log file. File is created
' inside a Log folder of the current directory
' params : strCode is a code to prefix the message with
' strMessage is the message to add to the file
' returns : void
' =============================================================
Function WriteLog(strCode, strMessage)
Dim objFS
Dim objFile
Dim objFolder
Dim strFileName
' is there a log folder in the directory that we are currently working
If Not objFS.FolderExists(objFS.GetAbsolutePathName(".") & "\log") Then
' set a name for the log file using year, month and day values
strFileName = objFS.GetAbsolutePathName(".") & "\log\" & year(date) &
month(date) & day(date) & ".log"
' =============================================================
' function: CheckIfServiceIsRunning
' desc : Check to see if a service is running
' params : strServiceName is the name of the service
' returns : True if running, False otherwise
' =============================================================
Function CheckIfServiceIsRunning(strServiceName)
Function: String
Accepts a number and a character. Returns a string created with the character
that is repeated the given number of times.
' example
MsgBox String(5,"A")
Function: Len
Returns the number of characters from a given string.
' example
strMyName = "Joe Bloggs"
MsgBox "The Name '" & strMyName & "' is " & Len(strMyName) & " characters
long"
Function: Instr
Accepts two strings and returns True if the second string is contained within
the first.
' example
If Instr("Hello, welcome to www.QTPHelper.com!", "QTP")>0 Then MsgBox
"Found"
Function: Left
Returns the given number of left-most characters from a string
' example
MsgBox Left("Joe Bloggs", 3)
Function: Right
Returns the given number of right-most characters from a string
' example
MsgBoxRight("Joe Bloggs", 6)
Function: LCase
Returns a given string in lower-case
' example
MsgBox LCase("JoE BloGGs")
Function: UCase
Returns a given string in upper-case
' example
MsgBox UCase("joe bloggs")
Get System Information
Get system information like User Name and Computer Name.
Dim objNet
' =============================================================
' function: GetSystemVariable
' desc : Get the value of a system variable
' params : strSysVar is the variable name
' returns : Content of variable name
' =============================================================
Function GetSystemVariable(strSysVar)
' create description objects for each item we are dealing with
Set objLogout = Description.Create()
Set objUser = Description.Create()
Set objPass = Description.Create()
Set objRemember = Description.Create()
End If
APPLICATION MAP
The Application Map is one of the most critical components, which is used for
mapping the objects from names humans can recognize to a data format useful for the
automation tool. For a given project it is needed to define a naming convention or
specific names for each component in each window as well as a name for the window
itself. Then use the Application Map to associate that name to the identification method
needed by the automation tool to locate and properly manipulate the correct object in the
window.
Application Map not only gives the ability to provide useful names for the objects,
it also enables the scripts and keyword driven tests to have a single point of
maintenance on the object identification strings. Thus, if a new version of an application
changes the title of the window or label of the components or the index of an image
element within it, they should not affect the test tables. The changes will require only a
quick modification in one place--inside the Application Map.
COMPONENT FUNCTIONS
The component Functions takes the windows name in which the component
resides, the actual component name on which the action is to be performed, the values
needed for performing the action and the type of action to be performed as its
arguments. The Component Function keywords and their arguments define the low-level
vocabulary and individual record formats will be used to develop the test tables.
TEST TABLES
The input to the framework apart from the application map are the test tables, which
holds the arguments needed for the Component Functions and other information. There
are three levels in which the test tables are organized, they are as follows,
The StepDriver module is the one that initially parses and routes all low-level
instructions that ultimately drive our application.
The Suite Tables are handled by the SuiteDriver module which parses each
record in the Suite Table and passes each Step Table to the StepDriver module for
processing.
High-level Test Tables or Cycle Tables combine intermediate-level Suites into Cycles.
The Suites can be combined in different ways depending upon the testing Cycle which is
efficient to execute. Each Cycle will likely specify a different type or number of tests. The
columns in the Cycle Tables are as follows,
These Cycles are handled by the CycleDriver module which passes each Suite
to SuiteDriver for processing.
The Core Data Driven Engine is the primary part of the framework and it has
three main modules, they are as follows
<!--[if !supportLists]--> <!--[endif]-->StepDriver
CycleDriver processes Cycles, which are high-level tables listing Suites of tests
to execute. CycleDriver reads each record from the Cycle Table, passing SuiteDriver
each Suite Table it finds during this process. SuiteDriver processes these Suites, which
are intermediate-level tables listing Step Tables to execute. SuiteDriver reads each
record from the Suite Table, passing StepDriver each Step Table it finds during this
process. The following figure represents the Core Data Driven Engine,
<!--[if !vml]-->
<!--
[endif]-->
SUPPORT LIBRARIES
The Support Libraries are the general-purpose routines and utilities that let the
overall automation framework do what it needs to do. They are the modules that provide
services like,
They also provide traditional automation tool scripts access to the features of our
automation framework including the Application Map functions and the keyword driven
engine itself. Both of these items can vastly improve the reliability and robustness of
these scripts until such time that they can be converted over to keyword driven test
tables.
'In order to have IntelliSense for the Dictionary object, and have it recognized by other
actions, it is added to the registry
Dim WshShell
' After updating the registry, you must close and reopen QuickTest Professional.
'
************************************************************************
***********
' -----------------------------
' Exists
' Remove
' RemoveAll
' Add
GlobalDictionary.Add <Key Name>, <Value> ' Create a new key and assigns its value
' Item
Regular Expression
Objects and text strings with varying (changeable) values or we can say dynamic values can be
identified by QuickTest using Regular expressions.
You can use regular expressions only for values of type string.
When any special character in a regular expression is preceded by a backslash (\), QuickTest
searches for the literal character.
You can define a regular expression for a constant value, a Data Table parameter value, an
Environment parameter value, or a property value in a programmatic description.
For more common options to create Regular Expressions, see QTP User Guide.
Instead of writing more about QTP regular expressions, lets quickly jump to examples.
[This is just an example using Yahoo mail inbox. Your inbox unread mails may differ from the one
shown in this example]
Now if you don't check any mail in your inbox and log out and then again run this code it will work fine.
But if you check any mail like if I check one mail in my inbox then it will be Inbox(5), then if I run this
code it will fail because the link has changed from Inbox(6) to Inbox(5) and shows the below
mentioned error.
"Cannot identify the object Inbox(6) (of class Link). Verify that this object`s properties match an
object currently displayed in your application."
Now we will change the above code with the help of regular expression so that it will work even if there
is only one unread mail.
Object Repository window will open. Select the object "Inbox(6)". Click on the label Inbox(6) inside
Value column and then click on "<=>" button which will appear.
When you click on the button, it will open 'Value Configuration Options' window. On this window click
on Regular Expression check box. When you click on checkbox it will show warning . Just click on Yes.
Now in the Constant text box inside the displayed window( what I have entered "Inbox \([5-6]\)" and
click Ok and close Object Repository window.
This Regular Expression setting which we have done works for inbox unread mails between 5 and 6
e.g. if your inbox says inbox(5) or inbox(6).
Run the test. It passes for me because I had 5 unread mails in my inbox (inbox(5)).
You can do this setting according to your convenience e.g. [1-5] for unread mails between 1 and 5 and
so on.
VBScript Examples
1) Write a program for finding out whether the given year is a leap year or not?
Dim xyear
xyear=inputbox ("Enter Year")
If xyear mod 4=0 Then
msgbox "This is a Leap year"
Else
msgbox "This is NOT"
End If
2) Write a program for finding out whether the given number is, Even number or
Odd number?
Dim num
num=inputbox ("Enter a number")
If num mod 2=0 Then
msgbox "This is a Even Number"
Else
msgbox "This is a Odd Number"
End If
Dim p,t, r, si
p=inputbox ("Enter Principle")
t=inputbox ("Enter Time")
r=inputbox ("Enter Rate of Interest")
si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest
msgbox ("Simple Interest is " &si)
5) Read Four digit number, calculate & display the sum of the number or display
Error message if the number is not a four digit number?
6) Read any Four-digit number and display the number in reverse order?
Dim num,rev
num= inputbox("Enter a number")
If len(num)=4 Then
rev=rev*10 + num mod 10
num=num/10
num= left(num,3)
rev=rev*10 + num mod 10
num=num/10
num= left(num,2)
rev=rev*10 + num mod 10
num=num/10
num= left(num,1)
rev=rev*10 + num mod 10
msgbox "Reverse Order of the number is "&rev
Else
msgbox "Number, you entered is not a 4 digit number"
End If
Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 1 to n step 2
msgbox num
Next
Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 2 to n step 2
msgbox num
Next
Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgbox num
Next
16) Verify weather the entered 10 digit value is a numeric value or not?
Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))
If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and
isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and
isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and
isnumeric (d10) = "True" Then
17) Verify weather the entered value is a 10 digit value or not and Numeric value or
not? (Using multiple if conditions)
Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))
If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and
isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and
isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and
isnumeric (d10) = "True" Then
msgbox "It is a Numeric Value"
End If
End If
debug below
Parameter("companyName") = "07_Daniel"
Parameter("searchString") = "Assigned to"
debug above
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexBox("...").Fle
xCanvas("Overview").FlexPanel("What's New").Output CheckPoint("What's New
Table")
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexDividedBox("
Home").FlexPanel("casesPanel").FlexDividedBox("index:15").FlexDataGrid("con
tentGrid").DoubleClick aName
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexDividedBox("
Home").FlexPanel("casesPanel").FlexDividedBox("index:15").FlexDataGrid("con
tentGrid").DoubleClick aName
'************ Programmatically parse and verify the text in PDF docs using
clipborad to text '************
string1 = "Hello World"
len_data = len(string1)
i=0
file_path = "C:\qtp\pdftotext.text"
Set clipboard = createobject("mercury.clipboard")
Set fso = createobject("scripting.filesystemobject")
Set notepad = fso.createtextfile(file_path,8)
'************ Start recording click on Edit menu--select all, 'click on Edit menu--
copy, click on pdf file to get deselect 'the text...'************
Window("Adobe Reader").Activate
Window("Adobe Reader").WinMenu("Menu").Select "Edit;"
Window("Adobe Reader").WinMenu("Menu").Select "Edit;"
Window("Adobe Reader").Activate
get_text = clipboard.gettext
notepad.Write get_text
notepad.Close
End if
Loop
'msgBox ("the text is found in" &i &"rows")
'************ Programmatically parse and verify the text in PDF docs using
clipborad to text '************
LocalParameter("filePath") = "C:\qtp\"
LocalParameter("fileType") = "parsePDF.xls"
LocalParameter("verifyText") = "Stephanie Cassady"
LocalParameter("pdfDoc") = "cover letter.pdf"
filePath = LocalParameter("filePath")
localPath = LocalParameter("filePath")&LocalParameter("fileType")
snapData = LocalParameter("verifyText")
Dim captureData
lenData = Len(snapData)
i=0
rowCounter=0
filePath = localPath
Set clipboard = createobject("mercury.clipboard")
Set fso = createobject("scripting.filesystemobject")
Set notepad = fso.createtextfile(filePath,8)
getText = clipboard.gettext
notepad.Write getText
notepad.Close
End if
Loop
If captureData Then
msgBox "The '"&captureData &"' text were found in the number " &searchData
&" position on row "&rowNumber+1
Else
msgBox "The were no text found in this document that matches what you're
looking for. Code: ID-10-T, S-U-E"
End If
initialIndex = 7
For Iterator = 1 To numNotes-1 Step 1
initialIndex=initialIndex+13
Next
resultIndex = ("index:"&initialIndex)
buttonIndex = ("index:"&initialIndex+1)
shareIndex = ("index:"&initialIndex+5)
LocalParameter("shareNote") = resultIndex
LocalParameter("share") = shareIndex
If assertTrue(userMarcus.exists(NULL)) Then
userMarcus.edit(ARRAY("Role", "Agile SCRUM Master"))
End If
i=1
basic100 = "Basic (100%)"
ParArray = Array(A, B,C)
n = Ubound (ParArray)
msgBox n
For i = 0 To n Step 1
msgBox ParArray(i)
msgBox ParArray(i) <> Empty
If ParArray(i) <> Empty Then
Reporter.ReportEvent micPass, "Verify whether the field is populated with data",
" The "&basic100&" field is not empty."
msgBox i
Else
Reporter.ReportEvent micFail, "Verify whether the field is populated with data",
" The "&basic100&" field is EMPTY."
msgBox i
End If
Next
'************ Lbound Arrays '************
A = "1"
B = "2"
C = "3"
i=1
basic100 = "Basic (100%)"
ParArray = Array(A, B,C)',(a,b,c)
n = Ubound (ParArray)
msgBox n
For i = 0 To n Step 1
msgBox ParArray(i)
msgBox ParArray(i) <> Empty
If ParArray(i) <> Empty Then
Reporter.ReportEvent micPass, "Verify whether the field is populated with data",
" The "&basic100&" field is not empty."
msgBox i
Else
Reporter.ReportEvent micFail, "Verify whether the field is populated with data",
" The "&basic100&" field is EMPTY."
msgBox i
End If
Next
i =6
j =0
k =4
numRows = 6
Next
'************ Calculate Variable Index 2'************
j=0
i=6
k=4
'Index number for that column within that row
resultColumnIndex=0
'Extracted value from the flex property
rowIndex=12
'Number of rows
max=3
'The index number of the last row. e.g. for 4 rows - the last index number would
be 12
range=(max+1)*3
'Step 3: Comparision
If strComp(strText,strTBL_text) = 0 then
Reporter.ReportEvent micPass, "PASS","PASS"
Else
Reporter.ReportEvent micFail,"FAIL","FAIL"
End If
Set xlApp=CreateObject("Excel.Application")
Set xlBook=xlApp.workbooks.add
Set xlSheet=xlBook.activesheet
xlSheet.cells(1,1)="helloo"
xlBook.saveas "c:test.xls"
xlApp.quit
SendTo=".......@........com"
SendToCC=".......@........com"
Subject="QTP mail"
Body1="This mail is generated from QTP Environment"
Attachment="C:\Spec.xls"
Function AttachHTMLAsMailContent(sSendTo,
sSendToCC,sSendToBCC,sSubject,sHtmlPath)
Dim objOutlook
Dim objOutlookMsg
Dim olMailItem
' Create the Outlook object and the new mail object.
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(sHtmlPath,1)
strText = ts.ReadAll
.HTMLBody = strText
.Display
End With
End Function
'Sample usage
'AttachHTMLAsMailContent "MyName@abc.com","","","TestResults-
MultipleAttachments","D:TestCase.html"
For i = 1 to secondchild.count()
secondchild.item(i).ElementName()
Next
'Save changes
xmlDoc.Save(XMLDataFile)
'Save changes
xmlDoc.Save(XMLDataFile)
End Function
End Select
'***************************************************************************
******************************************************
' Run suite QA Deployment Sanity Test
qtApp.Open "C:\Temp\simple_test", True ' Open the test in read-only mode
'Email Status
WScript.StdOut.Write "Status is:" & qtTest.LastRunResults.Status ' Check the
results of the test run
Set qtResultsOpt = Nothing ' Release the Run Results Options object
Set qtTest = Nothing ' Release the Test object
Set qtApp = Nothing ' Release the Application object
'***************************************************************************
******************************************************
'Call scripts and execute
'Load common functions from library
Execute getTextFileContent("\\server\path\libraryFileName","Unicode")
'***************************************************************************
******************************************************
'Filter email messages in MS Outlook
Const olFolderInbox = 6
'***************************************************************************
******************************************************
'Lock PC after QTP run
Set obj = CreateObject("WScript.Shell")
sCmnd = "%windir%\SYSTEM32\rundll32.exe user32.dll,LockWorkStation"
obj.Run sCmnd, 0, False
'***************************************************************************
******************************************************
'File Compare
public function FileComparison(in File1, inFile2, out Result)
{
auto SaveFile = "Somefile in which the compared files are saved for future
viewing."
return(Result);
}
'***************************************************************************
******************************************************
'Outlook API
sServer = "mse20be3,mse20.exchange.ms" '"your.server.address.here"
sMailbox = "Arnold Conchas" '"mailboxName"
' create your Inbox object and get the messages collection
Set oInbox = oSession.Inbox
Set oMessageColl = oInbox.Messages
'***************************************************************************
******************************************************
'Outlook message extraction
Dim strBody ' Body
Const olFolderInbox = 6 ' Folder Constant in VBScript.
Dim objMail ' Mail Object.
Dim strFilter ' Filter For Messages
Dim strSubject 'What are we looking for?
strSubject = "Something" 'Change this to whatever subject fragment you want.
' ***** Filter Messages by Unread Flag And Sort Then in Descending Order
********** '
strFilter = "[UnRead] = True"
Set objResMailItems = objMailItems.Restrict( strFilter )
objResMailItems.Sort "[UnRead]",True
' ******* Search a mail with the given Subject ************ '
If InStr(objMail.Subject,strSubject) > 0 Then
strBody = objMail.Body
objMail.UnRead = False 'Marke message as unread
Exit For
End If
Next
Msgbox strBody
'***************************************************************************
******************************************************
'Send Keys
Set WshShell = CreateObject("WScript.Shell")
Browser("Browser").Page("Dashboard").WebEdit("WebEdit").Set "7208"
WshShell.SendKeys "{ENTER}"
Set WshShell = Nothing
'***************************************************************************
******************************************************
'Search email web based client
Browser("micClass:=Browser").Page("micClass:=Page").Frame("html
id:=canvas_frame").WebElement("innerText:=info@emailiwant.com","html
tag:=SPAN","index:=0").Click
'***************************************************************************
******************************************************
'Open link from email
Define the collection
Set oDesc = Description.Create()
oDesc("micclass").Value = "Link"
Wait (0.5)
Set Links =
Browser("micClass:=Browser").Page("micClass:=Page").ChildObjects(oDesc)
NumberOfLinks = Links.Count()
nLoopCount = 0
svOuterHTML = Links(nLoopCount).GetROProperty("outerHTML")
Loop
Links(nLoopCount).Click
'***************************************************************************
******************************************************
'Query DB by using and caliing stored procedure
Set objDB = CreateObject("ADODB.Connection")
strDSN = "DRIVER=SQL Server; DATABASE=[databasename];APP=QuickTest
Professional;SERVER=[servername];Description=Testconnection"
objDB.Open(strDSN)
Set objRec = objDB.Execute("exec [spname] '[param1]','[param2'")
Do Until objRec.EOF
Msgbox objRec.Fields("[column]")
objRec.MoveNext
Loop
Set objRec = Nothing
Set objDB = Nothing
'***************************************************************************
******************************************************
Set cnn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cnn.ConnectionString ="CONNECTION STRING"
cnn.open
query = "QUERY HERE"
rs.open query,cnn
rs.movefirst
msgbox rs(0)
msgbox rs(1)
'***************************************************************************
******************************************************
'Get last date of the month
MsgBox DateSerial(Year(Now), 1 + Month(Now), 0)
'***************************************************************************
******************************************************
sub LastDateOfCurMonth()
dim lstDateCurMonth, fstDateCurMonth, fstDateNxtMonth
fstDateCurMonth="01/" & Month(date) & "/" & Year(Date)
fstDateNxtMonth=DateAdd("m",1,fstDateCurMonth)
lstDateCurMonth=DateAdd("d",-1,fstDateNxtMonth)
wscript.echo "Last Date of Current Month is: " & lstDateCurMonth
End Sub
call LastDateOfCurMonth
'***************************************************************************
******************************************************
accruedPeriod = 16
msgBox numDay
'Mousemove on flex
'ManualStep "Step 1", "Type text in the note, then click the Share button on the
New Note ", "A Share Note message pop up displays with the following: · 'Are you
sure you want to share the selected note with the agent?' · Yes button · No button"
'ManualStep "Step 2", "Select 'Send e-mail to agent', then click the Yes button",
"The pop-up closes and a notification displays in the What's New area"
'Share Note
numNotes = Parameter("numNotes")
initialIndex = 7
For Iterator = 1 To numNotes-1 Step 1
initialIndex=initialIndex+13
Next
resultIndex = ("index:"&initialIndex)
buttonIndex = ("index:"&initialIndex+1)
shareIndex = ("index:"&initialIndex+5)
LocalParameter("shareNote") = resultIndex
LocalParameter("share") = shareIndex
actualNumNotes =
Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexBox("notesContainer").g
etROproperty("numchildren")
If actualNumNotes => numNotes Then
Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexBox("shareNote").Mous
eMove
Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexButton("Share").Click
Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexBox("shareNote").Mous
eMove
Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexBox("notesContainer").
Click
End If
************************
Set olapp = createobject("outlook.application")
set inbox = olapp.getnamespace("mapi").folders
msgbox inbox.count
sub getunreadmails(objfolder)
end sub
sub getsubfolders(objparentfolder)
set colfolders = objparentfolder.folders
for each objfolder in colfolders
set objsubfolder = objparentfolder.folders(objfolder.name)
if objfolder.name<>"notes" then
getunreadmails(objfolder)
end if
getsubfolders objsubfolder
next
end sub
******************************************
olFolderInbox = 6
varSubject = "Info from Closing.com" 'The subject of your mail
Set objOutlook = CreateObject("outlook.application")
Set objNameSpace = objOutlook.GetNameSpace("MAPI")
Set Inbox = objNameSpace.GetDefaultFolder(olFolderInbox)
Set Mail = Inbox.Items.Restrict("[Subject] = " & Chr(34) & varSubject &
Chr(34) )
'The above line is used to filter mails by subject similarly u can use "From" in
place of subject.
if sail.Count = 1 then
Msgbox "Mail Found"
Else
Msgbox "Mail Not present or there are More than one mail with same subject"
End if
POSTED BY ARNOLD AT 10:41 AM
12:37 AM | Add a comment | Permalink | Blog it | News and politics
January 18
Return Sub
Description
Value Datatype
0 vbEmpty Empty (uninitialized)
1 vbNull Null (no valid data)
2 vbIntegerInteger
3 vbLong Long integer
Single-precision floating-point
4 vbSingle
number
Double-precision floating-
5 vbDouble
point number
6 vbCurrency Currency
7 vbDate Date
8 vbString String
9 vbObject Automation object
10 vbError Error
11 vbBoolean Boolean
Variant (used only with arrays
12 vbVariant
of Variants)
13 vbDataObjectA data-access object
17 vbByte Byte
8192 vbArray Array
Ex:
Dim x
x=10
msgbox vartype(x) 'Returns 2
In the above table 2 indicates vbInteger datatype.So x is an integer
type.
Typename directly returns the name of the Sub Datatype of a
variable.
Sub
Description
Datatype
Byte Byte value
Integer Integer value
Long Long integer value
Single Single-precision floating-point value
Double Double-precision floating-point value
Currency Currency value
Decimal Decimal value
Date Date or time value
String Character string value
Boolean Boolean value; True or False
Empty Unitialized
Null No valid data
<object type> Actual type name of an object
Object Generic object
Unknown Unknown object type
Object variable that doesn't yet refer to an
Nothing
object instance
Error Error
Ex:
Dim x
x=10
msgbox typename(x) 'Returns “Integer”
If vartype(oValue)=8 then
IsString=true
Else
IsString=False
End If
End Function
'*******************************
12:20 AM | Add a comment | Permalink | Blog it | VB Script Samples
January 16
Approach 1:
For example, in the above table if the WebEdit step is failed then how
do we figure out the failure for which object in the application by just
using “name:=q” property. If we have assigned those properties to a
constant which is having an understandable name then it will be very
easy to identify for which object the failure occurs.
So now we have Excel Keywords and Object Description Constants. We
have to write driver script. Follow the
below steps prior to write the driver
script.
1. Create a Folder
“KeyWordDrivenSample” in
“C:\” drive
o In this folder create 3
subfolders with the names
“Scripts”,
“Constants”,”KeyWords”
2. Prepare an excel like how it is available in above table Save the
Excel file in the “C:\KeyWordDrivenSample\KeyWords”
folder with the name “ScriptKeywords.xls”
3. Copy above Object Description Constants in a VBS File and save
it in the “C:\KeyWordDrivenSample\Coanstants” with the
name “OR Constants.vbs”
4. Open a new test in QTP and Save the test in “C:\
KeyWordDrivenSample\Scripts” Folder with the name
“Driver Script”
Now you should have the Folder structure like specified below
Now you can save the below script in Driver Script and Run it.
'####################################################
###############
' Objective : This is a driver script for Sample Keyword Driven Framework
' Test Case : Driver Script
' Author : Sudhakar Kakunuri
' Date Created : 01/16/2010
' Date Updated : 01/16/2010
'Updated by : Sudhakar Kakunuri
'####################################################
###############
'##############Initialize Variables and Load
Libraries#############################
ExecuteFile "..\..\Costants\OR Constants.vbs"
'#####################Driver Script
######################################
'Add a new sheet and import keywords
Set dtKeyWords=DataTable.AddSheet("Keywords")
Datatable.ImportSheet "..\..\Keywords\ScriptKeywords.xls","Sheet1","Keywords"
'Get Row Count and Column Colunt of the databable
dtRowCount=dtKeyWords.GetRowCount
dtColumnCount=dtKeyWords.GetParameterCount
'Use for lop to get values row by row
For dtRow=1 to dtRowCount
dtKeyWords.SetCurrentRow (dtRow)
strObjClass = DataTable("ObjectClass","Keywords")
strObjProperties = DataTable("ObjectProperties","Keywords")
strOperation = DataTable("Operation","Keywords")
strValue = DataTable("Value","Keywords")
If strOperation="SetParent" Then
oParentObjectArray=Split(strObjClass,"/")
oParentObjectPropArray=Split(strObjProperties,"/")
For iParentCount=0 to ubound(oParentObjectArray)
iParent=oParentObjectArray(iParentCount)
iParentProps=oParentObjectPropArray(iParentCount)
If iParentCount=ubound(oParentObjectArray) Then
strParent=strParent&iParent&"("&""""&eval(iParentProps)&""""&")"
Exit For
End If
strParent=strParent&iParent&"("&""""&eval(iParentProps)&""""&")."
Next
ParentObject=strParent
Else
oStatement=ParentObject&"."&strObjClass&"("&""""& eval(strObjProperties)
&""""& ")."& strOperation
If strValue<>"" Then
iStrInputDataArray=split(strValue,",")
For iInputValuesCount=0 to UBound(iStrInputDataArray)
If iInputValuesCount=UBound(iStrInputDataArray) Then
oStatement=oStatement&" "&""""&
iStrInputDataArray(iInputValuesCount) &""""
Exit for
End If
oStatement=oStatement&" "&""""& iStrInputDataArray(iInputValuesCount)
&""""&","
Next
End If
Execute (oStatement)
End If
Next
'####################################################
###############
Note: I have given this as a sample. As of now it only works
with Test Objects.