Beruflich Dokumente
Kultur Dokumente
Analog mode: This mode records exact mouse and keyboard "movements" you perform
in relation to the screen / application window. This mode is useful for the operation
such as drawing a picture, recording signature., drag and drop operations.
8) How will you call from one action to another action ?
We can call an action in 2 ways
1) Call to copy of Action. - In this ,the Action Object Repository , Script and Datable will
be copied to the destination Test Script.
2) Call to Existing Action. - In this, Object Repository , Script and Datable will NOT be
copied but a call (reference) would be made to the Action in the source script.
10) How to perform Cross platform testing and Cross browser testing using QTP? Can u
explain giving some example?
You will need to create separate Actions which take care of different OS and Browsers
Cross Platform Testing:
Using the Built in Environment Variable you can dig up the OS information.
Eg. Platform = Environment("OS"). Then based on the Platform you need to call the
actions which you recorded on that particular platform.
Cross Browser Testing:
Using this code Eg. Browser("Core Values").GetROProperty("version") you can extract
the Browser and its correspondin version. Ex: Internet Explorer 6 or Netscape 5. Based
on this value you call the actions which are relevant to that browser.
For i=0 To 1
If i=0 Then
myBrowser = "IE"
myBrowserpath = "iexplore.exe"
ElseIf i=1 Then
myBrowser = "FF"
myBrowserpath = "firefox.exe"
Set App = CreateObject("QuickTest.Application")
App.Visible = True
App.Test.Settings.Launchers("Web").Act... = False
App.Test.Settings.Launchers("Web").Bro... = myBrowser
systemutil.Run myBrowserpath ,"http://studyautomation.com"
If Browser("Study Automation - A Community").Page("Study Automation - A
Community").Link("Home").Exist Then
Reporter.ReportEvent micPass,myBrowser &" Test","Passed"
Else
Reporter.ReportEvent micFail,myBrowser &" Test","Failed"
End If
Next
11) What is logical name of the object?
Logical name is a name given by QTP while creating an object in the repository to
uniquely identify it from other objects in the application. This name would be used by
the QTP to map the object name in script with its corresponding description in the
object repository. Ex: Browser("Browser").Page("Guru99") Here Guru99 is the logical
name of the object.
12) What is descriptive programming?
Typically ,an object and its properties must be recorded in the Object Repository to
enable QTP to perform action s on it.
Using descriptive programming , you do not store the object and its property values in
the Object repository but mention the property value pair directly in the script.
The idea behind descriptive programming is not bypass the object repository but help
recogonize dynamic objects.
13)What are the properties you would use for identifying a browser & page when using
descriptive programming ?
You can use the name property
ex: Browser("name:="xxx"").page("name:="xxxx"").....
OR
We can also use the property "micClass".
ex: Browser("micClass:=browser").page("micClass:=page")....
14)Can we record an application running on a remote machine using QTP ?
Yes .you can record remote application provided you are accessing application through
the local browser not via remoter like citrix.If you are still unable to record it is
advisable install QTP and application, on the same machine
15) Explain the keyword CreateObject with an example.
Creates and returns a reference to an Automation object
SYNTAX: CreateObject(servername.typename [, location])
Arguments
servername: Required. The name of the application providing the object.
typename : Required. The type or class of the object to create.
location : Optional. The name of the network server where the object is to be created.
Example : Set IE = CreateObject("InternetExplorer.Application")
16) Can you switch between Per-Action and Shared Object Repository ? If yes how ?
Yes .We can switch. Go to Test--->Settings--->Resources. Here you have an option to
choose repositories.
17) What is Object Spy ? How to Use it ?
Object Spy helps in determining the run & test time object properties & methods of the
application under test.You can access object spy directly from the toolbar or from the
Object Repository Dialog Box.It is very useful during Descriptive Programming
18) When ordinal identifiers alone can make an object unique then why they are not
given top priority? Why it is first mandatory and next assistive. Why we cannot go for
ordinal identifiers directly?
Consider the following -a) If two objects are overlapped on each other than location
based object recognition will fail.b) If only index based recognition is used your script
will work but script execution time will increase.Hence mandatory and assistive
properties are used.
19) What is the file extension of the code file in QTP?
Code file extension is script.mts
20) Explain in brief about the QTP Automation Object Model.
QTP Automation Object model deals with Automation of QTP itself. Almost all
configuration and functionality provided by QTP is represented by QTP's Automation
Object Model . Almost all dialog boxes in QTP have a corresponding automation object
which can set or retrieved using the corresponding properties or methods in the
Automation Object Model.QTP Automation Objects can be used along with standard VB
programming elements like iterative loops or conditional statements to help you design
a script of choice.
21) What is the use of Text output value in QTP?
Text Output values enable you to capture text appearing on the application under test
during run-time.
If parameterized, text output values will capture values appearing in each iteration
which would be stored in the run-time data table for further analysis.
22) What is Step Generator?
Step Generator enables use to Add Test Steps in your script. Using step generator you
can add steps to your script without actually recording it.
23) How to make QTP understand the difference amongst the same type of objects
.Suppose there are 5 check boxes in a page and I have to choose the 2nd one, how to do
that through script?
You can use ordinal identifiers like index along with a little descriptive programming for
object recognition.
24) What is Test Fusion Report ?.
Test Fusion Report , displays all aspects of a test run and is organized in a Tree format.
It gives details of each step executed for all iterations.
It also gives Run-time data table, Screen shots and movie of the test run if opted.
26) What are the types of environment variables in QTP ?
Environment variables in QTP are of three types:
1) Built-in (Read only)
2) User-defined Internal (Read only)
3) User-defined External (Read/Write)
You Set the Environment Variable using the following syntax
Environment.Value( "name") = "Guru99"
You can Retrieve the Environment Variable using following syntax
Environment.Value("name") -- This will retrun name as Guru99
Environment.Value("OS") -- This will return your system OS
27) What is the Difference between Bitmap Check point & Image Check point?
Bitmap checkpoint does a pixel to pixel comparison of an image or part of an image.
Image checkpoint does do a pixel to pixel comparison but instead compare image
properties like alt text , destination url etc.
28) What is the difference between functions and actions in QTP?
Actions have their own Object Repository & Data Table. Actions help make your Test
modular and increase reuse. Example: You can divide your script into Actions based on
functionality like Login, Logout etc.
Functions is a VB Script programming concept and do not have their own Object
Repository or Data Table. Functions help in re-use of your code. Ex: You can create a
Function in your script to concatenate two strings.
29) What is keyword view and Expert view in QTP?
Keyword View is an icon based view which shows test steps in tabular format. It also
automatically generates documentation for the test steps.
Expert View gives the corresponding VB Script statement for every test step in the
Keyword view.
30) Explain QTP Testing process? Quick Test testing process consists of 6 main phases:
1) Create your test plan - This is preparatory phase where you identify the exact test
steps, test data and expected results for you automated test. You also identify the
environment and system configurations required to create and run your QTP Tests.
2) Recording a session on your application - During this phase , you will execute test
steps one by one on your AUT ,and QTP will automatically record corresponding VB
script statements for each step performed.
3) Enhancing your test - In this stage you will insert checkpoints , output values ,
parameterization , programming logic like ifelse loops to enhance the logic of your test
script.
4) Replay & Debug - After enhancements you will replay the script to check whether its
working properly and debug if necessary.
5) Run your Tests - In this phase you will perform the actual execution of your Test
Script.
6) Analyzing the test results - Once test run is complete, you will analyze the results in
the Test Fusion report generated.
7) Reporting defects - Any incidents identified needs to be reported. If you are
usingQuality Center , defects can be automatically raised for failed tests in QTP.
31) What are the different types of Test Automation Frameworks ?
The types of Automation Frameworks are 1) Linear Scripting - Record & Playback
2) The Test Library Architecture Framework.
3)The Data-Driven Testing Framework.
4)The Keyword-Driven or Table-Driven Testing Framework.
32) How will you check a web application for broken links using QTP?
You can use the Page Checkpoint which gives a count of valid/invalid links on a page.
33) What is a Run-Time Data Table? Where can I find and view this table?
Data like parameterized output , checkpoint values , output values are stored in the
Run-time Table. It is an xls file which is stored in the Test Results Folder. It can also be
accessed in the Test Fusion Report.
34) What is the difference between check point and output value.
Check point is a verification point that compares a current value for a specified property
with the expected value for that property. Based on this comparison, it will generate a
PASS or FAIL status.
An output value is a value captured during the test run and can be stored in a specified
location like the Datable or even a variable. Unlike Checkpoints, no PASS/FAIL status is
generated.
35) How would you connect to database using vbscript ?
To connect to the database you must know
a) connection string of your server
b) username
c) password
d) DNS name
You can code the database connectivity command directly or you can use the SQLQuery
tool provided by QTP.
36) What is QTP batch testing tool?
You can use the Batch testing tool to run multiple scripts. Once the scripts are added in
the tool , it will automatically open the scripts and start executing them one after the
other.
37) What are the drawbacks of QTP?
As of QTP version 10
1) Huge Tests in QTP consume lots of memory and increase CPU utilization.
2) Since QTP stores results in HTML file (and not txt) the result folder sometimes
becomes big.
38) What is an Optional Step ?
A step when declared optional is not mandatory to be executed. If the corresponding
GUI object is present, QTP performs the operation on it. If the GUI object is not present,
QTP bypasses the optional step and proceeds to execute the next step.
39) What is Reporter.ReportEvent ?
Reporter.Reportvent is standard method provided by QTP to send custom messages to
the test results window.
Syntax
Reporter.ReportEvent EventStatus, ReportStepName, Details [, ImageFilePath]
where
EventStatus = 0 or micPass
1 or micFail
2 or micDone
3 or micWarning
Results can assume any status like Pass , Fail , Warning etc. You can also send
screenshot to the test results window.
40) How will you declare a variable in QTP ?
You declare using a DIM keyword. You assign value to the variable using the SET
keyword.
Ex.Dim temp 'Will declare the temp variable
Set temp = 20 ' Will assign a value 20 to temp.
41) What is GetRoProperty ?
GetRoProperty is a standard method provided by QTP to fetch property values of a run
-time object.
42) What is smart Identification?
Typically, if even one of the on-screen object property does not match the recorded
object property. The test fails.
In smart identification, QTP does not give an error if the property values do not match,
but uses Base filter and Optional Filter properties to uniquely identify an object. In
Smart identification, if a property value does not match the script does not fail but it
proceeds ahead to compare the next property. Smart identification can be enabled in
Object Identification Dialog box.
43) How would you export a Script from one PC to another in QTP ?
We can make use of the "Generate Script" function available in Object Identification,
Test Settings and Tools/Options tab to create a zip of the script at the source computer.
These zip files then can be imported into QTP at the destination computer.
44) Can launch two instances of QTP on the same machine ?
No. You can work with only single instance of QTP on the same machine. But QTP itself
can work on multiple instances of the Application Under Test (AUT). Ex: QTP can
handle multiple IE browser windows.
45) Give the syntax to import/export xls into QTP.
DataTable.ImportSheet "..\..\TestData\Input.xls",1,dtGlobalSheet
DataTable.ExportSheet "..\..\Results\Output.xls","Global"
47) What is the standard timing delay for web based application in QTP ?
The standard delay is 60 seconds. This is can be changed in Test Settigns.
48) What is the Action Conversion Tool ?
It is an in-built tool provided by QTP to convert Actions into Business Process
Components.
49) What is the extension for a function library ?
The extension is '.QFL'
50) If the Global Data sheet contains no data and the Local Datasheet contains two rows
of data, how many times will the test iterate?
The test will iterate only once - global iteration.
51) Explain how to read registry key in UFT ?
The example demonstrated here explains how to read registry key in UFT
Create a shell object
set MyShell= CreateObject (WScript.Shell)
Read the value of key from the registry
RegValue =MyShell.RegRead (varpathofkey)
in above function we have to pass the path of key in registery.
e.g. HKCU\software\ie\settings
msgbox RegValue
52) What are the ways in UFT to get system environment variables in UFT?
There are three ways to get system environment variables in UFT
Use the WSH shell object
Use WMIs Win32_Environment Class
Read variables from the registry
Set myShell = CreateObject (WScript.Shell)
WScript.Echo myShell.ExpandEnvironmentStrings( "%PATHEXT%" )
myShell=Nothing,
The output will be .BAT;.CMD;.VBS;. VBE;. JS;. JSE
Other user variable, like TEMP, overwrite their system counterpart
Set myShell = CreateObject( "WScript.Shell" )
WScript.Echo myShell.ExpandEnvironmentStrings( "TEMP=%TEMP%" )
myShell=Nothing
The output will be
TEMP:C:\DOCUME~1\You\LOCALS~1\Temp
53) Mention the steps required in UFT to send mail from outlook?
To send mail from outlook in UFT,
Set Outlook = CreateObject ("Outlook.Application")
Dim Message 'As Outlook.MailItem
Set Message = Outlook.CreateItem(olMailItem)
With Message
.Subject = Subject
.HTMLBody = TextBody
.Recipients.Add (aTo)
Const olOriginator = 0
.Send
End With
54) Explain how you can fetch data from database in UFT?
To fetch data from database in UFT, you have to follow the code below
Set db= createobject (ADODB.Connection)
db.Open Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=G:\guru99\vb6\admission_project.mdb;
Persist Security Info= False
Set rst=createobject(ADODB.Recordset)
rst.Open select*from Course, db, 3
id=rst. RecordCount
For i=0 to id-1
Print rst.field (0) & rst.fields (1) & rst.fields (2) & rst.fields (3)
rst.Movenext
Next
55) What are the codes we can use to get files from ftp server in UFT?
To get ftp files from ftp server, you have to use below code
a) put- To store single file on server
b) get- To download single file from ftp server
c)
mget- To download multiple files from server
d) mput- To store multiple files on server
e) delete- To delete files on ftp server
MyShell.Run "%comspec% /c FTP -n -s:" & commandstoworkwithftp & " " & Site, 0,True
56) In UFT how you can prevent the system from getting locked?
To prevent system getting locked, any of the two ways can be used
Create a simple vbs file having code to press numlock key and run that vbs file
Edit one registry key DisableLockWorkstation =1 to disable locking
57) What is descriptive programming in UFT means?
Descriptive programming includes property name and property value. Whenever UFT
is facing difficulty in identifying objects from object repository, and instead the object is
directly identified from the script is known as descriptive programming.
58) In UFT explain the difference between qfl and vbs files?
a) qfl is quick test function library file while vbs is Microsofts vbscript
b) qfl is a non-executable file while vbs is an executable file
c)
To use file in UFT associate qfl file from test setting, while to include vbs file use
execute file statement
59) What is the code to write data to text file in UFT?
To write data to text file in UFT code is
Content = Guru99 Rocks
Set Fo = createobject ("Scripting.FilesystemObject")
Set f = Fo.openTextFile ("c:\myFile.txt",8,true) ' open in write mode
f.Write (contents)
f.Close
Set f = nothing
60) How to write data to excel file in UFT?
Code to write data to excel file in UFT is
filepath = C:\Bugs\Reports.xlsx
Set objExcel = CreateObject(Excel.Application)
objExcel.Visible= True
Set Wb= objExcel.Workbooks.Open (filepath)
Wb.worksheets(1).Cells(1,1).Value = guru99 read value from Excel file
Drag the crosshair to another window, and it will be framed, and the main properties
are displayed in the main window. Once released, you get this menu:
Select the first option, and the browser is displayed (running in the address space of the
selected application):
You may right-click on a node to bring up a context menu. This allows you to refresh the
node (including children).
The top line in the window shows the "path" to the currently selected object,
e.g. Controls[0].Size.Width. You can also type this in and go directly to the
corresponding node. You can even call parameterless methods using this,
e.g. Controls[0].GetHashCode() or FindForm().Location.X. The Copy button copies the
"path" to the clipboard. The is intended as a help to ObjectSpyEvaluator, which is
explained later.
The Implementation
The solution contains three assemblies, which are described in detail in the following
paragraphs:
InjectLib - A C++ library that wraps the code injection as a generic
method, Injector.InvokeRemote
ObjectSpy - A C# executable that contains the main window
ObjectSpyLib - A C# library that contains the browser, which is injected into the spied
application
InjectLib (InvokeRemote)
A spinoff from this solution is a generic method with this signature (C# syntax):
Copy Code
object Injector.InvokeRemote(IntPtr hWnd, string assemblyFile,
string typeName, string methodName, object[] args)
This wraps the injection process in a generic way that can be used for other purposes.
The hWnd parameter identifies the window (and thus the process) in which your code
should be injected. The assemblyFile specifies the code that should be
injected, typeName specifies a class in this assembly, and methodName specifies a static
method on this class. The method is called with the supplied arguments, and may
optionally have a return value.
There are different methods to inject code into another process (see the CodeProject
article Three Ways to Inject Your Code into Another Process). This solution is based on
the same approach that most other tools use, Windows hooks (see Using Hooks for
details on Windows Hooks). The steps performed by InvokeRemote are:
Create a Windows message hook, using the Win32 API function SetWindowsHookEx
Serialize the parameters to shared memory
Send a custom message to the hook, to request its service
The hook (i.e., code injected in the target process) now:
Deserializes the parameters from shared memory
Loads the requested assembly
Invokes the requested method with the specified parameters
Serializes any return value to shared memory
Remove the hook
Deserialize the return value from shared memory and return it to the caller
SetWindowsHookEx requires the address of the hook function. This must be exported
from the library, which cannot be done from C#. Therefore, this library is made as a
mixed-mode C++ library, using Visual Studio 2005's C++/CLI support. I.e., the library
contains both native and managed code.
The memory shared between the two processes is simply a data segment created in the
library, i.e., it has a fixed size. For this library, it means that the serialized version of the
parameters to InvokeRemote must fit within 2000 bytes (obviously, they must also be
serializable). The same limitations apply to the return value. An alternative approach
could be memory mapped files (see this article on the MSDN Library).
The hook function caused a couple of interesting problems:
Problem #1: To make a nice wrapping of the serialization/deserialization, the
parameters to the message hook are wrapped in a serializable RequestMessage class,
declared in the InjectLib library itself. Despite this, the deserialization in step 4a above
failed, complaining that it was unable to find the InjectLib library - obviously ignoring
that it was running it in this exact moment! Searching the Internet indicated that this
situation may occur if the library is loaded using LoadFrom. Although it is Windows
itself that loads the library when it is injected, the suggested solution solved the
problem: subscribe to the eventAppDomain.CurrentDomain.AssemblyResolve. This
event occurs when the CLR cannot find an assembly, and lets you return the assembly
yourself.
Problem #2: When the message hook tries to load the assembly specified in
the InvokeRemote call (step 4b above), it cannot find it. This is solved by
using Assembly.LoadFrom instead of Assembly.Load. The message hook appends the
path of InjectLib, assuming that the requested assembly is located in the same place.
Otherwise, the requested assembly would have to be placed in the GAC or in the spied
application's folder. A solution similar to problem #1 could probably also be used.
ObjectSpy
ObjectSpy is the executable that contains the main window. It is written in C#, and
makes several Win32 API calls to find window handles and extract information etc. (for
declaring API calls in C#, pinvoke.net is very useful). The implementation of the
crosshair approach is highly inspired by the WinSpy demo project in Robert
Kuster'sarticle about three ways to inject code into another process. Apart from these
API calls, the code is very straightforward, and ends calling
InjectLib's InvokeRemote method:
Copy Code
Injector.InvokeRemote(hWnd, "ObjectSpyLib.dll",
"Bds.ObjectSpy.ObjectSpyForm", "ShowBrowser", new object[] { hWnd });
ObjectSpyLib
This C# library contains the browser form which is injected in the spied application. The
entry point is the static method specified by ObjectSpy's parameters to InvokeRemote:
Copy Code
public static void ShowBrowser(IntPtr hWnd)
This method creates an instance of the form and calls its Show method. The window
handle is "converted" into aControl, using Control.FromHandle. The control forms the
root of the object hierarchy. From there, the rest is exercising the reflection namespace.
Below each node in the tree that represents a non-null object, public and private fields,
and properties of that object are added the first time the node is expanded (indexers
excluded, since they require parameters). Furthermore, if an object
implements IEnumerable, the enumerated objects are added. Whenever a node is
selected in the tree, the corresponding object is used as the SelectedObject for
the PropertyGrid control in the right side of the window.
One thing worth noting is that generic type names are mangled. For example, the
typename returned from the reflection classes for the generic List class is "List`1". The
number after the backtick indicates the number of type parameters. ObjectSpyLib
unmangles this in a recursive manner, and presents it in C# syntax (i.e., using less-than
and greater-than characters).
ObjectSpyEvaluator
In addition to the browser form, ObjectSpyLib also includes the
class ObjectSpyEvaluator with this static method:
Copy Code
public static string Evaluate(IntPtr hWnd, string expression)
The expression parameter is identical to the object "path" that can be entered in the
browser. The result of the expression is returned. When performing automated GUI
testing, this makes it very easy to write validation code. The validation code might e.g.
make a call like this to check the Text property of the root node in a TreeView:
Copy Code
string result = (string)Injector.InvokeRemote(hWnd, "ObjectSpyLib.dll",
"Bds.ObjectSpy.ObjectSpyEvaluator", "Evaluate",
new object[] { hWnd, "treeView.Nodes[0].Text" });
A sample application using the Evaluate method - ObjectSpyEE - is included in the
downloads:
Future Enhancements
I hope this tool is useful as it is (at least it was fun making it!). However, there are
several improvements that I would like to do when I have time:
Include static members
Find and include "root objects" from the application, if possible (i.e., not just objects
referred to by the selected control)
Stop expansion when "simple types" (Int32 etc.) are encountered
Display private properties + public and private fields in PropertyGrid (by
implementingICustomTypeDescriptor)
Display additional type information about objects (FullName of declared
type, FullName (+Name?) of actual type), possibly in PropertyGrid
Allow changing the value of "simple types" (Int32 etc.), also when not public properties,
and thus in parent's PropertyGrid
Abort fetching enumerated objects if huge number of objects (when it takes too long)
Show information about from which base class a property or field is inherited, possibly
in PropertyGrid
Option to only show fields, not properties, by default (to avoid possible side effects from
calling a getaccessor)
History
2007-02-23 (ObjectSpy 1.2.0)
Added ObjectSpyEvaluator, ObjectSpyEE and related functionality in the browser form.
2006-12-05 (ObjectSpy 1.1.0)
Members are no longer sorted using SortedList (by key), but by Sort method on
ordinary List(and implementation of IComparable on ObjectInfo). This solves the
problem with handling obfuscated names (like in .NET Reflector). Due to culture issues,
keys for different members were considered equal. See Microsft Forums and MSDN for
details.
Tree in browser window no longer hides selection when there is no focus.
Refresh option added in the browser context menu.
ObjectInfo has been split up into base and derived classes.
Slightly modified icon for browser window (to distinguish it from main window).
1 Dim ArrName(ArrSize)
where
ArrName=Array Name
ArrSize =Array Size
While defining the dynamic array ,we dont need to declare the size of array.
1 Dim ArrName()
where
ArrName=Name of an array
Assigning value to static array in VBScript
The values that needs to be assigned to the array needs to be on the right hand side of
the line
1 ArrName(ArrIndex)=Value
where
ArrName=Nameofanarray
1 Redim ArrName(ArrSize)
where
ArrName=Nameofanarray
ArrSize =Size of the array
Now, lets take an example, where we have 5 elements (10,20,30,40,50).We need to
assign these variables to an array in VB Script.
First we need to declare a dynamic array in VbScript for the same.
1 Dim Arr()
Now we need to increase the size of this empty array which can be done using Redim
keyword
1 Redim Arr(5)
As we have increased the size of the array as per our requirement,we will now assign
the value to this array starting from the position zero(0)
1 Arr(0)="10"
2.
3.
4.
5 Arr(4)="50"
So the overall code which has been designed till now looks like
1 Dim Arr
2 Redim Arr(5)
3 Arr(0)="10"
4 Arr(1)="20"
5 Arr(2)="30"
6 Arr(3)="40"
7 Arr(4)="50"
Lets see the value in the msgbox of the above code till now
1 For i= 0 to 4
2 FirstArr=FirstArr+"Arr("+cstr(i)+") : "+(Arr(i))&vbnewline
3 next
4 msgbox FirstArr
The output will be as follows
1 Arr(0) : 10
2 Arr(1) : 20
3 Arr(2) : 30
4 Arr(3) : 40
5 Arr(4) : 50
Now if we want to add a new element say 60, so again we will redefine the size of array
to 6
1 ReDim Arr(5)
2 Arr(5)=60
Now if we check the output again of the array using the code
1 For i= 0 to 5
2 SecondArr=SecondArr+"Arr("+cstr(i)+") : "+(Arr(i))&vbnewline
3 next
4 msgbox SecondArr
The output will be as follows
1 Arr(0) :
2 Arr(1) :
3 Arr(2) :
4 Arr(3) :
5 Arr(4) :
6 Arr(5): 60
We see that when we have added an element to an array in Vbscript using Redim
keyword,it makes Arr as blank for index 0 to 4.
If we want to preserve the values of an array as it is ,we can achieve the same using
the Preservekeyword.
1 Dim Arr
2 Redim Arr(5)
3 Arr(0)="10"
4 Arr(1)="20"
5 Arr(2)="30"
6 Arr(3)="40"
7 Arr(4)="50"
8 Redim Preserve Arr(5)
9 For i= 0 to 5
10 SecondArr=SecondArr+"Arr("+cstr(i)+") : "+(Arr(i))&vbnewline
11 next
12 msgbox SecondArr
The output will be as follows
Arr(0) :10
Arr(1) :20
Arr(2) :30
Arr(3) :40
Arr(4) :50
Arr(5): 60
In this way we can assign the values to the dynamic array.
PS: While using array in Vbscript, we recommended the usage of dynamic array instead
of the static array as it helps to reduce the memory consumption during execution.
108) what is error handling in qtp?
Error handling is the way for responding to occurrence of some unexpected situation
that arrives during the computation. In automation testing, these unexpected situation
can be like objects of application getting changed or some mathematical manipulation
etc.
For handling such situation Visual Basic Script Edition (VBScript) provides us some of
the methods. The details and usage of these methods are as follows:
On error resume next
This statement specifies that when any run time error occurs at particular line in script
the control goes to the next line following the statement where the error as occurred.
For example: We are performing a division by zero, and if such situation occurs we dont
want script to be interrupted. So we will be adding On error resume next statement at
the top of the script.
On error resume next
Division=100/0
If Div=0 then
Msgbox Pass
Else
Msgbox Fail
End if
On error go to 0
Disables any enabled error handler and reset it to nothing
Err object
Err object is the intrinsic object with global scope means there is no need to create the
instance of it for accessing the various methods of it.The details of all the methods of
err object can be find in the below table:
Err Properties
Details
Number
Description
Source
HelpFile
HelpContext
Err Methos
Details
Clear
Raise
To disable recognition of virtual objects while recording select Tools > Options and click
General tab, and select the Disable recognition of virtual objects while
recording check box.
Object Spy cannot be used on virtual objects
Scroll bars and Labels cannot be treated as Virtual objects
QTP does not support virtual objects for analog or low level recording.
If you have used virtual objects and that too only after doing a record, and you are
wondering if we have descriptive programming for virtual objects as well!
The answer to these is Yes, we do have and we can easily do the same for Virtual
Objects. For those who are not aware of what Virtual Objects are, let us first understand
what it is and how it works. Virtual object feature in QTP enables us to create and run
tests on objects that are not normally recognized by QTP. These objects can be any
object that behave like standard objects but are not recognized by QTP. Virtual objects
helps a lot in such situations.
Recently, I encountered a similar situation where I had to click on a link which was
there in the email body (I will elaborate the whole scenario in a seperate post).
Although the link was behaving properly it was not getting recognized by QTP, actually
QTP was identifying the whole body section as an object. objective was to open the url
which was associated with the link and that was getting opened only after clicking the
link at the email body. I tried other means but no luck. So finally in this situation Virtual
Object was very helpful and it worked like a charm.
So, we can define such objects as virtual objects and map them to standard classes like
button, checkbox etc. QuickTest emulates the actions on virtual object during the run
session. A virtual object can be defined using the virtual Object Wizard(Tools>Virtual
Objects>New Virtual Object). The wizard prompts you to select the standard object
class to which you want to map the virtual object. You then mark the boundaries of the
virtual object using a cross-hair pointer. Next, you select a test object as the parent of
the virtual object. Finally, you specify a name and a collection for the virtual object. A
virtual object collection is a group of virtual objects that is stored in the Virtual Object
Manager under a descriptive name. Find more details on virtual objects step by step with
screenshots in my earlier post Virtual Objects When Nothing works.
The virtual objects that you create using the virtual object wizard, gets stored as VOT
file into <QuickTest installation folder>\ dat \ VoTemplate. That means, if you want to
use the script in which you have added the virtual object onto some other machine then
this VOT file also needs to be copied to the same location on the other machines
wherever you want the script to execute. This is main challenge for maintaining the
script and the execution on multiple machines or in other terms portability. To
overcome this issue, Descriptive programming is the best way. Basically a virtual object
stores and uses the properties x,y,width and height with it. so if by any means we are
able to maintain these properties and values then we are done. below is an example of
how we can do it
1 Browser("Google").Page("Google").VirtualButton("x:=667","y:=158","height:=21","wid
th:=75","name:=Saket").Click
This way we can run the script without having the virtual object collection or the VOT
files on the machine.We can do the same with using description object as well.
Set oVDesc=Description.Create
1
oVDesc("x").value=667
2
oVDesc("y").value=158
3
oVDesc("height").value=18
4
oVDesc("width").value=41
5
Browser("name:=Google").Page("title:=Google").VirtualButton(oVDesc).click
Descriptive programming for virtual objects can be done only for the classes which can be
created using the virtual object manager.
for virtual lists objects use one more property rows:=row number
for tables use rows:=row number and columns:=column number
110) What is Dictionary object ?
Most of the time; We use variables, when we need to store a input value or a value
retrieved from an outside source. When there are many such values, either we use
individual variables or we can store in an array. Alternatively, information can also
be stored in a Dictionary object. It is a part of VB Script and so it can be used with the
tools supporting VBS.
The Dictionary object is used to hold a set of data values in the form of (key, item) pairs.
A dictionary is sometimes called an associative array because it associates a key with an
item. The keys behave in a way similar to indices in an array, except that array indices
are numeric and keys are arbitrary strings. Each key in a single Dictionary object must
be unique.
A Dictionary object can contain any data including objects and other Dictionary objects.
The value of these dictionary items can be accessed by using unique keys that are stored
along with the data, rather than by using an items ordinal position as you do with an
array. This makes the Dictionary object ideal when you need to access data that is
associated with a unique named value.
Adding Keys and Items
Dictionary is a COM objects, it can be instantiated in the same way as
any other COM Object. TheProgID for a Dictionary object is Scripting.Dictionary, and so
the following example creates a Dictionary object using CreateObject:
1 Dim oDict
2 Set oDict = CreateObject("Scripting.Dictionary")
One you have created an instance of the Dictionary object, you can use
the Add method to add items to the dictionary. The Add method requires two
parameters, which must be supplied in the following order and separated by a comma.
for example
Key
Value
Book1
QTP Unplugged
Book2
QTP DP Unplugged
Book3
UFT & QTP Interview Unplugged
Dictionary keys must be unique. In the examples below, after the first line is interpreted,
the key Book1 will already be in the Dictionary.
1 oDict.item("Book2")
One potential problem in using the Dictionary object is that any attempt to reference
an element that is not contained in the Dictionary does not result in an error. Instead,
the non-existent element is added to the Dictionary. Consider the following script
sample, which creates a Dictionary, adds three key-item pairs to the Dictionary, and
then attempts to echo the value of a non-existent item, Book4:
1 Dim oItem
2 Dim sItem, sMsg
3 Dim oDict
4
5 Set oDict = CreateObject("Scripting.Dictionary")
6
7 Set oDict = CreateObject("Scripting.Dictionary")
8 oDict.Add "Book1", "QTP Unplugged"
9 oDict.Add "Book2", "QTP DP Unplugged"
10 oDict.Add "Book3", "UFT & QTP Interview Unplugged"
11
12 For Each oItem In oDict
13 sItem = oDict.Item(oItem )
14 sMsg = sMsg & sItem & vbCrLf
15 Next
16
17 MsgBox sMsg
Configuring Dictionary Properties
The Dictionary object has only one configurable property, Compare Mode, which plays
an important role in determining which keys can be added and which ones cannot.
By default, a Dictionary is created in binary mode, which means each key in the
Dictionary is based on its ASCII value. This is important because the ASCII value of an
uppercase letter is different from the ASCII value of that same lowercase letter. In
binary mode, both of these services can be added to the Dictionary as individual keys. So
we can have same keys for multiple Items when in binary mode. for example, book and
BOOK
When a Dictionary is configured in text mode, uppercase and lowercase letters are
treated identically.
To configure the Dictionary mode, create an instance of the Dictionary object and then
set the CompareMode property to one of the following values:
1 aBooks = oDict.Keys
2 aNames = oDict.Items
Enumerating a Dictionary
Items and Keys method returns the array of Items and keys respectively. These methods
cannot be directly used to access the values, there return array has to be first assigned
to a variable and then accessed. Below example illustrates the enumerations.
Start QTP, type Dictionary., it should show the methods and properties of dictionary
objects to use.
Sorting a Dictionary
Below function demonstrate, how we can sort a dictionary with items. [Source]
1 Const dictKey = 1
2 Const dictItem = 2
3
4 Function SortDictionary(objDict,intSort)
5 ' declare our variables
6 Dim strDict()
7 Dim objKey
8 Dim strKey,strItem
9 Dim X,Y,Z
1
0 ' get the dictionary count
1 Z = objDict.Count
1
1 ' we need more than one item to warrant sorting
2 If Z > 1 Then
1
' create an array to store dictionary information
3
ReDim strDict(Z,2)
1
X=0
4
' populate the string array
1
For Each objKey In objDict
5
strDict(X,dictKey) = CStr(objKey)
1
strDict(X,dictItem) = CStr(objDict(objKey))
6
X=X+1
1
Next
7
1
' perform a a shell sort of the string array
8
For X = 0 to (Z - 2)
1
For Y = X to (Z - 1)
9
If StrComp(strDict(X,intSort),strDict(Y,intSort),vbTextCompare) > 0 Then
2
strKey = strDict(X,dictKey)
0
strItem = strDict(X,dictItem)
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
strDict(X,dictKey) = strDict(Y,dictKey)
strDict(X,dictItem) = strDict(Y,dictItem)
strDict(Y,dictKey) = strKey
strDict(Y,dictItem) = strItem
End If
Next
Next
' erase the contents of the dictionary object
objDict.RemoveAll
' repopulate the dictionary with the sorted information
For X = 0 to (Z - 1)
objDict.Add strDict(X,dictKey), strDict(X,dictItem)
Next
End If
End Function
111) What are Object models in qtp ?
An Object Model is basically the way we use the object properties in a Programming
language or technology. When we say usage of object properties, it means accessing
the objects by object references to achieve the objectives like invoking a particular
method of object. For example, object model of MS Excel, which enables other
program to control it via different methods and properties.
A collection of objects or classes through which a program can examine and manipulate
some specific parts of its world. In otherwords, the object-oriented interface to
someservice or system. Such an interface is said to be the object model of the
represented service or system.
In this post we will discuss about the four different types of Object Models
Test Object Model ( TOM )
Document Object Model ( DOM )
Component Object Model ( COM )
Automation Object Model ( AOM )
Test Object Model ( TOM )
A collection of object types or classes which represents the different objects in the
application. For Example a button object or edit box object in an application are the
objects of and represent Button class or Edit box class. These test object class has a
several properties to uniquely identify the objects of the particular class and methods
to perform specific actions.
There are two types of objects in TOM,
Test Object and
Run-time object.
The objects which QuickTest creates and stores to represent the object in application,
is a test object whereas a run-time object is the actual object in the application on
which methods are performed during the run session, i.e the test object object
5
4
6
4
7
4
8
4
9
5
0
properties are the properties as they are saved in the test object repository. Run time
properties refers to the object properties as it appears in the application under test.
for example, a button with one of the properties enable
If you need to click on the Google Search button using DOM, you will have to look into
the source. For the button there are certain properties like id, name etc, you can find
in the source above. These properties can be used to identify the object and do the
action. If we take the Name property, this can be used byGetElementsbyName
byGetElementsbyName method
as below
Browser("Google").Page("Google").object.getElementsByName("btnK").Item(0).cli
ck
You can use GetElementsbyTagName to have all the button objects and then search
for the required one as below
1
1
2
3
4
5
6
7
8
9
1
0
ElementFromPoint Method returns the object at specific coordinate on the page. for
example the below code finds the search text box as per x and y coordinate and sets
the value.
x=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").GetROPro
perty("x")
1
y=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").GetROPro
2
perty("y")
3
Browser("name:=Google").Page("title:=Google").Object.elementFromPoint(x,y).Val
ue="Automated-360"
Some useful Properties which can be used for different purposes
activeElement Retrieves the object that has the focus when the parent document
has focus. Get the name of the text box which has the focus during runtime
1 Print Browser("Google").Page("Google").Object.activeElement.name
cookie Sets or retrieves the string value of a cookie. Find more details on Cookie
here
1 Print Browser("Google").Page("Google").Object.Cookie
documentElement - Retrieves the root node of the document.
1 Print Browser("Google").Page("Google").Object.documentElement.innerHTML
readyState - Retrieves a value that indicates the current state of the object. This
property can be used for sync in QTP scripts.
1 Browser("Google").Page("Google").Object.readyState
range of programming languages. COM is the basis for several other Microsoft
technologies and frameworks, including OLE, OLE Automation, ActiveX, COM+, DCOM,
the Windows shell, DirectX, and Windows Runtime.
COM is basically used by developers to make the things simpler and easier to build
and link by creating reusable components. The objects can be accessed by the
interface (properties and methods) provided by COM for a particular class. Basically
the properties and methods of an object can be the interface of the object and
accessed by taking the reference of the object.
COM objects can be used with any tool that supports COM automation. And
since VBScript supports COM automation, It becomes very easy to use in QTP
scripting. But we cannot use all the COM objects, we can use only those objects that
expose a string called a programmatic identifier (ProgID). Although not all COM
objects have a ProgID, all COM objects have a 128-bit number called a class
identifier, or CLSID. If a COM object has a ProgID, you can use VBScript to instantiate
the object, invoke its methods and properties, and destroy the object.
To use a COM object in a script, you must first create an instance of the object. You
can do this by calling the CreateObject or GetObject method.
1 Dim UFTApp
2
3 Set UFTApp= CreateObject("QuickTest.Application") ' Create the application object
4
5 UFTApp.Launch 'Start QuickTest
6
7 UFTApp.Visible = True ' Make it visible
112) How To generate Random strings in QTP/UFT?
'************************************
'Logic Explanation:
'************************************
' RandomNumber ststement only gives specific random numbers between given
range
' 97-122 are the ASCII codes for a-z alphabets.
' Chr(97) will return 'a', Similarly Chr function return chacters based on ASCII codes
' In below function the random numbers will be generated between 97-122
' Using Chr function the generated numbers will be converted in to characters
' The generated characters will store in "gChr" variable
' Finally gChr value will be returned as Function Value
'************************************
Function GenerateRandomString(StrLength)
' Declare Variables
Dim StrLenIndex
Dim chrAscCode
Dim gChr
'Use for loop to generate StrLength many characters
End Function
'***************************************************
'Method 2
'***************************************************
'Logic Explanation
'Desktop is a built in object
'ChildObjects is a method to get child objects based on description provided in
description object
'When we give "Micclass" as browser in description object, all browsers in desktop
will be returned
'We for loop from "0" to Count-1 because the Object Indexing starts from "0"
'We will close each and every browser with for loop and index
Function CloseAllBrowsers()
'Declare Variables
Dim oBrDes
Dim oBrObjList
Dim objIndex
'Create Description Object with Browser class
Set oBrDes=Description.Create
oBrDes.Add "micclass","Browser"
'Get Browser Objects from Desktop
Set oBrObjList=Desktop.ChildObjects(oBrDes)
'Use For Loop to close each browser
'Use Count-1 because Object Indexing starts from "0"
For objIndex=0 to oBrObjList.count-1
'Close the Browser
oBrObjList(objIndex).close
Next
'Release Variables
Set oBrObjList=Nothing
Set oBrDes=Nothing
End Function
'##################################
'Close All browsers except Alm/Qc
'##################################
'Logic Explanation
'Desktop is a built in object
'ChildObjects is a method to get child objects based on description provided in
description object
'When we give "Micclass" as browser in description object, all browsers in desktop
will be returned
'We will check the the title before closing every browser with for loop and index
'We for loop from "0" to Count-1 because the Object Indexing starts from "0"
'If title is "Quality Center" or "ALM" we will not close it
Function CloseAllBrowsersExceptQC()
'Declare Variables
Dim oBrDes
Dim oBrObjList
Dim objIndex
'Create Description Object with Browser class
Set oBrDes=Description.Create
oBrDes.Add "micclass","Browser"
'Get Browser Objects from Desktop
Set oBrObjList=Desktop.ChildObjects(oBrDes)
'Use For Loop to close each browser
'Use Count-1 because Object Indexing starts from "0"
For objIndex=0 to oBrObjList.count-1
'Verify the name of the browser is "Quality Center" or "ALM"
If lcase(oBrObjList(objIndex).GetROproperty("name"))<>"mercury quality center"
then
'Close the Browser
oBrObjList(objIndex).close
Exit For
End If
Next
'Release Variables
Set oBrObjList=Nothing
Set oBrDes=Nothing
End Function
'##################################
'Close All browsers except last opened browser
'##################################
'Logic Explanation
'Desktop is a built in object
'ChildObjects is a method to get child objects based on description provided in
description object
'When we give "Micclass" as browser in description object, all browsers in desktop
will be returned
'We for loop from "1" to Count-1 because the in this script we will not work with
object indexing
'We will get the count of number of browsers and write a FOR loop with Count-1
times
'because we should close all browsers except one
'Each time we have to verify "0" creationtime browser exist and if exist close it
'We will repeat this Count-1 times
'The For Loop gets exit when the last browser creationtime becomes "0"
Function CloseAllBrowsersExceptLastBrowser()
'Declare Variables
Dim oBrDes
Dim oBrObjList
Dim iCounter
'Create Description Object with Browser class
Set oBrDes=Description.Create
oBrDes.Add "micclass","Browser"
'Get Browser Objects from Desktop
Set oBrObjList=Desktop.ChildObjects(oBrDes)
'Use For Loop to close each browser
'Use Count-1 because we should close all browsers except one
For iCounter=1 to oBrObjList.count-1
'Close the first browser each time by checking creationtime "0"
If Browser("creationtime:=0").Exist Then
'Close Browser
oBrObjList("creationtime:=0").close
End If
Next
'Release Variables
Set oBrObjList=Nothing
Set oBrDes=Nothing
End Function
'##################################
'Close All browsers except First opened browser
'##################################
'Logic Explanation
'Desktop is a built in object
'ChildObjects is a method to get child objects based on description provided in
description object
'When we give "Micclass" as browser in description object, all browsers in desktop
will be returned
'We for loop from "1" to Count-1 because the in this script we will not work with
object indexing
'We will get the count of number of browsers and write a FOR loop with Count-1
times
'because we should close all browsers except one
'Each time we have to verify "1" creationtime browser exist and if exist close it
'We will repeat this Count-1 times
'The For Loop gets exit when there no extra browsers
Function CloseAllBrowsersExceptLastBrowser()
'Declare Variables
Dim oBrDes
Dim oBrObjList
Dim iCounter
'Create Description Object with Browser class
Set oBrDes=Description.Create
oBrDes.Add "micclass","Browser"
' Get Browser Objects from Desktop
Set oBrObjList=Desktop.ChildObjects(oBrDes)
'Use For Loop to close each browser
'Use Count-1 because we should close all browsers except one
For iCounter=1 to oBrObjList.count-1
'Close the second browser each time by checking creationtime "1"
If Browser("creationtime:=1").Exist Then
'Close Browser
oBrObjList("creationtime:=1").close
End If
Next
'Release Variables
Set oBrObjList=Nothing
Set oBrDes=Nothing
End Function
114) Prepare QTP/UFT for Test Batch Execution Using AOM?
'***************************************************
'***************************************************
'Author - QtpSudhakar.com
'Purpose - To Run a Test Batch for all tests in side of a folder
' - This will create a CSV file which will have all the status of execution
'How to Use - Specify the Folder Path of where tests are stored
' - Make sure you don't have any other empty folders without QTP test
' - Give TestPath, Save the code into VBS file and Double click on vbs file
'***************************************************
'For any doubts contact https://www.facebook.com/Qtpsudhakarblog
'***************************************************
'***************************************************
'Declare Variables
Dim TestsFolderPath 'To specify Tests folder path
Dim QtApp 'To store Qtp Automation Object
Dim fso 'To access file system
Dim fld 'To store the test folder object
Dim tFlName 'Unique File name to store Test Results
Dim fl 'To store Result File Object
Dim fldLst 'To store Child Folders(tests) of base folder
Dim f 'To store each QTP Test Folder
object identifiers can lead to a more reliable and accurate object identification, and a
quicker object identification process.
Web Object Identifier Types
The following Web object identifiers are available:
CSS
CSS (Cascading Style Sheet) is a language used to define formatting of elements in HTML
pages. You can define a CSS identification property value for a test object to help
identify a Web object in your application based on its CSS definition.
QuickTest uses CSS identifiers only when identifying objects and not when learning
objects. Therefore, they are not available from the Object Spy or the Object
Identification dialog box.
User-defined XPath
XPath (XML Path) is a language used to define the structure of elements in XML
documents. You can define an XPath identification property to help identify a Web
object in your application based on its location in the hierarchy of elements in the
Web page. Because of the flexible nature of the language, you can define the XPath
according to the unique way your Web page is structured.
QuickTest uses XPath identifiers only when identifying objects and not when learning
objects. Therefore, they are not available from the Object Spy or the Object
Identification dialog box.
Automatic XPath
You can instruct QuickTest to automatically generate and store an XPath value when
learning Web test objects. During the run session, if the automatically learned XPath for
a particular object results in multiple matches or no matches, the learned XPath is
ignored. Additionally, if you have added a user-defined XPath or CSS identification
property to a test object description, then the automatically learned XPath is ignored.
Automatic XPath is a QuickTest-generated property, and therefore it is not available
from the Object Spy, the Add/Remove Properties dialog box, or the Object Identification
dialog box.
Attribute/* Notation
You can use the attribute/* notation to access custom native properties of Web-based
objects or events associated with Web-based objects.
How to Use Web Object Identifiers - Exercise
In this exercise, you use XPath and CSS identifiers in a test object description to help
locate the correct button in an HTML table.
1.
Prerequisites
a.
Open QuickTest and create a new test.
b. Disable Smart Identification for the Button test object class by selecting Tools >
Object Identification, selecting the Web environment in the Object Identification dialog
box, and then selecting the Button test object class from the Test Object classes list.
<html>
<head>
<style type="text/css">
body { background: green; color: blue; }
.SelectedRow { color: #22444; background: #ebcbeb; width: 450px; }
.RegularRow { color: #444; background: #cbebeb; width: 450px; }
.BPTRow { color: #D9660E; background: #cbebeb; width: 450px; }
</style>
</head>
<body>
<br><br>
<table onclick="javascript:change();" id="maintab">
<tr class="BPTRow" id=BPT>
<td> HP Business Process Testing </td>
<td> <input type="button" value="Buy"> </td>
</tr>
<tr class="RegularRow" id=QC>
<td> HP Quality Center </td>
<td> <input type="button" value="Buy"> </td>
</tr>
<tr class="SelectedRow" id=QTP>
<td > HP QuickTest Professional </td>
<td> <input type="button" value="Buy"> </td>
</tr>
</table>
</body
</html>
c.
Disable automatic XPath by selecting Tools > Options > Web > Advanced, and then
making sure that the Learn and run using automatic XPath identifiers checkbox is not
selected.
2.
Create a sample Web application
a.
Copy the following syntax content into a text document, and save the document
with an .html extension. The document is saved as an HTML page.
b. Review the appearance and content of your newly created HTML page in any
browser. Make sure that it matches the following image.
3.
Learn the button objects in the Web application
a.
In QuickTest, open the Object Repository Manager, and select Object > Navigate
and Learn. QuickTest is hidden, and the cursor changes to a pointing hand.
b. To verify that QuickTest learned the objects correctly, in the object repository,
select each Button object and select View > Highlight in Application. QuickTest
highlights each button object in the HTML page.
c.
Rename the Button objects to make them more clear:
Rename Buy to Buy_BPT.
Rename Buy_2 to Buy_QC.
Rename Buy_3 to Buy_QTP.
4.
Remove the ordinal identifiers from the button objects
Because all of the Button objects have identical property values, when QuickTest
learned the objects it assigned an ordinal identifier to each test object based on the
location of each object in the application. This may cause QuickTest to identify the
objects incorrectly if the sorting order of the buttons in the application changes.
a.
Select the first button object to display its object properties on the right side of the
object repository window.
b. In the Ordinal Identifier section, select the Browse button. The Ordinal Identifier
dialog box opens.
c.
In the Identifier type drop-down list, select None and close the dialog box. The
ordinal identifier is removed from the test object's identification properties.
d. Repeat steps a - c above for each of the buttons.
e. Verify that the test object descriptions are no longer unique by selecting each test
object and selecting View > Highlight in Application. QuickTest cannot identify the
objects.
5.
Add a CSS identifier based on the object's parent-container
a.
Select the Buy_BPT button. The test object details are displayed on the right side of
the object repository window.
b. In the Object Description section, click the Add button, and add the css property to
the test object description.
c.
Copy and paste the following syntax into the Value edit box:
tr.BPTRow input
6.
Add an XPath identifier based on the object's parent-container
a.
Select the Buy_QTP button. The test object details are displayed on the right side of
the object repository window.
b. In the Object Description section, click the Add button, and add the xpath property
to the test object description.
c.
Copy and paste the following syntax into the Value edit box:
//TR[@id='QTP']/*/INPUT
7.
a.
Select the Buy_QC button. The test object details are displayed on the right side of
the object repository window.
b. In the Object Description section, click the Add button, and add the xpath property
to the test object description.
c.
Copy and paste the following syntax into the Value edit box:
//td[contains(concat(' ',text(),' '),'Quality')]/../*/INPUT
8.
Results
Select each object and select View > Highlight in Application. QuickTest can now identify
each button based on the Web object identifiers you added.
Considerations for Working with Web Object Identifiers
General:
Defining xpath and css properties using Frame HTML tags is not supported. This may
cause incorrect identification when identifying Frame objects or
retrieving Frame objects using the ChildObjects method.
xpath and css properties are not supported for .NET Web Forms test objects or for other
Web-based test objects that have .NET Web Forms parent test objects.
When running in Maintenance Mode, QuickTest may replace test objects with XPath or
CSS identifier property values with new objects from your application.
Workaround: Use the Update from Application option in the Object Repository Manager
to update specific test objects with XPath or CSS identifier property values.
Differences Between User-defined XPath and Automatic XPath Behavior During Run
Sessions
Behavior in case of...
User-defined XPath
Automatic XPath
Multiple objects
match the XPath
value
You can use the attribute/* notation to access custom native properties of Web-based
objects or events associated with Web-based objects. You can then use these properties
or events to identify such objects by adding the notation to the object's description
properties using the Object Identification dialog box, or by using programmatic
descriptions.
Example of using attribute/<property> to identify a Web object
Suppose a Web page has the same company logo image in two places on the page:
<IMG src="logo.gif" LogoID="122">
<IMG src="logo.gif" LogoID="123">
You could identify the image that you want to click by adding the attribute/LogoID notation
to the object's description properties and using a programmatic description to identify the object:
Browser("Mercury Tours").Page("Find Flights")
.Image("src:=logo.gif","attribute/LogoID:=123").Click
(68, 12)
Example of using attribute/<event> to identify a Web object
Suppose a Web page has an object with an onclick event attached to it:
`'alert('OnClick event for edit.');"
You can identify the object by adding the attribute/onclick notation
to the object's description properties and using a programmatic description
to identify the object:
Browser("Simple controls").Page("Simple controls")
.WebEdit("attribute/onclick:= alert\('OnClick event for edit\.'\);").Set "EditText"
114) Using Xpath in qtp?
X- Path Introduction
QTP uses many ways to find an object. X-Path is one of that. In any XML or HTML
document there is a concept called tagging. If you want to create HTML document you
need to go by tags.
For example to create a HTML document you will first create <html> <body> </body>
</html> Tags.
This is the standard for HTML. Like this we have to use TAGS to create any object.
Following to that automatically for every object a hierarchy will be created. This
hierarchy is nothing but XPath.
The x-path for body is /html/body
Example
<html> <body> <table> </table> <table> </table> </body> </html>
In the above code the x-path for the first table is /html/body/Table[1]
XPath (XML Path) is a language used to define the structure of elements in XML
documents. You can define an XPath identification property to help identify a Web object
in your application based on its location in the hierarchy of elements in the Web page.
Because of the flexible nature of the language, you can define the XPath according to the
unique way your Web page is structured.
<html><body>
<table id="maintab" border=1>
<tr id=BPT>
<td>HP Business Process Testing</td>
<td> <input type="button" value="Buy"> </td>
</tr>
<tr id=QC>
<td>HP Quality Center</td>
<td><input type="button" value="Buy"></td>
</tr>
<tr id=QTP>
<td >HP QuickTest Professional</td>
<td> <input type="button" value="Buy"> </td>
</tr>
</table></body></html>
The view of above html code is like below
To find the objects of above html we can use complete hierarchy of objects. We can even
simplify the XPaths using X Path Syntax.
XPath Syntax
Expression Description
/
//
Selects nodes in the document from the current node that match
the selection no matter where they are
@*
Selects attributes
Below table displays path expressions and the result of expressions based on above
html document:
Path Expression
Result
/html
//table
//TR[@id='QTP']
//TR[@id='QTP']/*/INPUT Select input tag in the QTP table row and skips elements
between input and table row
//Table | //TR
h1
{
color:orange;
text-align:Left;
}
/* Define CSS Classes */
.MyObject1 { color: #22444; background: #ebcbeb; width: 200px; }
.MyObject2 { color: #22444; background: lightblue; width: 200px; }
</style>
</head>
<body>
<h1>CSS in QTP</h1>
<!-- Specify defined CSS class for object -->
<input type=button class="MyObject1" value="QtpSudhakar">
<input type=button class="MyObject2" value="QtpSudhakar">
</input>
<h1>Sudhakar Kakunuri</h1>
</body>
</html>
In the above html document I have defined a style for h1 tag. Because of that where
ever I have used h1 tags automatically the specified style will be applied there.
I have also created a CSS style classes MyObject1 and MyObject2. I can specify the CSS
style class for any object using class=MyObject1 or class=MyObject2.
Like this we can specify styles to automatically give a specific formatting for Html tags
or we can specify class names for selected objects.
The output of above code is like below
6)
Remove Ordinal Identifier Index for both the buttons in Object Repository
There will be two QtpSudhakar buttons created because there are duplicate buttons with
the name of QtpSudhakar. We differentiate these buttons based index. But index is not
reliable if more objects are added. But we can use CSS property to differentiate both the
objects. Continue to below steps
7)
8)
9)
sum in an external file or maybe display in a message box. Lets see how you can do this
in QTP.
Method Overriding in QTP
You can use QTPs RegisterUserFunc statement to achieve method overriding in your
scripts. Consider a scenario where you want to click on a web button in your
application. Now you can override the default Click method with a function that first
checks whether the web button exists or not. If it exists, then it checks that the button
should be enabled. After both these validations are done, comes your code to click on
the button. Lets see the sample code for this scenario 1
'===== Code in Function Library =====
2
RegisterUserFunc "WebButton", "fnBtnClick", "fnBtnClick"
3
4
'Function Definition
5
Function fnBtnClick(objControl)
6
7
'<nobr><a id="PXLINK_5_0_4" class="pxInta" href="#">Check</a></nobr> if object exists
8
If objControl.Exist Then
9
'Check if the object is enabled or not
10
If objControl.GetROProperty("disabled") <> 0 Then
11
'Click on the button
12
objControl.Click
13
End If
14
End If
15
16
End Function
17
18
'===== Sample code in your action =====
19
Browser("Browser").<nobr><a id="PXLINK_2_0_1" class="pxInta" href="#">Page</a></nobr>("Page"
From the above code, you would see that we have created a function fnBtnClick which
overrides the default click operation. This function clicks on the button only when you it
exists in the application as well as it is enabled.
Method Reuse in QTP
This is another cool feature that you can actually implement using RegisterUserFunc
statement. This concept is slightly different from the normal function reuse where you
create a function for a reusable scenario and then call this function wherever required.
With RegisterUserFunc, you create a generic function and then bind this function with
different controls. For example, you can create a generic fnClick function and then bind
the function with a web button, link, image, web element etc. This way you can use the
same function for different controls.
1
'===== Code in Function Library =====
2
RegisterUserFunc "WebButton", "fnClick", "fnClick"
3
RegisterUserFunc "Link", "fnClick", "fnClick"
4
RegisterUserFunc "Image", "fnClick", "fnClick"
5
6
'Function Definition
7
Function fnClick(objControl)
8
objControl.Click
9
End Function
10
11
'=====Code in Action =====
12
Browser("Browser").Page("Page").WebButton("btn1").fnClick
13
Browser("Browser").Page("Page").Link("lnk1").fnClick
14
Browser("Browser").Page("Page").Image("img1").fnClick
In the above example, we have created a single function fnClick which is being used by
different controls like Web Button, Link, Image etc.
It would be better to read function libraries (if you dont know what these are) before
going down further.
What do you mean by Registering a Function?
You can register a public function to a test object to enable the function
(operation) to be performed on a test object.
What are the ways to register a function in QTP?
Register a function through Function Definition Generator.
Register a function manually.
How to register a function manually? Give examples.
You can manually register your function to a test object by adding a
RegisterUserFunc statement after your function as shown in the following
example:
RegisterUserFunc "WebEdit", "MySet", "MySetFunc"
In this example, the MySet method (operation) is added to the WebEdit test
object using the MySetFunc userdefined
function. If you or the Subject Matter
Expert choose the WebEdit test object from the Item list in the Keyword View, the
MySet operation will then be displayed in the Operation list (together with other
registered and out of the box operations for the WebEdit test object), or if in the
Expert View, you press dot (period) after webedit object, you will get MySet in the
IntelliSense dropdown
list.
RegisterUserFunc: Enables you to add new methods to test objects or change
the behavior of an existing test object method during a run session. When you use
this statement, QuickTest uses your userdefined
function as a method of a
specified test object class for the remainder of a run session, or until you
unregister the method.
Another RegisterUserFunc example with little bit more detail
This may not be useful in real word scenario, but it is just a simple example to
give you a feel of RegisterUserFunc.
See the below screenshot. It shows all the operations which you can apply on a Page
object (also known as IntelliSense). Just write the below line in QTP and press dot
(period).
If you write some function and register it to any test object as shown below, it shows up
with all the default operations in IntelliSense popup. Just write the below code in QTP
and press dot (period). You dont have to Run anything. Here the my_multiply method
(operation) is added to the Page test object using the multiply userdefined function.
[see the below screenshot my_multiply is shown
in IntelliSense popup]
And manually to define a function as the default function, you define the value of
the fourth argument of the RegisterUserFunc statement as True. For example:
RegisterUserFunc "WebEdit", "MySet", "MySetFunc", True
3. A registered or global function can only be called from a test or component after
it is added to the test script or a function library that is associated with the test or
the component's application area.
4. QuickTest clears all function registrations at the beginning of each run session.
5. When you register a function, it applies to an entire test object class. You CANNOT
register a method for a specific test object.
6. If you want to call a function from additional test objects, you can copy the
RegisterUserFunc line, paste it immediately after another function and replace any
relevant argument values.
7. If the function you are registering is defined in a function library, it is
recommended to include the RegisterUserFunc statement in the function library as
well so that the method will be immediately available for use in any test using that
function library.
8. You can reregister the same method to use different userdefined functions without
first unregistering the method. However, when you do unregister the method, it resets
to its original QuickTest functionality (or is cleared completely if it
was a new method), and not to the previous registration.
9. If you register a method within a reusable action, it is strongly recommended to
unregister the method at the end of the action (and then reregister it at the beginning of
the next action if necessary), so that tests calling your action will not
be affected by the method registration.
How to unregister a function?
To unregister a function simply use UnRegisterUserFunc:
To unregister my_multiply function from our above example use:
unRegisterUserFunc "Page", "my_multiply"
UnregisterUserFunc: Instructs QTP to stop using the current registration of the method.
If the unregistered method is a defined QTP method for the object, the functionality of
the method returns to the standard QTP functionality.
121) Ways To associate Function Library in QTP?
4 Different Ways to Associate Function Libraries to your QTP Scripts
Most of the times, when you are creating test scripts or are designing a new QTP
Framework, you would be trying to come up with reusable functions which you would
have to store in the function library. Now, in order to use this function library with
multiple test cases, you need to associate this function library with your scripts. This
article explains the 4 methods that will help you in associating the function libraries in
QTP Test Cases.
Based on the type of framework you are using, you can use any of the following
methods to associate function libraries to your QTP Script 1) By using File > Settings > Resources > Associate Function Libraryoption in QTP.
2) By using Automation Object Model (AOM).
3) By using ExecuteFile method.
4) using LoadFunctionLibrary method.
Lets see in detail how each of these methods can be used to map function libraries to
your test scripts.
1. Using File > Settings > Resources > Associate Function Library option from the Menu
bar
This is the most common method used to associate a function library to a test case. To
use this method, select File > Settings option from the Menu bar. This will display the
Test Settings window. Click on Resources from the left hand side pane. From the right
hand side pane, click on the + button and select the function library that needs to be
associated with the test case.
Associate function Library to QTP
2. Using AOM (Automation Object Model)
QTP AOM is a mechanism using which you can control various QTP operations from
outside QTP. Using QTP Automation Object Model, you can write a code which would
open a QTP test and associate a function library to that test.
Example: Using the below code, you can open QTP, then open any test case and
associate a required function library to that test case. To do so, copy paste the below
code in a notepad and save it with a .vbs extension.
1
'Open QTP
2
Set objQTP = CreateObject("QuickTest.Application")
3
objQTP.Launch
4
objQTP.Visible = True
5
6
7
8
9
10
11
12
13
1
2
3
4
5
6
7
8
46
47
Erase arrChars
End If
End Function
Here is one more nice way to do this using array again.
Action parameters enable us to pass values from other actions in your test.
To use a value within a specific action, the value must be passed down through the
action hierarchy of the test to the required action.
We can then use that parameter value to parameterize a step in the test.
For example, suppose that we want to parameterize a step in Action3 using a value i.e
passed into the test from the external application that runs (calls) the test.
We can pass the value from the test level to Action1 (a top level action) to Action3 (a
nested action of Action1), and then parameterize the required step using this action
input parameter value (that was passed through from the external application).
Alternatively, we can pass an output action parameter value from an action step to a
later sibling action at the same hierarchical level.
For example,suppose that Action2, Action3, and Action4 are sibling actions at the same
hierarchical level, and that these are all nested actions of Action1.
We can parameterize a call to Action4 based on an output value retrieved from Action2
or Action3.
We can then use these parameters in the action step.
128) What are the challenges you have faced in automating test cases? and the
resolution?
as a automation test engineer,most of the times we get object
recognition problem. In our applications some pages having
dynamic objects(we can handling using DP). Some pages having
Custom objects (we can change custom to standard using virtual
objecct concept). 1. What to test and what not to test
2. Object recognition
3. Dynamic objects
4. System is not stable
5. Communication
these are the challenges I faced while doing automation testing
Keeping Automation Test Cases Up-To-Date With more and more development cycles adopting an Agile approach the automation
suite has to always have as up-to-date test cases as possible. Unfortunately for those
who think automation means that you can set and forget your software testing Im sorry
to inform you but there always be some amount of maintenance needed on your
automation scripts. The simple fact that any change to the DOM elements can halt an
automation script in its tracks means your testers need to have an intimate
understanding of how the scripts are interacting with the application under test so they
can quickly identify issues, correct them, and re-validate the test. It is always a good
practice to create detailed documentation for all test cases in the automation suite to
help facilitate the debugging process.
What is the toughest QTP challenge that you have faced?
Will: My toughest QTP challenge is the same challenge we all face continually. How do
we create maintainable tests that produce meaningful and reliable results from one
software release to the next? Like most people here, my first QTP test was a recordand-playback script that errored out the second time it ran. That started the challenge
to create better tests. Ive made pretty good progress on this challenge, but there is still
a lot left to do.
and how the changes manifest themselves in the control's state. You access the .NET
Windows Forms Spy by choosing Tools > .NET Windows Forms Spy in the main
QuickTest window.Chapter 1 Introducing QuickTest Professional .NET Add-in
Extensibility 19 Note: To spy on a .NET Windows Forms application, make sure that the
application is running with Full Trust. If the application is not defined to run with Full
Trust, you cannot spy on the .NET applications Windows Forms controls with the .NET
Windows Forms Spy. For information on defining trust levels for .NET applications,
refer to Microsoft documentation. For more information on the .NET Windows Forms
Spy, see the HP QuickTest Professional Add-ins Guide.
133)How to test XMLs in QTP?
XML is a markup language designed for how to store data that is in the form that both
human and machine readable format. Using XML, data can also be easily exchanged
between computer and database systems.
Sample XML and their key elements
Comparing XML
We can compare Two given xml's.
Dim xmlDoc1
Dim xmlDoc2
' Load the XML Files
Set xmlDoc1 = XMLUtil.CreateXMLFromFile ("C:\File1.xml")
Set xmlDoc2 = XMLUtil.CreateXMLFromFile ("C:\File2.xml")
'Use the compare method of the XML to check if they are equivalent
Comp = xmlDoc1.Compare (xmlDoc1, xmlDoc2)
'Returns 1 if the two files are the same
If Comp = 1 Then
Msgbox "XML Files are the Same"
Else
Msgbox "XML Files are Different"
136) What is COM interface? Does QTP has COM interface? have you used it?
COM interface appears in the scenario of front end and back end. for eg: if you r using
oracle as back end and front end as VB or any language then for better compatibility we
will go for an interface of which COM will be one among those interfaces. Create object
creates handle to the instance of the specified object so that we program can use the
methods on the specified object. It is used for implementing Automation
137) In how many ways you can call an action? which one you will prefer?
RunAction ActionName, [IterationMode , IterationRange , Parameters]
Here the actions becomes reusable on making this call to any Action.
IterationRange String Not always required. Indicates the rows for which action
iterations will be performed. Valid only when the IterationMode is rngIterations. Enter
the row range (i.e. "1-7"), or enter rngAll to run iterations on all rows.
If the action called by the RunAction statement includes an ExitAction statement, the
RunAction statement can return the value of the ExitAction's RetVal argument.
Using "Call to Existing Action" we can call one action from another action.
Go to Insert ->select Call to Existing Action
Select which action wants to call.
139) How to run multiple instances of application how to differentiate the instances?
We are aware of that multiple instances of QTP can't be running on a single machine.
But by using QTP we can work with multiple instances of the Application Under Test.
For example, QTP can handle multiple browsers or multiple applications at a time.
We can work with 2 applications at a time even without stopping the recording. We
should make sure that we configured both Record and Run on any opened
applications(Both Windows and Web) under Automation>Record And Run Settings>
Select the radio button "Record and Run on any application for both Windows and
Web".
We have to keep it in our mind that we can't run multiple instances of QTP on a single
machine.But we can handle multiple browsers or applications by using single QTP
instance.
within loop
use Systemutil.run "Apppath"
or use Invokeapplication("Apppath")
to recognize the application object - use index property.
ex: In case of Browser use Creation time
140) when tests run as batch, qtp shows the last run result only. how to get the results
for the each an every script?
Simple way is using MTM (Multi Test Manager) where you will build a test suit and then
simple hit on Run, which will execute the scripts and give you the status report. But, we
have to make sure that the results path is not pointing to Temp.
2) Develop a custome reporting where all the steps will be stored in your desired
location.
If you don't want to change your current code, then you can change the results folder to
you desired folder where you want to see the Results, once you are done with scripts
execution you can access all the execution reports.
'Create the Run Results object
set oQTPResultsLoc = CreateObject("QuickTest.RunResultsOptions")
'Make sure that you have the required folders for results storing.
'In this example C:\Test Results is the folder where I want to store my results with Test
Case name.
'Now change the results location
oQTPResultsLoc .ResultsLocation "C:\Test Results\" & Environment("TestName")
Start QTP, Open an Existing Test and Get All Available Action Names From the
Test:
Dim qtApp
'Create the QTP Application object
Set qtApp = CreateObject("QuickTest.Application")
'If QTP is notopen then open it
If qtApp.launched <> True then
qtApp.Launch
End If
'Make the QuickTest application visible
qtApp.Visible = True
qtApp.Open "C:\Program Files\HP\QuickTest Professional\Tests\trial", False, False
'Get count of Action in a test
oActCount=qtApp.Test.Actions.Count
For iCounter=1 to oActCount
' Get the first action in the test by index (start from 1)
MsgBox qtApp.Test.Actions(iCounter).Name
Next
'Close QuickTest
qtApp.Quit
' Release the Application object
Set qtApp = Nothing
140) QTP-Qc integration
QTP-QC Integration:
In this section, we are going to learn how to integrate QTP and QC. By Integrating, the
QTP automation scripts can be executed right from Quality Center. For establishing a
connection, first step is to install the required Addins. We will understand how to
integrate by taking a sample QTP script and execute it from QC.
Step 1: Navigate to ALM home page and click on "Tools" from the list of links.
Step 2: Click on "More HP ALM Addins" Link from the addins page as shown below.
Step 3: In the Addins page, select "Addins for HP applications" and choose "Quick Test
Professional". In case of "Unified Functional testing" (UFT), choose the options
appropriately and install the addins. The Installation is similar to HP-MS Office Addins.
Step 4: Establish a connection between QTP and QC by Navigating to "File" >> "ALM/QC
Connection".
Step 5: HP ALM Connection dialog opens. Enter the Server URL as shown in the below
example.
Step 6: Once the URL is correct, the credientials dialog opens. Tester has to connect to
the relevant project area.
Step 7: Once ALM Connection is successful, we need to save the Driver Script in Quality
Center. Select ALM/QC Plan as shown below.
Step 8: Once the test is saved, we can see the in ALM where the test type is shown as
"Quick Test".
Step 9: Upon Navigating to "Test Script" Tab which appears only if the test type is of
"Quick Test", The script shown in QTP screen would be displayed in Quality Center as
well.
Step 9: The other necessary component that is required for script execution is Library
files which can be placed under "Test Resources" Folder.
Step 10: The Function Library file can be added by creating a new resource of type ".qfl"
or ".vbs" .
Step 11: The Added library file can be accessed in quality Center using resource Viewer.
Step 12: If there are more library files, the same is added by creating a new resource of
type ".qfl" or ".vbs".
Step 13: Once again, Added library file can be accessed in quality Center using resource
Viewer.
Step 14: The Next dependant component for any script execution is "Object Repository"
which is again placed under "Resources" section.
Step 15: The added Object Repository and its properties can be viewed using "Resource
Viewer".
Step 16: The Datatable, parameterized data setup also be placed in Quality Center
under "Test Resouces" section.
Step 17: The added data Table can be viewed using in "Resource Viewer".
Step 18: The Datatable should now also be mapped to the test settings so that they can
be picked while execution. The same can be done using "Settings" of "File" Menu.
Step 19: The Test Settings dialog opens. Navigate to Resources Tab and select the
Datatable that we added in Step 16.
Step 20: Now we can access those test resources that are uploaded in Quality Center in
QTP script as shown below. The Libraries files and Object Repositories are binded
dynamically.
Step 21: Now, we should allow QTP to interact with other Hp Products. This will allow
QTP to interact with Quality Center. Goto "Tools" >> "Options"
Step 22: Now, enable "Allow other HP products to run tests and components" as shown
below.
Step 23: The Next Step is to add the test in "Test Lab" and execute the test. The
Procedure to Add tests into Test Lab remains the same as that of manual tests.
Step 24: Upon Clicking on "Run", the automatic runner opens and enable "Run all tests
locally" and hit "Run".
Step 25: Once execution is complete, the test result is displayed on the the same
"Automatic Runner" dialog.
Step 26: In Test Lab QTP report is loaded automatically. User can click on "Launch
report" to get to know about more details of the execution.
on start-up.
146) What if QTP tries to connect with QC automatically but QC login credentials had changed?
A: Change the following properties from 1 to 0. They are present in mic.ini file under
QTP installation generally found under C:Program FilesMercury InteractiveQuickTest
Professionalbin
LoginAutomatically=0
ReconnectToDB=0
ReconnectToServer=0
147) How can we access Quality Center Open Test Architecture (OTA) using AOM?
A: Using QCUtil object (AKA TDUtil for QTP 6.5 and backwards). You can find details of
all associated properties like CurrentRun, TestRun, Current Testset, CurrentTestSetTest,
IsConnected, QCConnection under QTP Help > Quick Test Object Model Reference > Utility
Objects > QCUtil Object.
Qqqq: Where can we find all methods and properties present under TDConnection
Object?
A: Refer QTP Help > QTP Advanced References > QuickTest Automation >
TDConnection Object.
QQ: How can we upload QTP scripts to QC using AOM?
A: Once connected to Quality Center, open the test using AOM and save it to QC.
Example:
qtqcApp.Open "C:TempProjectQTPTestScript1", True
' Get the Test object
Create a folder under the root folder and right click to create a new test as shown below.
Once New test option is clicked a pop up appears as shown below. In the Test Type box,
select QUICKTEST_TEST to create a Quick Test Professional test, or select WRAUTOMATED to create a
WinRunner test.
In the Test Type box, select QUICKTEST_TEST to create a Quick Test Professional test, or
select WR-AUTOMATED to create a Win Runner test.
Once Test Name is provided and user clicks on OK.It takes to the next step where we
need to provide the description as shown below.
Once the automated test case is created. Click on Test Script tab present on the right
hand side.A script is generated based on the design steps of the test case as shown
below.
Navigate to Test Lab module present on the left hand side of the application.
Navigate to the folder created and add a test set Test as shown below.
Right click and select the option Select tests which open a test plan tree as shown
below.
Select the tests from the test set by clicking on the left arrow in the test plan tree
present on the right hand side.
Select the required test case and click on the Run button present on the top, below the
menu bar.
The automatic runner pop up opens up, where the test to be run will be selected. Then
click on Run.
This connects to the automation tool which is integrated with the QC application and
gives us the result of the run for the particular test case.
When a test has finished running you can view the test results in your selected
testing tool
To view the test results in Quick Test Professional, click the Launch Report button.
To view the test results in Win Runner, click the View Report button.
Test Lab Module in QC Part2: Logging Defects from test lab
This is in continuation of our series of articles on Test Lab Module in QC. In the first
article we saw how to create a test set, move scripts from test plan and run them
manually
In this article well see how we can raise a new defect from the test lab itself for a
particular script. (Click on the images below to view them in full size. Press Esc key
when you wish to return to the article)
Once you find a particular test case is a failure and youre sure its a defect, then follow
the steps mentioned below.
Click on the option Run > Select Run Manually from the drop down list.
If any/all steps are failing for a test case then update the status as Fail Selected/Fail
Allas per the snapshot shown below.
Once the status is updated as Failed click on the New Defect option present beside
the attachment section.
A new window opens. You would need to input the details of the issue in various fields
given below and hit Submit.
Location_ID Regional_Group
122
NEW YORK
123
DALLAS
124
CHICAGO
167
BOSTON
DEPARTMENT
Department_ID
10
20
30
40
JOB
Job_ID
667
668
669
670
671
672
Name
ACCOUNTING
RESEARCH
SALES
OPERATIONS
Location_ID
122
124
123
167
Function
CLERK
STAFF
ANALYST
SALESPERSON
MANAGER
PRESIDENT
EMPLOYEE
EMPLOYEE_ID LAST_NAME FIRST_NAME MIDDLE_NAME JOB_ID MANAGER
7369
SMITH
JOHN
667
790
7499
ALLEN
KEVIN
670
7698
7505
DOYLE
JEAN
671
7839
7506
DENNIS
LYNN
671
7839
7507
BAKER
LESLIE
671
7839
7521
WARK
CYNTHIA
670
7698
to_char(hire_date,yyyy)=1985 group by
to_char(hire_date,yyyy),to_char(hire_date,mon)
32. How many employees who are joined in March 1985.
Select to_char(hire_date,yyyy)Year, to_char(hire_date,mon)
Month, count(*) No. of employees from employee where
to_char(hire_date,yyyy)=1985 and to_char(hire_date,mon)=mar
group by to_char(hire_date,yyyy),to_char(hire_date,mon)
33. Which is the department id, having greater than or equal to 3
Select department_id, count(*) No. of employees from
employee where to_char(hire_date,yyyy)=1985 and
to_char(hire_date,mon)=apr group by to_char(hire_date,yyyy),
to_char(hire_date,mon), department_id having count(*)>=3
SubQueries
34. Display the employee who got the maximum salary. : Select * from employee where
salary=(select max(salary)
from employee)
35. Display the employees who are working in Sales department: Select * from
employee where department_id IN (select
department_id from department where name=SALES)
36. Display the employees who are working as Clerk.:
Select * from employee where job_id in (select job_id from
job where function=CLERK
37. Display the employees who are working in New York
Select * from employee where department_id=(select
department_id from department where location_id=(select location_id
from location where regional_group=New York))
38. Find out no.of employees working in Sales department.
Select * from employee where department_id=(select
department_id from department where name=SALES group by
department_id)
39. Update the employees salaries, who are working as Clerk on the basis
of 10%.
Update employee set salary=salary*10/100 wehre job_id=
(select job_id from job where function=CLERK)
40. Delete the employees who are working in accounting department. :delete from
employee where department_id=(select
department_id from department where name=ACCOUNTING)
41. Display the second highest salary drawing employee details.
41.:Select * from employee where salary=(select max(salary)
from employee where salary <(select max(salary) from employee))
42. Display the Nth highest salary drawing employee details .:Select distinct e.salary
from employee where & no1=(select count(distinct salary) from employee where
sal>e.salary)
SubQuery
operators: (ALL,ANY,SOME,EXISTS)
43. List out the employees who earn more than every employee in
department 30: Select * from employee where salary > all (Select salary
QTP scripts :
1.Suppose I want to do DP for licindia.com where I need to click on the login button.
Here the hierarchy captured through Object spy shows as
Browser->frame->webTable->webTable->webTable->webTable->Button
In this case how should be the DP for clicking on the button?
Ans:
Beginners will feel difficult when writing descriptive programming.
Here is an example how to write descriptive programming when there are many objects
in an object hierarchy.
The basic hierarchy of an object is Browser--> Page --> Object
Some times when you spy on object it shows Browser--> Page -->WebTable-> WebTable-->WebTable-->Object
But in DP you can ignore webtables in the hierarchy and consider Browser--> Page -->
Object.
When the hierarchy is like Browser--> Page -->Frame-->WebTable--> WebTable->WebTable-->Object
Then consider Browser--> Page -->Frame-->Object
A Simple Technique to identify how to write DP when you have confusion in
hierarchy level
1. Add that object to Object Repository
2.
3.
38.
Set ImportSheetFromXLSX=qSheet
39.
ExcelFile.Close
40.
ExcelApp.Quit
41.
End Function
42.
'*************************************************************************
*******************************
There is also another way of overwriting Datatable object to import XLSX files. This is
useful for the projects which are already used Datatable.ImportSheet in lot many places
and now they want to enable XLSX support without modifying QTP script. Below is the
example on how to over write datatable object with newly created class. If you use
below code you need to update all existing QTP datatable object methods and
properties.
1.
EnableXLSXsupport()
2.
DataTable.ImportSheet "C:\Users\sudhakar\Desktop\Blog Data\test.xlsx
","Sheet2","Action1"
3.
4.
'*************************************************************************
*******************************
5.
Function EnableXLSXsupport()
6.
7.
ExecuteGlobal "Dim QTPDataTable"
8.
9.
Set QTPDataTable=Datatable
10.
ExecuteGlobal "Dim Datatable"
11.
12.
Set Datatable=New CustomDatatable
13.
14.
End Function
15.
'*************************************************************************
*******************************
16.
Class CustomDatatable
17.
18.
Function ImportSheet(dFileName,dSourceSheetName,dDestinationSheet
Name)
19.
20.
Dim ExcelApp
21.
Dim ExcelFile
22.
Dim ExcelSheet
23.
Dim sRowCount
24.
Dim sColumnCount
25.
Dim sRowIndex
26.
Dim sColumnIndex
27.
Dim sColumnValue
28.
29.
Set ExcelApp=CreateObject("Excel.Application")
30.
Set ExcelFile=ExcelApp.WorkBooks.Open (dFileName)
31.
Set ExcelSheet = ExcelApp.WorkSheets(dSourceSheetName)
32.
33.
Set qSheet=QTPDataTable.GetSheet(dDestinationSheetName)
34.
35.
sColumnCount= ExcelSheet.UsedRange.Columns.Count
36.
sRowCount= ExcelSheet.UsedRange.rows.count
37.
38.
For sColumnIndex=1 to sColumnCount
39.
40.
sColumnValue=ExcelSheet.Cells(1,sColumnIndex)
41.
sColumnValue=Replace(sColumnValue," ","_")
42.
43.
If sColumnValue="" Then
44.
sColumnValue="NoColumn"&sColumnIndex
45.
End If
46.
47.
Set qColumn=qSheet.AddParameter (sColumnValue,"")
48.
49.
For sRowIndex=2 to sRowCount
50.
sRowValue=ExcelSheet.Cells(sRowIndex,sColumnIndex)
51.
qColumn.ValueByRow(sRowIndex-1)=sRowValue
52.
Next
53.
54.
Next
55.
'Set Datatable=QTPDataTable
56.
ExcelFile.Close
57.
ExcelApp.Quit
58.
'Set QTPDataTable=Nothing
59.
End Function
60.
'********************************************************************
61.
Function AddSheet(shtName)
62.
Set AddSheet=QTPDataTable.AddSheet(shtName)
63.
End Function
64.
'********************************************************************
65.
End Class
66.
'*************************************************************************
*******************************
If you uncomment the Set Datatable=QTPDatatable and Set QTPDatatable =Nothing then
this function only works for once. When ever you want to import XLSX sheet then you
need to call EnableXLSXsupport() before you use import sheet. This way is for the
experts who can handle overwriting of reserved objects. Do remember that If you have
not uncommented, the existing datatable methods will not work and you need to define
each method in customdatatable class in order to work. You can observe the "AddSheet"
method in the above class example.
3. All About validation of Editbox : 1 Verify Maximum length
Ans
Basic Editbox Testing Checklist:-
1.Maximum Length
2.Characters Acceptance
Alpha Characters Only
Numeric Characters Only
Alpha Numeric Characters Only
Alpha Numeric Custom Characters
3.Clipboard Text Acceptance
4.Enable / Disable
5.Text Encryption
To understand this post the reader should already know about
18.
else
19.
Reporter.ReportEvent micFail,"Textbox Max Length Validation","Text
box support more than "& oMaxLength&"Characters"
20.
End If
21.
Set wsh= nothing
22.
23.
End Function
24.
25.
'*************************************************************************
*********
26.
27.
Calling the Function
28.
29.
set EditObj=Browser("").Page("").WebEdit("")
30.
ValidateTextboxMaxLength EditObj
31.
32.
'OR
33.
34.
RegisterUserFunc "WebEdit","ValidateTextboxMaxLength,"ValidateTextb
oxMaxLength
35.
36.
Browser("").Page("").WebEdit("").ValidateTextboxMaxLength
37.
38.
UnregisterUserFunc "WebEdit","ValidateTextboxMaxLength"
This article is the continuation of my previous post All about Validation of Editbox
Part-1. This will discuss about edit box character acceptance.
Usually there are 3 text character types used to enter in edit box. Sometimes it can be a
combination from these three types.
1.
Alphabetic
2.
Numeric
3.
Special characters
When you check the character acceptance for an edit box using QTP, the edit box will
always accept all the values which are coming from QTP. Even though if that edit box is
developed to enter only alphabetic or only numeric or only special characters. But when
anyuser enters the value it accepts only the values for which it is developed. As I said
before Automation Testing is Not like Automating the Application Functionalities. Its
should Replicate the Exact Manual Actions. So to replicate exact manual actions we have
to use SendKeys method in WSH.
The below function is useful in such conditions
1.
2.
3.
Function ValidateCharacterAcceptance(oEditObject,oTypeofEditBox)
'Variable Declaration
4.
Dim wsh
5.
Dim oTypingText
6.
Dim oVisibleText
7.
8.
'Assign a text value to the variable which is having all value types
9.
oTypingText="SudhakarKakunuri1234@!#$"
10.
11.
'clear the values of edit box and focus on it by clicking
12.
oEditObject.Set ""
13.
oEditObject.Click
14.
'Wait is to clear some disturbance
15.
wait(1)
16.
17.
'Create wscript object
18.
set wsh=CreateObject("wscript.shell")
19.
20.
'Send text using sendkeys method
21.
wsh.SendKeys oTypingText
22.
23.
'Wait is to clear some disturbance
24.
wait(1)
25.
26.
'Get the visible text of the edit box
27.
oVisibleText=oEditObject.GetROProperty("value")
28.
29.
'User can enter any type of text. But editbox accepts only the text which it
is meant for.
30.
'The below condition check the visible text based on the text type.
31.
'If the type of visible text doesnot match the type of the edit box then the c
ondition fails
32.
33.
Select Case lcase(oTypeofEditBox)
34.
35.
Case "alphabetic"
36.
37.
If oVisibleText="SudhakarKakunuri" then
38.
Reporter.ReportEvent micPass,"Check Alphabetic Character Acceptance",
"Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
39.
Else
40.
Reporter.ReportEvent micFail,"Check Alphabetic Character Acceptance", "
Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
41.
End If
42.
43.
Case "numeric"
44.
45.
If oVisibleText="1234" then
46.
Reporter.ReportEvent micPass,"Check Numeric Character Acceptance", "T
yped Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
47.
Else
48.
Reporter.ReportEvent micFail,"Check Numeric Character Acceptance", "T
yped Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
49.
End If
50.
Case "alphanumeric"
51.
52.
If oVisibleText="SudhakarKakunuri1234" then
53.
Reporter.ReportEvent micPass,"Check AlphaNumeric Character Acceptan
ce", "Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
54.
Else
55.
Reporter.ReportEvent micFail,"Check AlphaNumeric Character Acceptanc
e", "Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleText
56.
End If
57.
58.
Case "alphanumericspecial"
59.
60.
If oVisibleText=oTypingText then
61.
Reporter.ReportEvent micPass,"Check AlphaNumericSpecial Character Ac
ceptance", "Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleT
ext
62.
Else
63.
Reporter.ReportEvent micFail,"Check AlphaNumericSpecial Character Acc
eptance", "Typed Text: "& oTypingText &vbnewline& "Visible Text: "& oVisibleTe
xt
64.
End If
65.
End Select
66.
67.
Set wsh= nothing
68.
End Function
69.
70.
'Calling the Function
71.
Set oEditObject=Browser("").Page("").WebEdit("")
72.
ValidateCharacterAcceptance oEditObject,"alphanumericspecial"
Vbscript Samples
In lot of places I have used print statement. This will work only in QTP. If you
want to execute these samples using .vbs, just replace print with msgbox.
1.
##
2.
##
3.
4.
5.
##
6.
##
7.
8.
'##################################################
'##################################################
'1 Print Hello World
Print "Hello World"
'##################################################
'##################################################
'2 Find whether given number is a odd number
Dim oNumber
9.
10.
11.
12.
13.
14.
15.
16.
##
17.
##
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
##
35.
##
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
##
50.
##
51.
oNumber=4
If oNumber mod 2 <>0 Then
Print "The Number "& oNumber &" is an Odd Number"
else
Print "The Number "& oNumber &" is not an Odd Number"
End If
'##################################################
'##################################################
'3 Print odd numbers between given range of numbers
Dim RangeStart
Dim RangeEnd
Dim iCounter
RangeStart=10
RangeEnd=20
For iCounter=RangeStart to RangeEnd
If iCounter mod 2 <>0 Then
Print oNumber
End If
Next
'##################################################
'##################################################
'4 Find the factorial of a given number
Dim oNumber
Dim iCounter
Dim fValue
oNumber=6
fValue=1
For iCounter=oNumber to 1 step-1
fValue=fValue*iCounter
Next
print fValue
'##################################################
'##################################################
'5 Find the factors of a given number
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
##
64.
##
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
##
87.
##
88.
89.
90.
91.
92.
93.
94.
95.
96.
Dim oNumber
Dim iCounter
oNumber=10
For iCounter=1 to oNumber/2
If oNumber mod iCounter=0 Then
print iCounter
End If
Next
print oNumber
'##################################################
'##################################################
'6 Print prime numbers between given range of numbers
Dim RangeStart
Dim RangeEnd
Dim iCounter
RangeStart=1
RangeEnd=30
For iCounter=RangeStart to RangeEnd
For iCount=2 to round(iCounter/2)
If iCounter mod iCount=0 Then
Exit for
End If
Next
If iCount=round(iCounter/2)+1 or iCounter=1 Then
print iCounter
End If
Next
'##################################################
'##################################################
'7 Swap 2 numbers with out a temporary variable
Dim oNum1
Dim oNum2
oNum1=1055
oNum2=155
oNum1=oNum1-oNum2
97.
oNum2=oNum1+oNum2
98.
oNum1=oNum2-oNum1
99.
print oNum1
100. print oNum2
101. '##################################################
##
102. '##################################################
##
103. '8 Write a program to Perform specified Arithmetic Operation on two gi
ven numbers
104. Dim oNum1
105. Dim oNum2
106. Dim oValue
107.
108. oNum1=10
109. oNum2=20
110.
111. OperationtoPerform="div"
112.
113. Select Case lcase(OperationtoPerform)
114.
115.
Case "add"
116.
oValue=oNum1+oNum2
117.
Case "sub"
118.
oValue=oNum1-oNum2
119.
Case "mul"
120.
oValue=oNum1*oNum2
121.
Case "div"
122.
oValue=oNum1/ oNum2
123. End Select
124. print oValue
125. '##################################################
##
126. '##################################################
##
127. '9 Find the length of a given string
128. Dim oStr
129. Dim oLength
130. oStr="sudhakar"
131. oLength=len(oStr)
132. print oLength
133. '##################################################
##
134. '##################################################
##
135. '10 Reverse given string
136. Dim oStr
137. Dim oLength
138. Dim oChar
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
##
149.
##
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
##
171.
##
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
##
Dim iCounter
oStr="sudhakar"
oLength=len(oStr)
For iCounter=oLength to 1 step-1
oChar=oChar&mid(oStr,iCounter,1)
Next
print oChar
'##################################################
'##################################################
'11 Find how many alpha characters present in a string.
Dim oStr
Dim oLength
Dim oChar
Dim iCounter
oStr="su1h2kar"
oLength=len(oStr)
oAlphacounter=0
For iCounter=1 to oLength
If not isnumeric (mid(oStr,iCounter,1)) then
oAlphacounter=oAlphacounter+1
End if
Next
print oAlphacounter
'##################################################
'##################################################
'12 Find occurrences of a specific character in a string
Dim oStr
Dim oArray
Dim ochr
oStr="sudhakar"
ochr="a"
oArray=split(oStr,ochr)
print ubound(oArray)
'##################################################
183. '##################################################
##
184. '13 Replace space with tab in between the words of a string.
185.
186. Dim oStr
187. Dim fStr
188.
189. oStr="Quick Test Professional"
190.
191. fStr=replace(oStr," ",vbtab)
192. print fStr
193.
194. '##################################################
##
195. '##################################################
##
196. '14 Write a program to return ASCII value of a given character
197.
198. Dim ochr
199. Dim aVal
200.
201. ochr="A"
202.
203. aVal=asc(ochr)
204. print aVal
205.
206. '##################################################
##
207. '##################################################
##
208. '15 Write a program to return character corresponding to the given ASCI
I value
209.
210. Dim ochr
211. Dim aVal
212.
213. aVal=65
214.
215. oChr=chr(aVal)
216. print oChr
217.
218. '##################################################
##
219. '##################################################
##
220. '16 Convert string to Upper Case
221. Dim oStr
222. Dim uStr
223.
224.
225.
226.
227.
228.
##
229.
##
230.
231.
232.
233.
234.
235.
236.
237.
238.
##
239.
##
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
##
255.
##
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
oStr="QuickTest Professional"
uStr=ucase(oStr)
print uStr
'##################################################
'##################################################
'17 Convert string to lower case
Dim oStr
Dim lStr
oStr="QuickTest Professional"
lStr=lcase(oStr)
print lStr
'##################################################
'##################################################
'18 Write a program to Replace a word in a string with another word
Dim oStr
Dim oWord1
Dim oWord2
Dim fStr
oStr="Mercury Quick Test Professional"
oWord1="Mercury"
oWord2="HP"
fStr=replace(oStr,oWord1,oWord2)
print fStr
'##################################################
'##################################################
'19 Check whether the string is a POLYNDROM
Dim oStr
oStr="bob"
fStr=StrReverse(oStr)
If oStr=fStr Then
Print "The Given String "&oStr&" is a Palindrome"
else
Print "The Given String "&oStr&" is not a Palindrome"
End If
267.
##
268.
##
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
##
281.
##
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
##
292.
##
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
'##################################################
'##################################################
'20 Verify whether given two strings are equal
Dim oStr1
Dim ostr2
oStr1="qtp"
oStr2="qtp"
If oStr1=oStr2 Then
Print "The Given Strings are Equal"
else
Print "The Given Strings are not Equal"
End If
'##################################################
'##################################################
'21 Print all values from an Array
Dim oArray
Dim oCounter
oArray=array(1,2,3,4,"qtp","Testing")
For oCounter=lbound(oArray) to ubound(oArray)
print oArray(oCounter)
Next
'##################################################
'##################################################
'22 Sort Array elements
Dim oArray
Dim oCounter1
Dim oCounter2
Dim tmp
oArray=array(8,3,4,2,7,1,6,9,5,0)
For oCounter1=lbound(oArray) to ubound(oArray)
For oCounter2=lbound(oArray) to ubound(oArray)-1
If oArray(oCounter2)>oArray(oCounter2+1) Then
tmp=oArray(oCounter2)
oArray(oCounter2)=oArray(oCounter2+1)
oArray(oCounter2+1)=tmp
End If
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
##
320.
##
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
##
341.
##
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
Next
Next
For oCounter1=lbound(oArray) to ubound(oArray)
print oArray(oCounter1)
Next
'##################################################
'##################################################
'23 Add two 2X2 matrices
Dim oArray1(1,1)
Dim oArray2(1,1)
Dim tArray(1,1)
oArray1(0,0)=8
oArray1(0,1)=9
oArray1(1,0)=5
oArray1(1,1)=-1
oArray2(0,0)=-2
oArray2(0,1)=3
oArray2(1,0)=4
oArray2(1,1)=0
tArray(0,0)=oArray1(0,0)+ oArray2(0,0)
tArray(0,1)=oArray1(0,1)+oArray2(0,1)
tArray(1,0)=oArray1(1,0)+oArray2(1,0)
tArray(1,1)=oArray1(1,1)+oArray2(1,1)
'##################################################
'##################################################
'24 Multiply Two Matrices of size 2X2
Dim oArray1(1,1)
Dim oArray2(1,1)
Dim tArray(1,1)
oArray1(0,0)=8
oArray1(0,1)=9
oArray1(1,0)=5
oArray1(1,1)=-1
oArray2(0,0)=-2
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
##
366.
##
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
##
379.
##
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
##
392.
##
393.
394.
395.
396.
397.
oArray2(0,1)=3
oArray2(1,0)=4
oArray2(1,1)=0
tArray(0,0)=oArray1(0,0)* oArray2(0,0)+ oArray1(0,1)* oArray2(1,0)
tArray(0,1)=oArray1(0,0)* oArray2(0,1)+ oArray1(0,1)* oArray2(1,1)
tArray(1,0)=oArray1(1,0)* oArray2(0,0)+ oArray1(1,1)* oArray2(1,0)
tArray(1,1)=oArray1(1,0)* oArray2(0,1)+ oArray1(1,1)* oArray2(1,1)
'##################################################
'##################################################
'25 Convert a String in to an array
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr)
For iCounter=0 to ubound(StrArray)
print StrArray(iCounter)
Next
'##################################################
'##################################################
'26 Convert a String in to an array using i as delimiter
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
StrArray=split(oStr,"i")
For iCounter=0 to ubound(StrArray)
print StrArray(iCounter)
Next
'##################################################
'##################################################
'27 Find number of words in string
Dim oStr
Dim iCounter
oStr="Quick Test Professional"
442.
443.
444.
445.
446.
447.
448.
##
449.
##
450.
451.
452.
453.
454.
455.
456.
457.
458.
459.
##
460.
##
461.
462.
463.
464.
465.
466.
467.
468.
##
469.
##
470.
array
471.
472.
473.
474.
475.
476.
477.
478.
479.
480.
481.
482.
483.
484.
485.
486.
487.
488.
489.
490.
##
491.
##
492.
493.
494.
495.
496.
497.
498.
499.
500.
501.
502.
##
503.
##
504.
505.
506.
507.
508.
509.
510.
##
511.
##
512.
513.
514.
515.
516.
517.
518.
519.
520.
521.
##
522.
##
523.
524.
568.
569.
570.
571.
572.
573.
##
574.
##
575.
576.
577.
578.
579.
580.
581.
582.
583.
584.
585.
586.
587.
588.
##
589.
##
590.
591.
592.
593.
##
594.
##
595.
596.
597.
598.
599.
600.
601.
602.
603.
604.
605.
606.
##
607.
##
608.
609.
610.
611.
612.
##
613.
##
614.
615.
616.
617.
##
618.
##
619.
620.
621.
622.
623.
624.
625.
626.
627.
628.
629.
630.
631.
632.
633.
##
634.
##
635.
636.
637.
638.
639.
640.
641.
642.
643.
644.
645.
646.
647.
648.
) then
649.
650.
651.
652.
653.
654.
655.
656.
657.
658.
659.
660.
661.
662.
663.
664.
665.
666.
667.
668.
669.
670.
##
671.
##
672.
673.
674.
675.
676.
677.
678.
679.
680.
##
681.
##
682.
683.
684.
685.
686.
687.
688.
689.
690.
691.
692.
693.
##
694. '##################################################
##
695. '48 Write a program to show difference between Fix and Int
696.
697. 'Both Int and Fix remove the fractional part of number and return the res
ulting integer value.
698. 'The difference between Int and Fix is that if number is negative, Int retur
ns the first negative integer less than or equal to number,
699. 'Whereas Fix returns the first negative integer greater than or equal to nu
mber.
700. 'For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.
701.
702. print Int(99.8) ' Returns 99.
703. print Fix(99.2) ' Returns 99.
704. print Int(-99.8) ' Returns -100.
705. print Fix(-99.8) ' Returns -99.
706. print Int(-99.2) ' Returns -100.
707. print Fix(-99.2) ' Returns -99.
708.
709. '##################################################
##
710. '##################################################
##
711. '49 Write a program to find subtype of a variable
712.
713. Dim oVar
714. Dim oDatatypes
715. oVar="QTP"
716. oVartype=Typename(oVar)
717. print oVartype
718.
719. '##################################################
##
720. '##################################################
##
721. '50 Write a program to print the decimal part of a given number
722. Dim oNum
723. oNum=3.123
724. oDecNum=oNum- int(oNum)
725. print oDecNum
726. '##################################################
##
727. '##################################################
##
9) Using one library function in other library
As we all know that we can automate the Web Applications by using only DOM +
VBScript without having any automation tool. In this process we have to write the
global functions to handle webobjects like links, edit boxes, radio buttons etc.
I have got a requirement to automate an application only by using DOM + VBscript. For
this process I have created all the global functions to handle every web object and
stored all the functions in a library. Find some of the functions here to handle link, Edit,
Radio buttons etc.
This is the plan I thought to Automate the Testcases Using DOM
Write scripts by calling global functions (scripts will be stored as VBS files)
I thought of using filesystem object and execute statements to call functions in . But
those are not fully capable for some of the situations. And the next one immediately
came in my mind is Microsoft Script Control.
Using Microsoft Script Control you can call one library functions in another library. For
this you have to follow below steps.
1.
Read and store all the text from source library file using filesystem object
2.
3.
Call the functions using MSScriptControl methods
Source Library Code
Dim a
a=20
Function demo ()
MsgBox "QTP Sudhakar"
End Function
Function demo_add (x,y)
demo_add = x+y
End Function
Calling the Functions in other libraries
'Create file system object
Set fso=CreateObject("scripting.filesystemobject")
'Open library file
Set sFile=fso.OpenTextFile("C:\Documents and Settings\sudhakar
kakunuri\Desktop\Script Control\source.vbs")
'Read the complete data from library file
SourceLibraryData=sFile.ReadAll
'close the file
sFile.Close
'Create Script Control Object
Set scrControl=CreateObject("msscriptcontrol.scriptcontrol")
'Specify the language to be controlled
scrControl.Language = "VBScript"
31.
' Function Name : CheckStringSortDescending
32.
' Parameter : An Array contains list of strings
33.
' Description : This function checks the given list of
34.
' strings are in descending order
35.
'*************************************************************
36.
Function CheckStringSortDescending(strArray)
37.
38.
Dim aIndex
39.
40.
CheckStringSortDescending=True
41.
42.
For aIndex=0 To UBound(strArray)-1
43.
44.
If StrComp(lcase(strArray(aIndex)),lcase(strArray(aIndex+1)))<0 Then
45.
CheckStringSortDescending=False
46.
Exit Function
47.
End If
48.
Next
49.
50.
End Function
51.
52.
'*************************************************************
###########################################################
1.
'#################### Date Sort #######################
########
2.
'##################################################
############
3.
4.
'*************************************************************
5.
' Function Name : CheckDateSortAscending
6.
' Parameter : An Array contains list of Date Values
7.
' Description : This function checks the given list of
8.
' Date values are in ascending order
9.
'*************************************************************
10.
11.
Function CheckDateSortAscending(dtArray)
12.
13.
Dim aIndex
14.
15.
CheckDateSortAscending=True
16.
17.
For aIndex=0 To UBound(dtArray)-1
18.
19.
If DateDiff("d",dtArray(aIndex),dtArray(aIndex+1))<0 Then
20.
CheckDateSortAscending=False
21.
Exit Function
22.
End If
23.
24.
Next
25.
26.
End Function
27.
28.
'*************************************************************
29.
'##################################################
###########
30.
'*************************************************************
31.
' Function Name : CheckDateSortDescending
32.
' Parameter : An Array contains list of Date Values
33.
' Description : This function checks the given list of
34.
' Date values are in Descending order
35.
'*************************************************************
36.
37.
Function CheckDateSortDescending(dtArray)
38.
39.
Dim aIndex
40.
41.
CheckDateSortDescending=True
42.
43.
For aIndex=0 To UBound(dtArray)-1
44.
45.
If DateDiff("d",dtArray(aIndex),dtArray(aIndex+1))>0 Then
46.
CheckDateSortDescending=False
47.
Exit Function
48.
End If
49.
50.
Next
51.
52.
End Function
53.
54.
'*************************************************************
1.
'##################################################
############
2.
'#################### Numeric Sort ####################
########
3.
'##################################################
############
4.
5.
'*************************************************************
6.
' Function Name : CheckNumericSortAscending
7.
' Parameter : An Array contains list of numbers
8.
' Description : This function checks the given list of
9.
' numbers are in Ascending order
10.
'*************************************************************
11.
12.
Function CheckNumericSortAscending(numArray)
13.
14.
Dim aIndex
15.
16.
CheckNumericSortAscending=True
17.
18.
For aIndex=0 To UBound(numArray)-1
19.
20.
If numArray(aIndex)>numArray(aIndex+1) Then
21.
CheckNumericSortAscending=False
22.
Exit Function
23.
End If
24.
Next
25.
26.
End Function
27.
28.
'*************************************************************
29.
'##################################################
###########
30.
'*************************************************************
31.
' Function Name : CheckNumericSortDescending
32.
' Parameter : An Array contains list of numbers
33.
' Description : This function checks the given list of
34.
' numbers are in Descending order
35.
'*************************************************************
36.
37.
Function CheckNumericSortDescending(numArray)
38.
39.
Dim aIndex
40.
41.
CheckNumericSortDescending=True
42.
43.
For aIndex=0 To UBound(numArray)-1
44.
45.
If numArray(aIndex)<numArray(aIndex+1) Then
46.
CheckNumericSortDescending=False
47.
Exit Function
48.
End If
49.
Next
50.
51.
End Function
52.
53.
'*************************************************************
10)Different ways to write a statement
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
rch")
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
)
47.
48.
49.
50.
51.
52.
'***Common Method***
'For Web
Browser("Google").Page("Google").WebButton("Google Search").Click
'*******************
'For Windows
Window("Flight Reservation").WinButton("Update Order").Click
'##############################
'#### 2nd method ###############
'##############################
'*** Assigning window object to an object variable***
'For Web
'Assigning Parent Object to a variable
Set oPageObj=Browser("Google").Page("Google")
oPageObj.WebButton("Google Search").Click
'Assigning Complete Object to a variable
Set oBtnObj=Browser("Google").Page("Google").WebButton("Google Sea
oBtn.Click
'*******************
'For Windows
Set wndObject=Window("Flight Reservation")
' Following normal syntax ( click on a button)
wndObject.WinButton("Update Order").Click
'
OR
53.
54.
'*** Using With statement***
55.
56.
'For Web
57.
With Browser("Google").Page("Google")
58.
WebButton("Google Search").Click
59.
End With
60.
61.
'*******************
62.
63.
'For Windows
64.
65.
With Window("Flight Reservation")
66.
.WinButton("Update Order").click
67.
End with
68.
69.
'##############################
70.
'#### 4th method ###############
71.
'##############################
72.
73.
'***Descriptive programming (Static Description)***
74.
75.
'For Web
76.
77.
Browser("name:=Google").Page("title:=Google").WebButton("name:=Goo
gle Search").Click
78.
79.
'*******************
80.
81.
'For Windows
82.
83.
Window("text:=Flight Reservation").WinButton("text:=&Update Order").
Click
84.
85.
'##############################
86.
'#### 5th method ###############
87.
'##############################
88.
89.
'***Descriptive programming (Dynamic Description)***
90.
91.
'For Web
92.
93.
Set oDes=Description.Create
94.
' assigning description to the description object
95.
oDes("micclass").value="WebButton"
96.
oDes("name").value="Google Search"
97.
' clicking on button using the created description object
98.
Browser("name:=Google").Page("title:=Google").WebButton(oDes).click
99.
100. '*******************
101.
102. 'For Windows
103.
104. Set oDes=Description.Create
105. ' assigning description to the description object
106. oDes("nativeclass").value="Button"
107. oDes("text").value="&Update Order"
108. ' clicking on button using the created description object
109. Window("text:=Flight Reservation").winbutton(oDes).click
110.
111. '##############################
112. '#### 6th method ###############
113. '##############################
114.
115. '***Using Descriptive Programming Child Object Method***
116.
117. 'For Web
118.
119. ' creating a description object
120. Set oDes=Description.Create
121. ' assigning description to the description object
122. oDes("micclass").value="WebButton"
123.
124. ' Flitering the objects
125. set btnObjList=Browser("name:=Google").Page("title:=Google").ChildObj
ects(oDes)
126.
127. For objIndex=0 to btnObjList.count-1
128.
' Get property value from object
129.
propVal=btnObjList(objIndex).getroproperty("name")
130.
131.
' Compare property value
132.
If propVal="Google Search" Then
133.
' Click on identified object
134.
btnObjList(objIndex).click
135.
' Exit For loop after clicking on the button
136.
Exit for
137.
End If
138. Next
139.
140. '*******************
141.
142. 'For Windows
143.
144. ' creating a description object
145. Set oDes=Description.Create
146. oDes("nativeclass").value="Button"
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
ion***
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196. '##############################
197.
198. '***By Using DOM Methods***
199.
200. ' Assigning Parent object description to constants
201. Public const gBrowser="name:=Google"
202. Public const gPage="title:=Google"
203.
204. 'Using GetElementsByName Method
205. 'Get Elements List
206. Set ElemLst=Browser(gBrowser).Page(gPage).object.getelementsbynam
e("Google Search")
207.
208. For each elem in ElemLst
209.
'Fliter Elements by Tag Name & Type
210.
If elem.tagName="INPUT" or elem.tagName="BUTTON" Then
211.
If lcase(elem.type)="button" Or lcase(elem.type)="submit" Then
212.
'Click on identified element
213.
Elem.click
214.
End If
215.
End If
216.
217. Next
218.
219. '*******************
220.
221. 'Using GetElementById Method (For this method object must have Id)
222. Browser(gBrowser).Page(gPage).object.getElementById("Google Search"
).click
223.
224. '*******************
225.
226. 'Using GetElementsByTagName Method
227. 'If the button has input tag
228. Set ElemLst=Browser(gBrowser).Page(gPage).object.getelementsbyTagN
ame("INPUT")
229.
230.
For each elem in ElemLst
231.
232.
If elem.type="BUTTON" Or elem.type="SUBMIT" Then
233.
If elem.value="Google Search" Then
234.
elem.click
235.
Exit For
236.
End if
237.
End If
238.
Next
239.
240. 'If the button has Button tag
view plainprint?
1.
'###############################################
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
'###############################################
' Deleting Rows from Excel Sheet
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open the Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get the Control on Specific Sheet
Set worksheet1=excel.Worksheets.Item("Sheet1")
'Delete Row1
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
worksheet1.Rows("1:1").delete
'Save Excel
workbook.SaveAs("D:\excel.xls")
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set worksheet1=Nothing
Set workbook=Nothing
Set excel=Nothing
Add and Delete ExcelSheet
view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
'###############################################
' Add and Delete ExcelSheet
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Existing Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Add New Sheet
Set newsheet=workbook.sheets.Add
'Assign a Name
newsheet.name="raj"
'Delete Sheet
Set delsheet=workbook.Sheets("raj")
delsheet.delete
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
31.
32.
33.
34.
Set newsheet=Nothing
Set delsheet=Nothing
Set workbook=Nothing
Set excel=Nothing
Copy an Excel Sheet of one Excel File to another Excel File
view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
'###############################################
' Copy an Excel Sheet of one Excel File to another Excel File
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open First Excel File
Set workbook1=excel.Workbooks.Open("D:\excel1.xls")
'Open Second Excel File
Set workbook2=excel.Workbooks.Open("D:\excel2.xls")
'Copy data from first excel file sheet
workbook1.Worksheets("raj").usedrange.copy
'Paste Data to Second Excel File Sheet
workbook2.Worksheets("Sheet1").pastespecial
'Save Workbooks
workbook1.Save
workbook2.Save
'Close Workbooks
workbook1.Close
workbook2.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set workbook1=Nothing
Set workbook2=Nothing
Set excel=Nothing
Comapre Two Excel Sheets Cell By Cell for a specific Range
view plainprint?
1.
'###############################################
2.
' Comapre Two Excel Sheets Cell By Cell for a specific Range
3.
'###############################################
4.
5.
'Create Excel Object
6.
Set excel=createobject("excel.application")
7.
8.
'Make it Visible
9.
excel.Visible=True
10.
11.
'Open Excel File
12.
Set workbook=excel.Workbooks.Open("D:\excel.xls")
13.
14.
'Get Control on First Sheet
15.
Set sheet1=excel.Worksheets.Item("Sheet1")
16.
17.
'Get Control on Second Sheet
18.
Set sheet2=excel.Worksheets.Item("Sheet2")
19.
20.
'Give the specific range for Comparision
21.
CompareRangeStartRow=1
22.
NoofRows2Compare=4
23.
CompareRangeStartColumn=1
24.
NoofColumns2Compare=4
25.
26.
'Loop through Rows
27.
For r=CompareRangeStartRow to(CompareRangeStartRow+(NoofRows2
Compare-1))
28.
29.
'Loop through columns
30.
For c=CompareRangeStartColumn to(CompareRangeStartColumn+(Noof
Columns2Compare-1))
31.
32.
'Get Value from the First Sheet
33.
value1=Trim(sheet1.cells(r,c))
34.
'Get Value from the Second Sheet
35.
value2=Trim(sheet2.cells(r,c))
36.
37.
'Compare Values
38.
If value1<>value2 Then
39.
40.
' If Values are not matched make the text with Red color
41.
sheet2.cells(r,c).font.color=vbred
42.
43.
End If
44.
45.
Next
46.
47.
Next
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
'Save workbook
workbook.Save
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set sheet1=Nothing
Set sheet2=Nothing
Set workbook=Nothing
Set excel=Nothing
Reading complete data from excel file
view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
'###############################################
' Reading complete data from excel file
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Excel File
Set workbook=excel.Workbooks.Open("D:\excel.xls")
'Get Control on Sheet
Set worksheet=excel.Worksheets.Item("raj")
'Get the count of used columns
ColumnCount=worksheet.usedrange.columns.count
'Get the count of used Rows
RowCount=worksheet.usedrange.rows.count
'Get the Starting used Row and column
top=worksheet.usedrange.row
lft=worksheet.usedrange.column
'Get cell object to get the values cell by cell
Set cells=worksheet.cells
'Loop through Rows
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
'###############################################
' Read complete data from an Excel Sheet content
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Open Excel File
Set workbook=excel.Workbooks.open("D:\excel.xlsx")
'Get Control on Sheet
Set worksheet=excel.Worksheets.Item("Sheet1")
'Get Used Row and Column Count
rc=worksheet.usedrange.rows.count
cc=worksheet.usedrange.columns.count
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
view plainprint?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
'###############################################
' Assign Colours to Excel Sheet Cells, Rows
'###############################################
'Create Excel Object
Set excel=createobject("excel.application")
'Make it Visible
excel.Visible=True
'Add a New work book
Set workbook=excel.workbooks.add()
'Get the Excel Sheet
Set worksheet=excel.worksheets(1)
'Coloring Excell Sheet Rows
Set objrange=excel.activecell.entirerow
objrange.cells.interior.colorindex=37
'Coloring Excell Sheet Cell
worksheet.cells(2,1).interior.colorindex=36
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
'Save Excel
workbook.SaveAs("D:\excel.xls")
'Close Work Book
workbook.Close
'Quit from Excel Application
excel.Quit
'Release Variables
Set objrange=Nothing
Set worksheet=Nothing
Set workbook=Nothing
Set excel=Nothing
UFT is called as Unified Functional Testing where all HP testing related products
are combined into it
HP Service Test used to test the web services and hence UFT will also be used to
test web services
There are lot of changes in IDE when compared with QTP. All menu options
segregated based on their usage
o
All Script Run related options like Running, Debugging, Update,
Maintenance run modes etc there in Run menu
o
Record Related options like types of recordings, recording configurations
available in Record menu
o
Script design options like inserting Steps, Synchronization, checkpoints,
comments and transaction points available in Design menu
o
HP Quality Center is also combined to HP Application Life Cycle
Management. And so we call QC as ALM
o
All ALM connecting options available in ALM menu
o
o
o
o
o
o
o
o
o
o
o
o
o
o
Changes in Checkpoints
File Content Checkpoint introduced
Using this you can verify the data in HTML, PDF, MS WORD, RTF, TEXT
Files
o
You can also use Regular expressions to verify data in those files
Product Enhancements
o
Introduced code blocks in expert view
o
enhanced the intelligence for classes, functions, environment variables
and other keywords
o
Short cut key introduced CTRL+ALT+F5 to stop the test run
o
You can use XLSX files when importing data
Finally Dont forget to watch Product Movies about new features introduced
Repositories collection object
1.
'###############################################
2.
'
RepositoriesCollection Object
3.
'###############################################
4.
5.
' Purpose:Used to Add, Remove, Find and Change Position of Shared Object Repositories of
an Action in RunTime
6.
7.
'**************************
8.
'Adding Repositories
9.
'**************************
10.
'Syntax:- RepositoriesCollection.Add RepositoryPath [, Position]
11.
12.
RepositoriesCollection.Add "D:\ProjectSuite\AutomationSuite\OR\Main.t
sr",2
13.
14.
'**************************
15.
'Find Repositories
16.
'**************************
17.
'Syntax:- Pos = RepositoriesCollection.Find RepositoryPath
18.
19.
RepositoryPosition=RepositoriesCollection.Find("D:\ProjectSuite\Autom
ationSuite\OR\Main.tsr")
20.
21.
'**************************
22.
'Move Position of a Repository
23.
'**************************
24.
'Syntax:RepositoriesCollection.MoveToPos CurrentPosition, NewPosition
25.
26.
'Get Current Position
27.
RepositoryPosition=RepositoriesCollection.Find("D:\ProjectSuite\Autom
ationSuite\OR\Main.tsr")
28.
29.
'Move to Another Position
30.
RepositoriesCollection.MoveToPos RepositoryPosition, 1
31.
32.
'**************************
33.
'Remove Repository
34.
'**************************
35.
'Syntax:- RepositoriesCollection.Remove(Pos)
36.
37.
'Get Current Position
38.
RepositoryPosition=RepositoriesCollection.Find("D:\ProjectSuite\Autom
ationSuite\OR\Main.tsr")
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
'Remove Repository
RepositoriesCollection.Remove RepositoryPosition
'**************************
'Remove All Repositories
'**************************
RepositoriesCollection.RemoveAll()
'**************************
'Count Repositories
'**************************
print RepositoriesCollection.Count
27.
' The property Index Start from '0'
Here is the script to export Object Repository to Excel.
view plainprint?
1.
'############################################
2.
'Description : Exporting Object Repository to Excel
3.
'What Concepts used : Object Repository Model, Excel Object Model
4.
'Required Parameters: Object Repository, Excel Path (Creates Excel File)
5.
'Required Software : QTP/UFT Installed
6.
'Developed By : Sudhakar Kakunuri
7.
'############################################
8.
9.
'Declare Variables
10.
'************************************
11.
Dim srcRepository
12.
Dim ParentObject
13.
Dim excel, workbooks, rIndex, objRange
14.
Dim ObjectRepositoryPath,orExcelPath
15.
'************************************
16.
17.
'Specify file Paths
18.
'************************************
19.
'OR must be created before executing this
20.
'You can use .TSR, .XML and .BDB Object Repositories
21.
'An excel file will be created automatically with the name excel.xls
22.
ObjectRepositoryPath="C:\Users\sudhakar7\Desktop\PracticeScripts\O
R\createrequest.tsr"
23.
orExcelPath="D:\excel.xls"
24.
'************************************
25.
26.
'Load Object Repository
27.
'************************************
28.
'Creating Object Repository utility Object
29.
Set srcRepository = CreateObject("Mercury.ObjectRepositoryUtil")
30.
31.
'Load Object Repository
32.
srcRepository.Load ObjectRepositoryPath
33.
'************************************
34.
35.
'Create Excel file with columns, colors and Autofit
36.
'************************************
37.
'Create Excel Object
38.
Set excel=createobject("excel.application")
39.
40.
'Add New Workbook
41.
Set workbooks=excel.Workbooks.Add()
42.
43.
excel.Cells(1,1).value="ParentObjectLogicalName"
44.
excel.Cells(1,2).value="ParentObjectProperties"
45.
excel.Cells(1,3).value="ObjectLogicalName"
46.
excel.Cells(1,4).value="ObjectProperties"
47.
48.
Set objRange = Excel.Range("A1:D1")
49.
50.
objRange.Font.Bold = True
51.
objRange.Font.ColorIndex = 1
52.
objRange.Interior.ColorIndex=15
53.
54.
' rIndex variable used to enter values row by row
55.
rIndex=2
56.
'************************************
57.
58.
'fnExportORtoExcel will get objects and properties from OR
59.
'************************************
60.
'Calling a fnExportORtoExcel Function
61.
fnExportORtoExcel ParentObject
62.
'************************************
63.
64.
'Auto Fit all other columns & save excel
65.
'************************************
66.
'Autofit all columns
67.
excel.Worksheets("Sheet1").UsedRange.Columns.AutoFit
68.
69.
With excel.Worksheets("Sheet1").UsedRange.Borders
70.
.LineStyle = 1
71.
.Color = vbblack
72.
.Weight = 2
73.
End With
74.
75.
'Save Work Book
76.
workbooks.saveas orExcelPath,true
77.
78.
'Close Work Book
79.
workbooks.Close
80.
81.
'Quit from Excel Application
82.
excel.Quit
83.
'************************************
84.
85.
'Release Variables
86.
'************************************
87.
Set workbooks=Nothing
88.
Set excel=Nothing
89.
Set srcRepository=Nothing
90.
'************************************
91.
msgbox "Exporting Completed. Open "&orExcelPath&" to view the Excel O
bject Repository"
92.
93.
'************************************
94.
95.
Function fnExportORtoExcel(ParentObject)
96.
97.
'Get Objects by parent From loaded Repository
98.
'If parent not specified all objects in OR will be captured
99.
100. Set fTOCollection = srcRepository.GetChildren(ParentObject)
101.
102.
For RepObjIndex = 0 To fTOCollection.Count - 1
103.
104.
'Get object by index
105.
Set fTestObject = fTOCollection.Item(RepObjIndex)
106.
107.
Props=""
108.
109.
'Check whether the object is having child objects
110.
If srcRepository.GetChildren (fTestObject).count<>0 then
111.
112.
113.
'Get TO Properties List
114.
Set PropertiesColl=fTestObject.GetTOProperties
115.
116.
For pIndex=0 to PropertiesColl.count-1
117.
'Store properties in a variable with a comma delimiter
118.
Set ObjectProperty=PropertiesColl.Item(pIndex)
119.
Props=Props&","&ObjectProperty.name&":="&ObjectPro
perty.value
120.
121.
Next
122.
123.
If InStr(1,Props,",")=1 Then
124.
Props=Mid(Props,2)
125.
End If
126.
127.
128.
'Write Logical name and Properties in Excel Sheet
129.
excel.Cells(rIndex,1).value=srcRepository.GetLogicalName(fTestObject)
130.
131.
132.
133.
134.
135.
136.
137.
138.
excel.Cells(rIndex,2).value=Props
'Color the cells based class name
If InStr(LCase(Props),"micclass:=browser")<>0 Then
Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)
objRange.Font.Bold = True
objRange.Font.ColorIndex = 1
objRange.Interior.ColorIndex=36
139.
ElseIf InStr(LCase(Props),"micclass:=page")<>0 Then
140.
Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)
141.
objRange.Font.Bold = True
142.
objRange.Font.ColorIndex = 1
143.
objRange.Interior.ColorIndex=35
144.
145.
ElseIf InStr(LCase(Props),"micclass:=frame")<>0 Then
146.
Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)
147.
objRange.Font.Bold = True
148.
objRange.Font.ColorIndex = 1
149.
objRange.Interior.ColorIndex=40
150.
End If
151.
152.
'increase rIndex to enter data in next lines of excel
153.
rIndex=rIndex+1
154.
155.
'Calling Recursive Function
156.
fnExportORtoExcel fTestObject
157.
158.
else
159.
'This else block will execute when the object is not having any chil
ds
160.
161.
'Get TO Properties List
162.
Set PropertiesColl=fTestObject.GetTOProperties
163.
For pIndex=0 to PropertiesColl.count-1
164.
'Store properties in a variable with a comma delimiter
165.
Set ObjectProperty=PropertiesColl.item(pIndex)
166.
Props=Props&","&ObjectProperty.name&":="&ObjectPro
perty.value
167.
Next
168.
169.
If InStr(1,Props,",")=1 Then
170.
Props=Mid(Props,2)
171.
End If
172.
173.
'Write Logical name and Properties in Excel Sheet
174.
excel.Cells(rIndex,3).value=srcRepository.GetLogicalName(fTestObject)
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
excel.Cells(rIndex,4).value=Props
'increase rIndex to enter data in next lines of excel
rIndex=rIndex+1
End if
Next
End Function
'************************************
If you use Relative Path for all the resources, the path displays
something like "..\..\QtpSudhakar\Libs\Sample.vbs". Sometimes we
may require to have full path to send it to results file or to know exact
location of the file for debugging. In this scenario to know the full path
of a resource which is associated with relative path, we have to use
below script. The script will automatically return the absolute path of a
resource which is specified with Relative Path.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
Dim QTP
Dim cLibs
Dim LibIndex
' Get Control over QTP
Set QTP=CreateObject("Quicktest.Application")
'Get All Associated Resources
set cLibs=QTP.Test.Settings.Resources.Libraries
For LibIndex=1 to cLibs.Count
' Using PathFinder object locate and display the Absolute path
msgbox PathFinder.Locate( cLibs.Item(LibIndex))
Next
'***************************************************
'How to popup a message with some wait
'***************************************************
Set WshShell = CreateObject( "WScript.Shell")
WshShell.Popup "message body", 5, "Title"
'***************************************************
'How to get the current UserName of logged in
'***************************************************
Set WshNetwork = CreateObject( "WScript.Network")
userName = WshNetwork.username
Set WshShell = CreateObject( "WScript.Shell")
WshShell.Popup userName , 50, " userName "
'***************************************************
'How to send keyboard inputs to application
'***************************************************
set WshShell = CreateObject( "WScript.Shell")
WshShell.SendKeys "QuickTest Professional"
'***************************************************
'How to get the value of the system environment variable
'***************************************************
Set WshShell = CreateObject( "WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM" )
WScript.Echo WshSysEnv("NUMBER_ OF_PROCESSORS" )
'***************************************************
'How to write and read registry
'***************************************************
31.
Set WshShell = CreateObject( "WScript.Shell")
32.
WshShell.RegWrite "HKCU\Software\ ACME\FortuneTell er\", 1, "REG_BINARY"
33.
WshShell.RegWrite "HKCU\Software\ ACME\FortuneTell er\MindReader" , "Goocher
!", "REG_SZ"
34.
bKey = WshShell.RegRead( "HKCU\Software\ ACME\FortuneTell er\")
35.
msgbox WshShell.RegRead( "HKCU\Software\ ACME\FortuneTell er\MindReader" )
36.
37.
'***************************************************
38.
'How to execute DOS commands
39.
'***************************************************
40.
Set oShell = CreateObject ("WSCript.shell" )
41.
oShell.run "cmd /K CD C:\ & Dir"
42.
'***************************************************
1.
Vartype
2.
Typename
Return Value
Sub
vbEmpty
vbNull
vbInteger
vbLong
vbSingle
vbDouble
Description
Datatype
Empty (uninitialized)
Null (no valid data)
Integer
Long integer
Single-precision floatingpointnumber
Double-precision floating-point
number
vbCurrency Currency
vbDate
Date
vbString
String
vbObject
Automation object
10
vbError
Error
11
vbBoolean Boolean
12
vbVariant
13
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.
Byte value
Integer
Integer value
Long
Single
Double
Currency
Currency value
Decimal
Decimal value
Date
String
Boolean
Empty
Unitialized
Null
No valid data
Generic object
Unknown
Nothing
Error
Ex:
Dim x
x=10
msgbox typename(x) 'Returns Integer
There are some more VBScript Built-in functions to find whether a
variable datatype is specific datatype or not.
IsArray Returns a Boolean value indicating whether a variable is an
array or not.
IsDate Returns a Boolean value indicating whether an expression can
be converted to a date.
IsEmpty Returns a Boolean value indicating whether a variable has
been initialized.
IsNull - Returns a Boolean value that indicates whether an expression
contains no valid data (Null).
IsNumeric - Returns a Boolean value indicating whether an expression
can be evaluated as a number.
IsObject - Returns a Boolean value indicating whether an expression
references a valid Automation object.
Built in functions are available for only these datatypes. You can write
built function for every datatype like below
'*******************************
Function IsString(oValue)
If vartype(oValue)=8 then
IsString=true
Else
IsString=False
End If
End Function
'*******************************