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

How to create a Hybrid Framework in QTP

A hybrid Framework is a framework that uses features of multiple frameworks and is more robust. For e.g, we can create data in external files as in data-driven approach, or creation of keywords as in keyword driven framework. 


Before understanding what needs to be a part of hybrid framework, it is necessary to know what are essential requirements of a framework, Below are the points that needs to be considered before creating a framework.

1. Identify where Test Artifacts needs to be maintained 


Test Artifacts can be maintained in test management tools like Quality Center or can be stored in a shared repository. Using a test management tool, For e.g HP ALM provides following features 

  •  Version controlling of test scripts, function libraries, Object repository, recovery scenario and test data
  •  Multiple Users can at the same time can access the resources in tool.
  • Option to run  set of tests and defining the execution flow can be done using test management tool.


In case of test management tool not available, Test Artifacts should be maintained in a shared folder, so that multiple user can have access to the  resources. In this case, we will require a driver script that will execute multiple test script in a batch and also can be scheduled.

2. Object Identification


Objects Identification is very important and can be identified in number of ways. Some of them are as follows

  • Using Object Repository
  • Using Descriptive Programming
  • Using HTML dom.
  • Using XPath/CSS

A hybrid approach can use a mix of various object identification techniques and can maintain object of different types in different vbs files which can be executed during test initialization.

3. Error Handling and Recovery Scenario


For expected errors, error handling should be implemented in the code and recovery scenario can be used to avoid interruption in test script execution.Code should have enough error handling defined.

4. Reporting


For each failed/passed step in test script execution, reporting in QTP results or user defined html results should be done. Reporting should not be direct using reporter.reportevent but should be wrapped in a function with arguments defined for taking screenshot or exiting the test based on flag status of the argument.

5. Test Data Management


Test data is an important factor in hybrid framework design. Preparation of test data should take into considerations factors like:

  • What are the validations required for test data preparation in fields
  • Can any random data be entered in the fields.
  • How much data is required. e.g bulk data required to execute scripts for multiple iterations.
  • What will be the source of data. Data can be stored on an excel file or can be imported from database at run time if specific existing data is required.
  • In case of large data requirement, test data generation tools like GenerateData can be used.

6. Libraries Management


For each test script execution, An initialization library should be called at the start of script execution which should load the required environment variables, object repositories and other function libraries with application specific code.
Similarly before exit from test script execution, function to close all process that were called during script execution should be executed. Also Code should have enough error handling and reporting, minimum hard code data, and should follow standing coding practices

How to capture images and create movie to be saved with QTP

QTP provides options to captures images and record movies of test script execution. User can define the setting for image Capture and screen recorder before test script execution. 

To define settings for images capture and screen recorder, Navigate to Tools>Options>Run>Screen Capture.

Click on Checkbox to save still image captures to results or click on checkbox for save movies to results.


Select whether to save images/capture movies always or only for error as shown below.



Settings for Screen capture in QTP
Settings for Screen capture in QTP

Once test is executed, recorded movie can be viewed in results as shown below



Viewing recorded movie in results
Viewing recorded movie in results

Understanding Object Repositories Manager: Managing Objects

1.  How to Import Object Repository from xml file


Object repository can be loaded from an external xml file using object repository manager.


Importing and exporting Object Repositories to/from xml file


2.  How to export Object Repository to a xml file


Object repository can be exported to an external file using object repository manager.


3. Defining Objects manually in object repository 


      A new test object can be added manually using object repository manager. Below are the steps to add object manually in the object repository

Adding Object manually in Object repository

  • Navigate to Resources>Object Repository Manager
  • Navigate to Object>Define New Test Objects
  • Define new test Object with environment, name, and class of object and add description properties to object.
  • Click on Add to add object.
  • Save object repository as shared object repository


4.       Add Object to repository

  • User can add an object from  application without recording
  • Navigate to Resources>Object Repository Manager.
  • Navigate to Object>Add Objects
  • Focus on object to be added and click.
  • Object is added to repository.


5.       Navigate and Learn

  • User can add required objects from application using Navigate and Learn.
  • Navigate to Resources>Object Repository Manager.
  • Navigate to Object>Navigate and Learn or press F6.
  • Define the filter for objects to be added.
  • Click on learn button.
  • Object will be added to object repository


·          
Options of Working with object

6.       Update Object from Application

  • User can update objects from application with below steps
  • Navigate to Resources>Object Repository Manager.
  • Select an object to be updated. Please note updated object class should be same as the class of object by which it is to be updated.
  • Navigate to Object>Update from application
  • Object properties are updated

How to integrate QTP 11 with Quality Center/ALM

HP ALM 11 or Quality Center is used as a test management tool in which we can store tests, function Libraries, test data, object repository, recovery scenario and much more. Below are some of the features in QTP required to connect to Quality Center and various options in QTP regarding QTP-QC Integration

Integration between QC and QTP

QTP can connect to a project stored in ALM through VBScript Code or through QTP IDE as explained below:

Through Code

Below code creates a connection to QC. This will validate if a connection to QC already exists and in case not connected than connects to the required project in QC

Public Functionfunc_ConnectQCQTP(QCurl,Domain,ProjectName,UserName,Password)

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,Domain,ProjectName,UserName,Password,False

End If

Set qtApp = nothing

End Function


Through QTP Interface


Go to File>ALM/QC Connection as shown below and create the connection.

Connecting to QC from QTP



Connecting to QC from QTP

User is allowed options to reconnect to the QC Server, and authenticate on start up and login to project automatically once QTP is launched.

Version Control in QC


In case of test stored in QC,version controlling the test script is very useful,so that test can be open by one user at a time and previous versions of test are available and can revert to previous version in case of issues. In case of version control, a test will open in read only mode and changes in script can be done only post checking out the script, and once changes are incorporated, changes should be checked in.



Priniciple of Software Testing and Difference between QC and QA

Basics of Testing

Testing is a quality control activity with objectives as finding defects, gaining confidence on the quality of products and preventing defect. Testing should start as early as possible and should be planned for different phases of software life cycle. Early detection of defects reduces the cost of fixing defects.

Principles of Testing

Below are the principles of testing which should be taken into consideration while performing testing:

  • Testing shows presence of defect but we cannot ensure there are no defects in the system. The reason for this is described in next principle
  • Exhaustive testing is not possible as covering all combination of data and scenario is not feasible as it will take lot of cost and resources & time.
  • Testing Activity should start as soon as possible. This will result in defect fixed with less effort in development and development can more easily accommodate the changes in early phases than latter.
  • So now the question arises, which things to test first. Most of the defects are concentrated to small number of modules, which is defect clustering. So we need to concentrate more on modules more prone to defects.
  • Next test case needs to be updated regularly to avoid pesticide paradox i.e same test cases if executed again and again will not be able to find more defects.
  • Testing should be context sensitive, i.e before considering testing, we should take into consideration the impact and importance area of the application
  • And finally the product delivered and tested should match the client expectation, and is no purpose even if no defect is found, but product does not fulfill client requirement.

    

 Quality Control and Quality Assurance


Last point in the Testing principles mentions the product delivered to the customer should be quality product. To ensure quality of the product, we must follow quality assurance and quality control activities.

Quality Assurance ensures proper quality processes are followed during product development .For example. There are regular audits, inspections, review activities, estimations, testing process standards during the software life cycle to assure the quality of product.

Quality Control is the testing activities in which product quality is compared with expected standards and issue is raised in case of defects or non conformance being encountered.

Some of the most important Quality Factors are Correctness, Reliability, Efficiency, Integrity, Usability, Maintainability, Reusability, and portability.


Examples of Working with WebTable in QTP

HTML normally has many webtable and we can extract a lot of information using webtable methods in QTP. In this post we will discuss various methods by which we can used for webtable object.

Example 1: Validate if a webtable exist

boolExist = Browser(…).page(…).webtable(…).exist

Example 2 : To Find number of rows and columns in a web table

intRowCnt=Browser("Google").Page("title:=.*").WebTable(“name:= TTable").RowCount
For r=1 to intRowCnt
‘’ This will loop through each row and tell count of column in each row.
intColCnt=Browser("Google").Page("title:=.*").WebTable(“name:=TTable").ColumnCount(r) 
MsgBox intColCnt
Next

Example 3: How to get data in a particular cell in the data table

strData= Browser("Google").Page("title:=.*").WebTable(“name:=TTable").GetCellData(r,c)
Where r = row number and c = column number

Example 4: Using childObject method to find objects of a particular type within a webtable

Public Function func_findObjectinaWebTable(strObjType)
Set objDesc=Description.Create
objDesc("micclass").value=strobjType
set objChild=Browser("Google").Page("title:=.*").WebTable(“name:=TTa").ChildObjects(objDesc)
func_findObjectinaWebTable = objChild.count
End Function

Example 5: Using HTML DOM to get count of objects in a webtable

Public Function func_findObjectinaWebTable(strTagName)
set objChild= Browser("Google").Page("title:=.*").WebTable(“name:=TestTable").object.getElementsbyTagName(strTagName)
func_findObjectinaWebTable = objChild.length
End Function

Example 6: Using ChildItemCount and childItem in webtable to extract information

Public Function func_findObjectinaWebTable(strObjType,introw,intCol)
ob0jChildCnt=Browser("Google").Page("title:=.*").WebTable(“name:=TestTable,"index:=0").ChildItemCount(introw,intcol,strobjType)
If objChildCnt >0
Childitem will return object oftype defined in arguments for childitem
Set ChldItm = Browser("Google").Page("title:=.*").WebTable(“name:=TestTable,"index:=0").ChildItem(introw,intcol,strobjType,0)
If (strobjType = "Link" or strobjType ="WebEdit") Then
ChldItm.Click
ElseIf(stobjType = "WebCheckBox") Then
ChldItm.Set "ON"
End If
End Function

Understanding QTP Testing process


Quick Test Professional  testing process consists of following phases:


Pre-conditions before testing:


Before recording in QTP ,Please ensure following :

1. Application on which to record is open after qtp is launched.

2. Add-ins based on application are loaded.

3. Unnecessary instances of Internet Explorer and other applications are closed.

4. Ensure record and run settings are as expected and will record on the AUT.



Recording a session on your application


Click on record button in QTP and perform actions on AUT. QTP records every action performed and each element on which action is performed is stored as object in object repository. QTP displays each step in keyword view as tree and in expert view as vbscript.
For Recording, press F5 OR Click on record button.



Enhancing your test

1. Add Checkpoint to define pass/fail condition in the test.

2. Break lines of Codes into functions and increase reusability of test code.

3. Use data table to parametrize data used in the test.

4. Add regular expressions, output value in the test.

5. Add logic and conditional or loop statements that enables to add checks in the test.



Debugging your test

Debug a test to ensure that it operates smoothly and without interruption.To use debugging features , please install Microsoft script debugger. Use breakpoints to pause a test at breakpoints.


Running your test

On running a test using QTP, We know whether the expected behaviour of application matches the current behavior. A test will show pass/fail based on checkpoint on error handling defined through Code.


Analyzing the test results

Once a test is run, we have to analyse results to understand the behavior of AUT. We can analyse whether checkpoint pass or user defined error handling is passed or not.


Reporting defects

Once defects are found in application , they should be reported to concerned team and the tests should pass in case error/defects are resolved




How to Use GetElementsBytagName Method in QTP explained with Code

In this post, we will discuss how to use GetElementsbyTagName to input values in a edit box, count number of editbox, links , and count number of rows in a particular table. Please suggest in case user miss anything in the code. We can similarly use GetElementsbyTagName in a variety of purposes and manipulate the html


Code to find number of links in a page.

set objLink = Browser("title:=.*","index:=0").Page(title:=.*).Object.GetElementsByTagName("a")

intLinks = objLink.length


Code to Identify number of edit box in the page.

set objLink = Browser("title:=.*","index:=0").Page(title:=.*).Object.GetElementsByTagName("input")

intLinks = objLink.length


Code to input Data in a field using HTML DOM

set objEdit = Browser("title:=.*","index:=0").Page(title:=.*).Object.GetElementsByTagName("input")

for each editbox in objEdit

       If editbox.classname = <strClassName>

editbox.innertext = <strSetVsalue>

Exit For

     End If

Next


Code to count number of rows in a table

set objTable = Browser("title:=.*","index:=0").Page(title:=.*).Object.GetElementsByTagName("table")

for each Tbl in objEdit

         If Tbl.classname = <strTableClassName>

set objrow = tbl.getelementsbyTagName("tr")

Msgbox objrow.length

        End If

Next


QTP VBScript - Excel Application - Sorting data in excel worksheet based on column name

Below script or code snippet is very useful in sorting an excel workbook based on the name of columns header . We can sort multiple columns of the excel worksheet. For e.g there are 3 columns with header name as "name","class" and "value" based on which we want to sort the database with priority in order name>class>value. So provide strSortbyfield as "name>class>value". Below piecee of code can be implemented to achieve the same


strWorkBook = InputBox ("Input the workbook with full path")

strWorkSheet = InputBox("Enter the sheet name")

strSortbyFields = Inputbox ("provide the field names, seperated by > in case of multiple sorting of data is required")

Set objExcel = Createobject("Excel.Application")

objExcel.Visible = False

Set XLWorkBook = objExcel.WorkBooks.Open(strWorkbook)

Set objWorksheet = XLWorkBook.Worksheets(strWorkSheet)  

Set objRange = objWorksheet.UsedRange

ColCount = objRange.columns.count

strSortDataArr = split(strSortbyFields,">")

intCnt = ubound(strSortDataArr)

For i = intCnt to 0 step -1

For j = 1 to ColCount step 1

If (objWorkSheet.cells(1,j).value =strSortDataArr(i)) Then

''get the column based on which data needs to be sorted in the excel document

chrCde = Chr(asc("A")- 1+j) & "1"

boolExcelSortData = True

Set objRangeSrt = objExcel.Range(chrCde)

objRange.Sort objRangeSrt, xlDescending, , , , , , xlYes 

XLWorkBook.save

             Exit For

End If  

Next

Next

''save the workbook and close

XLWorkBook.Save

XLWorkBook.Close

objExcel.Quit

Set XLwORKBook = Nothing

Set objExcel = Nothing



How to use GETROProperty to extract value using descriptive programming in QTP

We can use descriptive programming to display the value stored for object e.g the value displayed in a edit box or a webelement or default value in a webList.


We can learn following key points from the code below:


  • How to create a description object using description.create
  • How to implement descriptive programming for object uniquely identified by using multiple properties
  • How to use getROProperty to extract information at runtime
  • How to return value by a function.


Public Function ValueDisplayedForObject(DescObj,ObjType)
On error resume next
Set objDesc= Description.create
'Set of Property value are delimited by ,
If (instr(1,DescObj,",") >0) Then
   ''Split multiple links based on delimiter. ,
arrDesc = split(DescObj,",")
intPropSet = Ubound(arrDesc)
''Loop through each of the link and click the required link
for i = 0 to intPropSet
'' Property and value for property are seperated by |
strDesc = split(arrDesc(i),"|")
objDesc(strDesc(0)).value = strDesc(1)
Next
''In case of only one property value set of image
Else
strDesc = split(DescObj,"|")
objDesc(strDesc(0)).value = strDesc(1)
End If
If (ucase(ObjType) = "WEBELEMENT")  Then
ValueDisplayedForObject = Browser("Browser_Encompass").Page("title:=.*").WebElement(objdesc).GetRoProperty("innertext")
ElseIf (ucase(ObjType) = "WEBLIST") Then
ValueDisplayedForObject = Browser("Browser_Encompass").Page("title:=.*").WebList(objdesc).GetRoProperty("value")
Else
ValueDisplayedForObject = Browser("Browser_Encompass").Page("title:=.*").WebEdit(objdesc).GetRoProperty("value")
End If
If (err.number<>0) Then
Reporter.ReportEvent micpass,"Value displayed for object",err.description
End If 

End Function.

 Please see below links for more on descriptive programming

qtp descriptive programming basics

descriptive programming examples and comparison with OR

Script to execute specific QTP tests from Test Set in Quality Center using VBScript

Below code will execute tests in a test set in QC based on name of the test set. The code can run all the scripts in test set, only passed test script, only failed test script. This can be manipulated further based on requirement. Also an html file with test status will be displayed once test set execution is completed.




 UserName = InputBox("Enter the user name for QC Login", "QC UserName")  
 Password = InputBox("Enter the password for QC Login", "QC Password")  
 strExecFlag = InputBox("Enter the option for test execution" & vbcrlf & "Valid Values - P, A,F" & vbcrlf & "A: Run All test Scripts"& vbcrlf & "F: ExecuTe script not passed Only"& vbcrlf & "P: Execute Passed Test Scripts","Test Execution Option")  
 'Return the TDConnection object.  
 Set QCConnection = CreateObject("TDApiOle80.TDConnection")  
 QCConnection.InitConnectionEx QCurl  
 QCConnection.login UserName, Password  
 QCConnection.Connect DomainName, ProjectName  
 Set TSetFact = QCConnection.TestSetFactory   
 Set tsTreeMgr = QCConnection.TestSetTreeManager   
 Dim qtApp 'As QuickTest.Application ' Declare the Application object variable   
 Dim qtLibraries 'As QuickTest.TestLibraries ' Declare a test's libraries collection variable   
 Set tsFolder = tsTreeMgr.NodeByPath(<QC Test Set Path>) ' test set starts with "Root"  
 Set tsList = tsFolder.FindTestSets(<TestSetName>) 'Testset name  
 strTable = ""  
 Set theTestSet = tsList.Item(1)  
 For Testset_Count=1 to tsList.Count  
    Set theTestSet = tsList.Item(Testset_Count)   
    Set TSTestFact = theTestSet.TSTestFactory  
    TSName = theTestSet.Name  
    Set TestSetTestsList = TSTestFact.NewList("")   
   For Each theTSTest In TestSetTestsList   
      TestName = theTSTest.Test.Name    
      TestScript = <Test Script path in QC> & TestName    
      TestStatus = theTSTest.Status  
      If ((TestStatus ="Passed" and ucase(strExecFlag) = "P") OR (TestStatus <>"Passed" and ucase(strExecFlag) = "F") or (ucase(strExecFlag) = "A")) Then  
         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  
  ' Create the Application object  
      qtApp.Open TestScript, True  ' Open the test in read-only mode  
      Set qtTest = qtApp.Test  
     Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions")   
     ' Create the Run Results Options object   
     ' New Run Results in Quality Center option  
     qtResultsOpt.TDTestInstance = 1  
     qtResultsOpt.TDRunName= "Run_" & Month(Now) & "-" & Day(Now) & "_" & Hour(Now) & "-" & Minute(Now) & "-" & Second(Now)  
    qtResultsOpt.TDTestSet = TestSetPath ' Path to the Test Set where we should save the results  
    Set fso=createobject("Scripting.FileSystemObject")   
    If fso.FolderExists("C:\Res1") Then   
         fso.DeleteFolder("C:\Res1")  
    End If  
    qtResultsOpt.ResultsLocation = "C:\Res1"  
    qtTest.Run qtResultsOpt,True  
    TestStatus = qtTest.LastRunResults.Status  
    qtTest.Close  
    qtApp.quit  
    Set qtApp = Nothing    strTable = strTable & "<tr><td>"&TestName&"</td><td>"&TestStatus&"</td></tr>"  
    End If   
   Next  
 Next  
 Set objFSO = CreateObject("scripting.filesystemObject")  
 If (objFSO.FolderExists("c:\Temp") = False) Then  
    objFSO.CreateFolder("c:\Temp")  
 End If  
 strTable = "<html><h1>Test Results<h1><table border =""""2""""<tr><td>TestCaseName</td><td>Test Execution Status</td></tr>" & strTable &"</table></html>"  
 Set objFl = objFSO.CreateTextFile("c:\Temp\Test.html")  
 objFl.Write strTable  
 Set objFl = nothing  
 CreateObject("WScript.Shell").Run "c:\Temp\Test.html"