Blog to understand automation concepts in QTP, Selenium Webdriver and Manual Testing concepts

Reporting in QTP - Reporter Object

When we run a test in QTP, QTP generates a report based on inbuilt native reporting for steps  defined in QTP. To add user defined results, we have reporter object in QTP.
Below are the properties  and methods  of reporter object which will be described in details below.

Reporter.Filter Property 

Retrieves or sets the current mode for displaying events in the Test Results. You can use this property to completely disable or enable reporting of steps following the statement, or you can indicate that you only want subsequent failed or failed and warning steps to be included in the report.

Reporter.filter = FilterValue.


Filter value can be
·         0 or rfEnableAll – Default , all reporting events are displayed.
·         1 or rfEnableErrorandWarnings – only error and warning events are displayed.
·         2 or rfEnableErrorsOnly – Only errors are displayed.
·         3 or rfDisableAll – No event are displayed in results.

Reporter.ReportEvent Method

Reports an event to the results

Syntax: Reporter.reportEvent  eventstatus, reportStepName, Details,[Image]


EventStatus can have value 0, 1,2,3 or micPass,micFail, micDone, and micwarning.
reportStepName Name of the steps
Details – Details of execution.
Image – Path of imagefile to be attached for event.

Reporter.ReportPath property

 This retrieves the folder Path in which current test results are saved.

Reporter.RunStatus property

Retrieves the run status at the current point of the run session. For tests, it returns the status of current test during the test run.


Working with DataBase in QTP - Understanding Connection and Recordset object

QTP Interacts with database creating an instance of ADODB object using ADO. ADO is a Microsoft technology and stands for ActiveX Data Objects and is a programming interface to interact and access data from a database.

Connection Object


Before a database can be accessed by QTP, An object for database connection has to be established.

Set adocon = createobject(“Adodb.connection”)

Once the object is created, we need to set connection string to connect to the database. We can define a connection string with details of database including database provider, database, and user credentials for access.

Some useful methods and properties of connection object are as follows:


Properties:


adocon.connectionstring – This property sets or returns the details used to create a connection to a data source. Includes details of driver, database,username and password.


Strconnection = "Driver=… "Server=svrnme;uid=username;pwd=password;"
For e.g to connect to a database for excel the strConnection would be like:
 strcon = "Driver={Microsoft Excel Driver (*.xls)};Dbqls="+xfilename +";ReadOnly=0;"

For details of connection strings, see www.connectionstrings.com

adocon.ConnectionTimeout – this defines the time  to wait for a connection to be established.


adocon.provider – This sets or gets connection provider name.


adocon.state – gives status whether connection is on or off.


Methods


adocon.open – opens a database connection based on the connection string provided. 

adocon.Open connectionstring,userID,password,options


adocon.Execute – execute the sql statement provided

adocon.execute “Select * from table”

adocon.close – This closes the adodb connection.


RecordSet Object:

 Once a connection has been established, we can create recordset object to hold a set of record from database. A recorset consists of records and column

Set rs = createobject(“”Adodb.recordset”)

Some useful methods and properties of RecordSet Objects are as follows:

Properties:


BOF property returns True  if the current record position is before the first record in the Recordset,



EOF property returns True if the current record position is after the last record in the Recordset, otherwise it returns False. For a empty recordset,i.e no records in the recordset or empty recordset, value of BOF and EOF is false. So the property can be used in a loop to validate RecordSet does not return any records.


MaxCount Property returns the maximum value of records to be returned in a recordset.
rs.MaxCount = 20 will return 20 rows of data in recordset.


Methods:


rs.cancel – cancels an existing execution.


rs.clone – returns a clone of existing recorset and assigns to an object

set rsclone = rs.clone


rs.Close - closes instance of recordset


rs.open – opens a recordset based on query specified.

rs.open sqlquery, adocon

where sqlquery is query executed and adocon is connection object.

rs.move – moves the pointer in a recordset by specified count as defined in numrec
rs.move numrec, start.

Also  movenext,moveprevious, movefirst, movelast can be used to move to specified location in recordset.


rs.fields.count gives number of items in the fields collection.


rs.field.item(i) returns specified item from the collection.




Guidelines and features of different Automation frameworks in QTP

Definition :

A test automation framework is a set of assumptions, concepts and tools that provide support for automated software testing. An Automation Framework is a set of guidelines that you can follow during test case scripting to achieve successful automation results and high return on investment.

Guidelines in creating the automation framework:


1.  Select the tool to be used for test automation
2.  Select type of automation framework to be implemented in the automation based on project complexity and the tool.
3.  Define folder structure to be used for Object repositories, function libraries, test script, test data and other artifacts to be used for interaction.
4.  Validate proper interaction between various resources used in the framework.
5.   Define a driver script to execute test in batches.
6.   Define proper test results reporting to be used in automation.
7.   Define proper error handling and recovery scenarios to be implemented.
8.   Validate functions are created with proper coding standards and ensure high reusability in the framework.

Salient Features


Salient features of good automation framework are as follows:

  • High reusability of automation framework. Functions, structure used in framework should be reusable and easy to implement during script preparation.
  • Maintenance of the framework should be easy and easy to understand for new user.
  • Framework should ensure minimum effort from end user during script execution.
  • Test Results should be self explanatory.
  • Framework should be be able to run scripts smoothly without any issues and proper error handling should be defined in framework.
  • Automation Framework should be robust with good exceptional handling.
  • Automation Framework should be reliable.
  • Automation framework should be application independent.
  • Return on investment should be high in long run for automation. Framework should be choosen and created in such a manner to ensure high ROI.


Types of Automation Framework


Following are the types of Automation Frameworks.

1. Linear Framework:

     Linear scripts are created with steps written in a linear manner. Steps are recorded in this framework using record- play mechanism. This framework does not require any automation expertise as steps are recorded by record and play method.  This is useful for stable application with only a few tests with the same set of data as data is hard coded in this method.

2. Modular or function decomposition Framework:

In this approach test scripts  are first analyzed to find out the reusable flows. Steps for these flows are grouped together to create functions. Still test data is hard coded in this framework although reusability is improved.

3. Data Driven Framework:

      In Data driven framework data is stored in external files in the form of excel file, text files, database. Test data interacts with code through the external file. Since data is stored in an external file, test can be run with multiple set of data without any change in the code.

4. Keyword Driven Framework: 

      In Keyword Driven Framework we create a set of Keywords & Data Tables, the entire functionality of application gets captured as step by step instructions for every test. We create different keywords and associate different actions with these keywords in this framework. Once framework is prepared, it is much easier to implement using keywords defined.

5. Hybrid Framework:  

      This framework  is created by combining different features of different frameworks  and creating a framework with required features of the framework discuss like creating reusable functions, using data driven techniques and defining keywords all in the same framework.

6. BPT Framework:

      Business process testing framework divides test case flow into multiple Business Components. These business component are reusable and can be used in different tests to create workflow and business tests. This framework is maintained in quality center and requires QC to create framework and execute.


RegExp Object for regular expression using VBScript in QTP

VBScript provides a RegExp object to handle regular expressions.This object allows you to find regular expression matches in strings, and replace regex matches in strings with other strings.

Properties of RegExp Object

Following are the properties of regexp object:

IgnoreCase:  By default regular expression is case sensitive, to make it case insensitive, set value as “True”

Pattern: We can define the pattern of regular expression in the pattern property. Pattern can include literal and meta characters like .,*,/d as discussed in the earlier post on how to create regular expressions in QTP

Global: To return or replace all matches, set Global as True. If set as False, finds the first match only


‘’Defining a regular expression
Set newRegExp = New RegExp
newRegExp.IgnoreCase = True
newRegExp.Global = True
newRegExp.Pattern = ".*an"

Methods of RegExp object


Execute method: executes a match against the specified string. Returns a Matchescollection, which contains a Match object for each match. The Matchobject can also contain SubMatches collection. 

Execute method has following properties:

o    Item

       §  Item.value – value of item in the collection
       §  Firstindex – First instance of match location

o    Count

Count of instances matching the regular expression

Replace method: replaces the part of the string found in a match with another string.Does replace the pattern defined for object with the replace value.                                          Syntax: regExpobj.replace(teststring,”newpattern”)

Test method: executes an attempted match and returns True or False based on match found.


Sample Code explaining properties and methods of RegExp Object.


Set newRegExp = New RegExp
newRegExp.IgnoreCase = True
newRegExp.Global = True
newRegExp.Pattern = ".*an"
testString = "this ant is an insect"
Set colmatch = newRegExp.Execute(teststring)
For each match in colmatch
         msgbox match.Value
        msgbox colmatch.count
Next
boolMatch = newRegExp.Test(teststring)
msgbox boolMatch
newRegExp.pattern ="a"
strString = newRegExp.replace(teststring,"b")
msgbox strstring


To understand more on how to use regular expressions in qtp, click here


Useful VB Script Functions for QTP - String, Date, Array and Control flows

String Function:


Len: Returns the number of characters in a string or the number of bytes required to store a variable. 

Len(str)    
   

LCase:  Returns a string that has been converted to lowercase.


Ucase:  Returns a string that has been converted to uppercase.


Left: Returns a specified number of characters from the left side of a string.

Left(str,Length)

Right: Returns a specified number of characters from the right side of a string.

Right(str,Length)

Mid: Returns a specified number of characters from a string.

Mid(txt,start,[length])

Replace: Replaces string with another string

Replace(expression, find, replacewith[, start[, count[, compare]]])

Space: Returns a string consisting of the specified number of spaces.

Space (number)

Split: Returns a zero-based, one-dimensional array containing a specified number of substrings.

Split(expression[,delimiter[,count[,compare]]])

StrComp: Returns a value indicating the result of a string comparison. 

StrComp(string1,string2[,compare])

StrReverse: Returns a string in which the character order of a specified string is reversed.

strReverse(string)

LTrim; RTrim; and Trim: Returns a copy of a string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim).

Trim(str)
LTrim(str)
RTrim(str)

InStr: Returns the position of the first occurrence of one string within another.

InStr([start,]string1,string2[,compare])

InStrRev: Returns the position of an occurrence of one string within another, from the end of string. 

InStrRev(string1,string2[,start[,compare]])

Array Functions:


IsArray: Returns a Boolean value indicating whether a variable is an array.

IsArray(variable)

UBound: Returns the largest available subscript for the indicated dimension of an array.

UBound(arrayname[,dimension])

Join - The Join function returns a string that consists of a number of substrings in an array.

Join(list[,delimiter])


Date Functions:

Date: Returns the current system date.

Time: Returns a Variant of subtype Date indicating the current system time.


DateAdd: Returns a date to which a specified time interval has been added. 

DateAdd (interval, number, date): internal can be ‘yyyy’, ‘dd’,’mm’


DateDiff: Returns the number of intervals between two dates. 

DateDiff("yyyy","September 01, 2012","September 01, 2010")



DatePart: Returns the specified part of a given date. 

DatePart("yyyy","May 01, 2012") 


Day: Returns a whole number between 1 and 31, inclusive, representing the day of the month. Day(date)


Month: Returns a whole number between 1 and 12, inclusive, representing the month of the year.


MonthName: Returns a string indicating the specified month.


Weekday: Returns a whole number representing the day of the week.  

Weekday ("November 03, 2010") 


WeekdayName: Returns a string indicating the specified day of the week. 

WeekdayName (4)


Year: Returns a whole number representing the year.


Hour: Returns a whole number between 0 and 23, inclusive, representing the hour of the day


Minute: Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.


Second: Returns a whole number between 0 and 59, inclusive, representing the second of the minute. 


Now: Returns the current date and time according to the setting of your computer's system date and time.


Control Flows:

Do...Loop: Repeats a block of statements while a condition is True or until a condition becomes True.


For...Next Statement: For...Next: Repeats a group of statements a specified number of times.


For Each...Next: Repeats a group of statements for each element in an array or collection.


If...Then...Else: Conditionally executes a group of statements, depending on the value of an expression.


Select Case: Executes one of several groups of statements, depending on the value of an expression.


While...Wend: Executes a series of statements as long as a given condition is True.


With: Executes a series of statements on a single object.


Understanding Extern, Crypt and Environment Utility objects in QTP

In this post, We  will discuss about following utility objects in QTP.

Crypt Object
Environment Object
Extern Object


1. Crypt Object 


 Crypt object is used to encrypt the string. An encrypted string is generated for the provided string during Crypt.Encrypt method. This is useful for providing Password details and entering data in a field as setsecure.

Syntax : crypt.encrypt(strPass)


If we want to use this method through VBScript, we can create an instance of object using

Set crypt= CreateObject("Mercury.Encrypter")


2. Environment Object


Environment Object enables QTP to retrieve information  from the environment variables defined in QTP, Add new environment variables, and loading environment variables from external file.

Below are described the properties and method for Environment object.


Environment.value(EnvName) = EnvValue  will set the value of environment variable EnvName as EnvValue.


envVal = Environment.value(EnvName) will get the value of environment variable envName in variable envVal.


Environment.ExternalFileName will returns the ExternalFileName associated with the test.Will return “” if no externalfile is associated.


Environment.LoadFromFile(FileName) will load external user defined environment variables from the file specified.


3. Extern Object


By defining methods using extern object in QTP, we can call functions from external libraries. This is very useful to run functions from external DLL’s.

Using Extern Object

a. Declare Extern defintion

The syntax for declaring an extern object is as follows:

Extern.Declare micHwnd,UserProcedureName,DLLName,ProcedureinDLL, micString, micint


The above declaration declares user defined procedure UserProcedureName from procedure ProcedureinDLL in the DLL specified in DLLName. Next arguments are the datatype of various argument to be used when calling the procedure defined in extern.declare.


e.g : Extern.Declare micLong, "InternetOpen", "Wininet.dll", "InternetOpenA", micString, micDWord, micString, micString, micDWord will call InternetOpenA procedure from DLL  “Wininet.dll” on calling the method “InternetOpen”.Similarly other procedure from DLL can be declared using extern.declare.


b.Using procedure defined in Extern.declare

 Once we have defined the procedures using Extern.declare, we can call as shown below:

objIEOpen= Extern.InternetOpen("QTP_FTP", 1, vbNullChar, vbNullChar, 0).

Note we have to provide arguments with data type as defined during extern declaration above.
This will execute the procedure in DLL as specified in extern.declare.


QCUtil - utility object in QTP for QC- QTP intregration


In this tutorial, We will discuss about QCUtil - utility object in QTP for QC- QTP intregration. Will discuss various properties of QCUtil Object in this post. Hope this information is useful for QC-QTP integration.

QCUtil Object 

QCUtil Object is used to access QC OTA.
Below are the properties of QCUtil object that can be used for extracting information from QC.

Properties of QCUtil Object


1. QCUtil.CurrentRun:  This give reference to the current test run in QC.We can then get  information of currentrun  like name as shown below:


set objRun = QCUtil.CurrentRun
msgbox objRun.Name

2. QCUtil.CurrentTest: This give reference to the current test in QC. We can extract information like name of the test, adding attachment to current test using this property


set objTest = QCUtil.CurrentRun
msgbox objTest.Name

3. QCUtil.CurrentTestSet: This give reference to the current test set in QC. We can  extract information similar as above for testset using this property.


set CurrentTSTest = QCUtil.CurrentTestSet

4. QCUtil.CurrentTestSetTest: This gives reference to current test execution instance in the testset.


set CurrentTSTestSet = QCUtil.CurrentTestSetTest

5. IsConnected Property: returns true/false based on QTP currently connected to QC project.


blnQCsts = QCUtil.IsConnected

6. QCConnection Property: This gives an instance of current run session and can access the structure of QC using this property


Set QCConnection = QCUtil.QCConnection


Examples of working with QCUtil Object


1.Adding a defect in QC using QCUtil Object:


            ‘Create instance of QCConnection
            Set QCConnection = QCUtil.QCConnection
‘Create an instance of BugFactory
Set DefFactory = QCConnection.BugFactory
'Add a new defect
Set Bug = DefFactory.AddItem(Nothing)
‘Provide mandatory details for the defect
Bug.Status = “New”
Bug.Summary = “Module Detected new defect summary”
Bug.DetectedBy = “njoshi”
Bug.AssignedTo = “dev001”
Bug.Post
Set DefFactory = nothing
Set QCConnection = nothing.

2. Adding Attachment to QC 


Dim ObjCurrentTest,ObjAttch
‘ We can add attachment to currentTest, current run, testset, and testsettest by using repective ‘properties 
Set ObjTest = QCUtil.CurrentTest.Attachments
Set ObjAttachFile = ObjTest.AddItem(Null)
ObjAttachFile.FileName = FileName ‘ Provide path of the file that needs to be attached to QC 
ObjAttachFile.Type = 1
ObjAttachFile.Post
ObjAttachFile.Refresh

3. Validating If QC is connected properly: 


if QCUtil.IsConnected then
msgbox “QC is connected”
Else
Msgbox “QC is not connected”
EndIf
   

4. Connecting to QC through QTP


Set qtApp = CreateObject ("QuickTest.Application")
If  qtApp.launched <> True then
     qtApp.Launch
End If
qtApp.Visible = "true"
If Not qtApp.TDConnection.IsConnected Then
      qtApp.TDConnection.Connect QCurl, DomainName, ProjectName, UserName, Password, False
End If