Вы находитесь на странице: 1из 13

Database CheckPoint and QTP – Part1

Today almost all the software applications use relational database management
systems (RDBMS) to provide persistency to the program. An RDBMS used in
application could be the Oracle, SQL, Access, MySQL etc which depends on the
requirement of the software program. Testing the functionality of a database is one of
the most challenging tasks for software tester.

In this part of series we will discuss how we can use database checkpoint in QTP and
in the later parts we will understand the key concepts and how to connect to a
database using QTP scripting and how we can retrieve data from the database and
other important facts. As a good tester you must have basic knowledge of writing
query and verify its correctness based on the parameters. For this you will need to first
understand the database of the application under test, which includes understanding
the referential integrity, security, and data formats.

The most important Referential Integrity is basically the schema of the database- a
visual diagram of all the tables in your database, which you can get from your
development team. This is very important as it provides you all the basic information
about your database like how the integrity has been maintained, table information,
risks etc. Once you have knowledge on all the intricacies of the database you can
begin with your testing.

While automating, the very first thing you may face is to connect to the database. Let
us first understand the database Checkpoint. Database checkpoint is one of the
checkpoints in QTP which is used to test the contents of the database accessed by
application under test. It stores the expected data and compares this with the data
stored in the database. When you use a database checkpoint in your script, it connects
to the database and sends the query to the database to retrieve the current data into the
record set. QTP now compares the current data with the expected data stored in the
checkpoint and gives you the result as pass or fail. You can create a database
checkpoint to confirm that the data being stored in the database does not introduce
any error and you can do this by verifying

• The data is saved to the correct tables and in proper field


• The data on different operation in database like insert, delete, update
• The correctness of data etc.
To understand this lets take a very simple example for Flight Application. Suppose
you are updating an order by changing the name, as in the snapshot below. You need
to change the customer name to Learnqtp now and update the record. So if you want
to verify whether the record is properly updated with the changed name or not, you
use the database checkpoint.

To create a database checkpoint in QTP following steps should be followed – Insert


statements to update the record in your Script.

1. Go to Insert > Checkpoint > Database Checkpoint. You will see a database
query wizard.
2. Select either of the two option there
o Create query using Microsoft query – Select this if you want to use
Microsoft query.
o Specify SQL statement manually – Select this to manually provide the
sql query to the database. We will use and go with this option now.
Click ‘Next’ once you selected the query definition.
3. Click ‘Create’ button, which will open the data source window, Select
‘Machine Data Source’ and click new. ( To Connect to flight application
database there is already a data source as QT_Flight32, we can directly select
this press ‘OK’ and jump to step 7)

4. Create New Data Source window opens, Select the type of data source and
click Next
5. Select the Driver depending on the database type from the list. For example if
your database is SQL – select ‘SQL Server’, for Oracle – select ‘Microsoft
ODBC for Oracle’ and follow the onscreen wizard with the details of your
database like server name database name etc. Finally Test the connection and
press ‘OK’
6. You will see the data source name just created in the list at Machine Data
source. Select and Click ‘OK’
7. Specify your sql query e.g. for above mentioned example – ‘Select
Customer_Name from Orders’. Click Finish
8. It will Open the Database Checkpoint Properties, modify your checkpoint
settings, enter the expected data and Click ‘OK’
It will add a line in the expert view as:

DbTable("DbTable").Check CheckPoint("DbTable")

When you will run the script QTP will check the database whether the record is
updated with the customer name or not and will give you the result as pass or fail.
DbTable is the database table object, which has following properties and methods
associated with it.

• Exist Property –checks whether the database table exists


• GetToProperty method – is the same method used for test objects to get the
specified identification property.
• SetToProperty method – is to set the specified identification property.

There could be three identification properties of a database table object – Source,


dbuniqueid and connectionstring. So we can parameterize the database checkpoint
using these properties and methods, for example if you want to use the same
checkpoint to run for more query use the ‘SetToProperty’ method to set the source of
the DBTable. Following example illustrates above methods

If DbTable("DbTable").Exist (0) Then


Print " Current query : " & DbTable("DbTable").GetTOProperty
("Source")
DbTable("DbTable").SetTOProperty "Source", "Select * from Orders"
Print " Modified query : " & DbTable("DbTable").GetTOProperty
("Source")
End If

Result

Database Checkpoint and QTP Part2 – Using Scripts

In the earlier part of this series we have learnt how to use database checkpoint in
database testing. If you don’t want to use the database checkpoint in your database
testing, you will have to script it to connect to database and test the records. This
gives you more flexibility and options to play around the records. Let us see how we
can connect to a database using QTP through scripting.

• ActiveX Data Objects (ADO) is COM objects which can be used to gain
access to a database through QTP. While using ADO you will need to
understand three objects
• Command– Command object is like a container for a command which you
send to the database to do some actions. Mostly a sql statement is used as a
command to the database.
• Connection – Connection object is the link between QTP and the database.
For any operation you will need to open the connection link initially and make
sure you have closed the link once you are done. It requires a connection
string to initialize the properties needed to connect to a db .
• RecordSet – RecordSet object is the container for the command results. The
container is called as the cursor. A cursor is like a temporary table in the
memory which contains all the characteristics of a table like rows, columns,
record pointers etc. This is the object on which plays significant role in your
test.

To connect to the database, you will need to use CreateObject method to get the
object

Set MyConnection = CreateObject(“ADODB.Connection”)

Next you will need to pass the connection string to the connection object. The
connection string is created using certain keywords and values in it depending on the
database you need to connect. The keyword Provider (identifies the OLE DB provider
to be used.) is used in almost all type of connection and other keywords depends on
the database you are connecting. [Note From Ankur: You can use the site
ConnectionStrings to build strings corresponding to your database.]
A typical connecting string for database connection will be like –

Access

Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\mydatabase.mdb;User Id=admin;Password=;

Access 2007 –

Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security
Info=False;

SQL Server

Provider=sqloledb;Data Source=myServerAddress;
Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Oracle

Provider=msdaora;Data Source=MyOracleDB;
User Id=myUsername;Password=myPassword;

Once you have the connection string you can now open the connection using Open
method of Connection object

MyConnection.Open “Provider=sqloledb;Data Source=myServerAddress;


Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;”

That is all and now QTP is linked with the database. Now we need to pass the
required command and verify the data.

Below is a generalized function to connect to DB

Function 1

Function getConnection ()

On Error Resume Next


Dim oConnection,ConnectionString
ConnectionString ="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Program Files\HP\QuickTest
Professional\samples\flight\app\flight32.mdb;
User Id=admin;Password=;"

Set oConnection = CreateObject("ADODB.Connection")


oConnection.Open ConnectionString
Set getConnection = oConnection

End Function

The function creates a new connection session to a database using the connection
string passed. Connecting can be set as per the requirement.
Let us see how we can connect to the database of flight application. The database for
sample application is an Access Database located at “C:\Program
Files\HP\QuickTest Professional\samples\flight\app\flight32.mdb”. To connect to this
database we will need to create a connection string for Access which is used in the
above function.

Example 1 illustrates the usage of function mentioned above.

Example 1

Dim MyConnString, MyConnection


Set MyConnection = getConnection
If MyConnection.Errors.Count = 0 then
msgbox "Database Connected"
Else
msgbox Err.Description
End If

If you are having difficulties using connection string, don’t worry you can create the
connection using Data Source Name as well.

To create the DSN Click Start, Control Panel, Administrative Tools, and then
double-click Data Sources(ODBC). On the user DSN tab, click Add. And follow rest
of the wizard. Now in place of the connection string you need to have the DSN that
you provide while creating.

Connect to flight application database using already created DSN

Example 2

ConnectionString = "QT_Flight32”
Set oConnection = CreateObject("ADODB.Connection")
oConnection.Open ConnectionString

In the same you can now connect to any database using the connection. Note that for
connecting to Oracle database you need have the TNS Setup located in your
tnsnames.ora. the file can be found at “<Oracle Client Installation folder>
\network\admin”. And use the TNSname as the Datasource in your connection string.

A typical tnsnames.ora content will be like

YourTNSName =

(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = <YourServerNameOrIP>)(PORT =
<YourPortOrDefault1521>))
)
(CONNECT_DATA =
(SID = <YourDBSID>)
(SERVER = DEDICATED)
)
)
Use ‘Close’ method to close the connection.

MyConnection.Close

Database Checkpoint and QTP Part 3 – Retrieving Data

In Part1 we saw the wizard method to use Database checkpoint. In Part2 we learned
how to connect to a database using scripts in QTP. In this part we will see how we can
retrieve data from database using scripts.

Similar to connection object, you can use ADODB.Recordset to get the recordset
object.

Set MyRecordSet = CreateObject("ADODB.Recordset")

Before starting let us first understand the properties and methods of recordset object
which will help further.

RecordSet Properties Description


AbsolutePage Page of current position
AbsolutePosition Current position
ActiveConnection Active Connection Object
BOF Beginning of File
Bookmark Bookmark of current position
CacheSize Number of records cached
CursorLocation Server or Client
CursorType Forward, Static, Dynamic, Keyset
EOF End of File
EditMode Whether or not an edit is in progress
Filter What kind of records to hide
LockType Record lock type for edits or updates
MaxRecords Maximum number of records to retrieve
PageCount Total number of pages
PageSize Number of records per page
RecordCount Total number of records
Source Source Command Object
Status Status of last action
Recordset Methods Description
AddNew Add a new record to the RecordSet
CancelBatch Cancel pending batch updates
CancelUpdate Cancel pending update
Clone Copy the RecordSet
Close Close the RecordSet
Delete Delete current record
GetRows Retrieve multiple records
Move Move the record pointer to a specific record
MoveNext Move the record pointer to the next record
MovePrevious Move the record pointer to the previous record
MoveFirst Move the record pointer to the first record
MoveLast move the record pointer to the last record
NextRecordSet Load the next RecordSet in a multi-set query
Open Open the RecordSet (execute the query)
Requery Re-execute the last query executed
Resync Synchronize the data with the server
Supports Determine if a feature is supported by provider
Update Update the current record
UpdateBatch Update pending batched record updates

Don’t worry if you feel this listing is too big, you may never use many of these, all
this is for your reference in case you need. The most commonly used property and
functions are:

• EOF – to identify no records returned. You run a query and need to determine
the pointer is at last record or not or no records has been returned.
• Open – To retrieve the RecordSet we use open method which requires two
arguments – connection object and command object

Syntax for this would be

<RecordSetName>.Open source, connection, cursor, lock, type

• Source – is actually the command object, it could be a sql statement


• Connection – is the connection object connecting the database
• Cursor – optional parameter to define recordset cursor type (default – Forward
only)
• Lock – optional parameter to set the lock type property(default – Read Only)
• Type – optional parameter to define the command type (default unknown(8))

For example

Set oRecordSet = CreateObject("ADODB.Recordset")


oRecordSet.Open “Select * from Orders”,oConnection, adOpenStatic

here oConnection is connection session to the database , we have used the static
cursor which allows us to open the record in readonly mode, and not used a lock type
– so it will use the default lock.

a generic function for retrieving the recordset would be like

Function 2

Function getRecordset(strSQL)
Dim oConnection, oRecordSet
Set oConnection = CreateObject("ADODB.Connection")
Set oRecordSet = CreateObject("ADODB.Recordset")
oConnection = getConnection()
oRecordSet.Open strSQL,oConnection, adOpenStatic Set
getRecordset = oRecordSet
End Function

Let us now try this to retrieve data from Orders table of Flight application database.

To get the customer name from table Orders with Order Number 1 will need to
execute the query –

Select * from Orders where Order_Number = 1

Example 2

Set MyRecordset = getRecordset("Select * from Orders where


Order_Number = 1")

If MyRecordset.EOF <> True Then


msgbox MyRecordset.Fields("Customer_Name").Value
End If

Result

In this example we are using the function 2 by passing the required query and we get
the result recordset in the MyRecordset object. Then we are checking whether there is
some records there or not using the EOF property.

In the same way we can use other methods as well for different operations

Move to next record – We have a method MoveNext which we can use in a loop until
the max record in recordset. Below example illustrates the use of this method to get
all the records from table

Example 3

Set MyRecordset = getRecordset("Select * from Orders")

Do while MyRecordset.EOF <> True


print MyRecordset.Fields("Customer_Name").Value
MyRecordset.MoveNext
Loop

Result
In the same way you can use other methods and properties of RecordSet object to
achieve your task. I have listed her some example which you may encounter in your
test.

Function 3 – Number of Records We can traverse through all the records in the
recordset to get the number of records in recordset.

Function getRecordCount(ByRef RecordSet)


Dim Rows
Rows = 0
RecordSet.MoveFirst
Do Until RecordSet.EOF
Rows = Rows+1
RecordSet.MoveNext
Loop
getRecordCount = Rows
End Function

Function 4 – Execute Query

If you need to update, insert or delete records from database, you can use this
function. But if you are working on the database for application under test, you should
not perform such actions until unless it is required or a database used for QTP.

Function ExecuteQuery(strSQL)
On Error Resume Next
Set oConnection = CreateObject("ADODB.Connection")
oConnection = getConnection()
oConnection.Execute strSQL
If Err.Number <> 0 then
ExecuteQuery = False
Exit Function
End If
ExecuteQuery = True
End Function

Example 4 – Retrieve the column names from a table

Set MyRecordset = getRecordset("Select * from Orders")


nColumns = MyRecordset.Fields.Count
For n = 0 to nColumns - 1
Print MyRecordset.Fields(n).Name
Next

Example 5 – Import Database Table into Data table

‘ Get recordset
Set MyRecordset = getRecordset("Select * from Orders")
‘Get number of columns in table
nColumns = MyRecordset.Fields.Count
‘Add a sheet in your datatable
Datatable.AddSheet ("DBImport")
For n = 0 to nColumns – 1
‘Get column name
ParamName = MyRecordset.Fields(n).Name
‘Add DTParameter
Datatable.GetSheet("DBImport").AddParameter ParamName,""
nRow = 1
MyRecordset.MoveFirst
‘Retrieve and place data in data table
Do while MyRecordset.EOF <> True
Datatable.SetCurrentRow(nRow)
Datatable(ParamName,"DBImport") =
MyRecordset.Fields(ParamName)
nRow = nRow + 1
MyRecordset.MoveNext
Loop
Next

Apart from this, if you need to connect to a excel file using ADODB connection, you
will have to specify a different connection string, which will be like

" DRIVER={Microsoft Excel Driver (*.xls)};DBQ= FileName


;Readonly=True

Вам также может понравиться