Thursday 28 March 2013

Keyword Driven Automation Framework in QTP

Keyword driven Automation Framework is most popular QTP framework. It is very easy to design and learn a keyword driven automation framework in QTP.

In this article I will explain you all details about how we can design and use keyword driven automation framework in QTP with example. I will also explain the advantages and disadvantages of keyword driven automation framework in QTP.

What is keyword driven automation framework in QTP?

In keyword driven automation framework, focus is mainly on kewords/functions and not the test data. This means we focus on creating the functions that are mapped to the functionality of the application.

For example -
Suppose you have a flight reservation application which provides many features like
  • Login to the application
  • Search Flights
  • Book Flight tickets
  • Cancel Tickets
  • Fax Order
  • View Reports
To implement the keyword driven automation framework for this kind of application we will create functions in vbscript for each functionality mentioned above. We pass the test data and test object details to these functions.

What are the main components of keyword driven automation framework in QTP?

Each keyword driven automation framework has some common components as mentioned below.


As dispalyed in above image, We have 5 main components in keyword driven automation framework

  1. Scripts Library (.vbs, .txt, .qfl)
  2. OR - Object Repository
  3. Test Data (generally in excel format)
  4. QTP - Settings and Environment Variables
  5. Reports - (Generally in HTML format)
  6. Test Driver Script/ Test Engine
We will see examples of each component in below section.

1. Library Scripts (Files) in keyword driven automation framework in QTP.


As I mentioned earlier, in keyword driven automation framework we develop the kewords that are mapped to the functionality of the application. In large automation projects  where there are many functionalities, We need to create lot of functions. Generally We create functions for each module in the application and store similar functions in seperate library files.

For example -

We can store login/logout related functions in authentication.vbs file.
All functions related to booking could be stored in booking.vbs

Sample function in authentication.vbs is given below. Please note that single vbs file may contain multiple functions.

Function login()

'Setting the user id 
Dialog("Login").WinEdit("Agent Name:").Set uId
Dialog("Login").WinEdit("Agent Name:").Type  micTab 

'setting the password
Dialog("Login").WinEdit("Password:").SetSecure password
Dialog("Login").WinButton("OK").Click

If Dialog("Login").WinEdit("Agent Name:").Exist(1) Then
'Log the result saying login failed
Else
'log the result saying login passed/successful
End If

End Function

Please note that we can store library files with 3 extentions i.e. .vbs, .txt and .qfl.
QTP engineers prefer to store the library files in a file with extension .vbs as we can include vbs files using executefile statement and also find out the syntax errors by double clicking on the vbs file.
QFL file long form is Quick test function library.

Once you have created the library file with all functions in it, you can associate that file to test using resources setting.

2. Object Repository in keyword driven automation framework in QTP.

In QTP there are two types of Object Repository.
  • Local Object Repository (objectrepository.bdb for each action)
  • Shared Object Repository (.tsr extention)
Out of these 2 object repositories, Shared object repository is very popular among QTP testers. Because we can have all test objects in single file. This helps us to maintain the object repository. To add/ edit objects inside shared object repository, you must go to Object Repository Manager and open the .tsr file and then make the changes in the shared object repository.

3. Test Data (generally in excel format) in keyword driven automation framework in QTP.

Generally automated test cases are stored in excel sheets. From QTP ,we read excel file and then row by row we execute the functions in a test case. Each test case is implemented as a set of keywords.
Common columns in Data sheet are mentioned below.
  • Test case ID - Stores the Test Case ID mapped to Manual Test Cases.
  • Test Case Name - Name of the Test cases/ Scenario.
  • Execute Flag - if Marked Y -> Test case will be executed
  • Test_Step_Id - Steps in a test case
  • Keyword - Mapped to function in library file.
  • Object Types - Class of the object e.g winedit, webedit, swfbutton etc
  • Object Names -Names of objects in OR .
  • Object Values - Actual test data to be entered in the objects.
  • Parameter1 - This is used to control the execution flow in the function.








Please note that this is just a sample data sheet that can be used in keyword driven framework. There could be customized data sheets for each project depending upon the requirement and design.
For example there could be more parameters or test data is stored in the databases. 

4. QTP Test Settings and Environment Variables in keyword driven automation framework in QTP.

This is also one of the most important component of the keyword driven automation framework.
In Test settings We need to do some setting before we execute any test suite. This could be one time set up or per execution request set up.

List of Important Settings -
  • Object Synchronization timeout -
  • When Error Occurs during run session -
  • Resources - Associated library files
  • Environment - We need to set up some variables like folder path, User Id etc
  • Recovery - We must associate the recovery scenario file to the test. Recovery Scenario will handle unexpected events during execution. This will help for smooth execution using QTP.

5. Reports in keyword driven automation framework in QTP.

In actual projects we generally do not rely on the reports/results generated by the QTP. We usually create the reports in html formats using custom reporting function. We use filesystemobject to create html reports.
Reports will display the total number of test cases executed, Total Pass Test cases, Total Failed test cases and total time required to execute the test cases. This will give better picture of QTP Execution. 

Reports module may contain below functions.

'Below function will create the folder in which reports are stored
Function CreateReportFolder()
Set Fo = createobject("Scripting.FilesystemObject")
If Not Fo.FolderExists(Environment.Value("ResultPath")) Then
Fo.CreateFolder (  Environment.Value("ResultPath") )
End If
'******************************************************************************

'Below function will store the log of the test case in memory variable called templog until  it is written to file permanently.

Function CreateTestCaseLog(log,intStatus)
If intStatus = 1 Then
strhtml = "<span style=""color:green""> Pass : </span> " 
ElseIf  intStatus = 2 Then
strhtml = "<span style=""color:red""> Fail &nbsp; : </span> " 
ElseIf  intStatus = 3 Then
strhtml = "<span style=""color:maroon""> Warning :  </span> " 
ElseIf  intStatus = 4 Then
strhtml = "<span> Info &nbsp; : </span> " 
End If 
templog = templog &  strhtml & log & "<br/>"
End Function

'******************************************************************************
'Below function will write the log to html file permanently

Function GenerateHtmlReport(byval testCount,byval Test_Id,byval Test_Name,byval Test_Status,byval Test_Description)

If Test_Status = False Then
Test_Status = "<span style=""color:red"">Fail</span>"
Else
Test_Status = "<span style=""color:green"">Pass</span>"
End If

If  testCount = 0 Then

strDetailedHTML = "<html><head><title>Detailed Report Of Execution </title> " 
strDetailedHTML = strDetailedHTML & css
strDetailedHTML = strDetailedHTML & "</head> <body><table>" 
strDetailedHTML =  strDetailedHTML  & "<tr><th colspan=5> HTML Report  </th></tr>"
strDetailedHTML =  strDetailedHTML  & "<tr><th>No</th><th>Test_Case_Id</th><th>Test_Case_Name</th><th width='500px'>Test_Case_Log</th><th>Test_Case_Status</th></tr>"
filepath = "Detailed.html"
Call AppendFileData(filepath,strDetailedHTML)
End If

strDetailedHTML = "<tr><td> " & testCount & " </td><td>" & Test_Id & " </td><td> " & Test_Name & " </td><td style=""text-align:left;""> " & Test_Description & "</td><td>" & Test_Status & "</td></tr>"
filepath = "Detailed.html"
Call AppendFileData(filepath,strDetailedHTML)

End Function

'******************************************************************************
'Below utility/helper function will append the data to existing html file

Function AppendFileData(byval filepath, byval contents)
filepath =  Environment.Value("ResultPath") & "\" & filepath
Set Fo = createobject("Scripting.FilesystemObject")
Set f = Fo.openTextFile(filepath,8,true)
f.Write (contents)
f.Close
Set f = nothing
End Function

6. Test Driver Script/Test Engine Script

This is the heart of keyword driven / data driven frameworks. This is the main script that interacts with all modules mentioned above.
Main tasks that are accomplished by driver script are ->
  1. Read data from the Environment variables /File or from ini file.
  2. Call report module to create Report folders / files 
  3. Import Excel sheet to Data table.
  4. Read Excel file.
  5. Call the function mapped to keyword.
  6. Log the result
Sample Driver Script is given below



Function ExecuteTest()


'Load Environment Variables
Environment.Value("TestDirectory") = replace(Environment.Value("TestDir"),"Scripts\Driver Script","")
Environment.LoadFromFile Environment.Value("TestDirectory") & "Environment Variable\Env.ini"
strSheetName = Environment.Value("SheetName")
Environment.Value("ResultFolderPath") = Environment.Value("TestDirectory") & "Results\" & formatdatetime(now,2)
Environment.Value("ResultFolderPath") = replace(Environment.Value("ResultFolderPath"),"/","-")
CreateReportFolder()
gfilestamp = replace(replace(formatdatetime(now),":","-"),"/","-")

If instr(strSheetName,"|")>0 Then
arrSheet=split(strSheetName,"|")
else
arrSheet=array(strSheetName)
End If

For i=0 to ubound(arrSheet)

gfilestamp = replace(replace(formatdatetime(now),":","-"),"/","-")
TestStartTime = Now()
l_strsheetname=arrSheet(i)
intTestCaseCount=0

tmpDataTbl = "xyz"
tmpSheetLocation =  Environment.Value("TestDirectory")  & "Input Data\Mydatasheet.xls"
DataTable.DeleteSheet(tmpDataTbl)
DataTable.AddSheet tmpDataTbl
DataTable.ImportSheet tmpSheetLocation, arrSheet(i), tmpDataTbl
'Driver Script
intTotalRows = DataTable.GetSheet(tmpDataTbl).GetRowCount

dtRows = 1
Call CreateTestCaseLog("--------------- <b>" & ucase(arrSheet(i))  & "</b>---------------",4)
Call RunTest(TestStartTime,l_strsheetname)

Next


End Function

'*********************************************************************************
'*********************************************************************************

Function RunTest(TestStartTime,l_strsheetname)

TempLoginCredentials=""
intFailCount=0
intTestCaseCount=0


For dtRows = 1 To intTotalRows

' Read Test Case data

strExecutionflag = trim(ucase(DataTable("Exec_Flag", tmpDataTbl)))
strExecutionflag = Replace(strExecutionflag, Chr(13), "")
strExecutionflag = Replace(strExecutionflag, Chr(10), "")

temprows = dtRows

If ucase(trim(strExecutionflag)) = "Y" Then




blnTestStepFlag = True
blnOverallTestCaseStatus = True
blnReportTestCaseStatus = True
strTestCaseID = DataTable("ID", tmpDataTbl)
strTest_Case_Name = DataTable("Test_Case_Name", tmpDataTbl)
gtestcaselog = ""  ' Reinitialize the log for new test case


startTime = Now
Call CreateTestCaseLog("Test Start Time - " & replace(replace(formatdatetime(now),":","-"),"/","-")   ,4)


Do While    blnTestStepFlag


strTest_Step_ID = DataTable("Test_ID", tmpDataTbl)


strControlType = DataTable("ObjectTypes", tmpDataTbl)
strControlName = DataTable("ObjectNames", tmpDataTbl)
strControlValues = DataTable("ObjectValues", tmpDataTbl)

StrScenarioName=DataTable("Test_Step_ID", tmpDataTbl)
BusinessKeyword =  DataTable("Keyword", tmpDataTbl)
strParameter1 =  DataTable("Parameter1", tmpDataTbl)


Call CreateTestCaseLog("******************<b>" & BusinessKeyword  & "</b>******************",4)

ret = Eval (BusinessKeyword)
If (ret = False) OR (ret = "") Then
blnOverallTestCaseStatus = False
blnReportTestCaseStatus = False
tempstimestamp = replace(replace(formatdatetime(now),":","-"),"/","-")
tempspath = Environment.Value("TestDirectory") & "Screenshots\" & tempstimestamp  & ".png"
constobjParent.CaptureBitmap tempspath,True
Call CreateTestCaseLog("Snapshot <br/> " & "<a target='_blank' href='" & tempspath & " '> Screenshot</a> <br/> "  ,2)

Else

Call CreateTestCaseLog("Function " & BusinessKeyword & " was  successful"  ,1)
End If


DataTable.GetSheet(tmpDataTbl).SetNextRow
dtRows = dtRows + 1




If DataTable("ID", tmpDataTbl) <> ""  or (blnOverallTestCaseStatus = False ) Then

blnTestStepFlag = False      
DataTable.GetSheet(tmpDataTbl).SetPrevRow
dtRows = dtRows - 1

If  Instr(1,ucase(strTestCaseID),"P") > 0 Then
intPreTestCaseCount = intPreTestCaseCount + 1
If  blnOverallTestCaseStatus = False Then
intPreFailCount=intPreFailCount+1
End If
End If


Call CreateTestCaseLog("Test End  Time - " & replace(replace(formatdatetime(now),":","-"),"/","-")   ,4)
DurationOfCaseExecution = DateDiff("n",startTime,Now)  

Call CreateTestCaseLog("Test Case Execution Time - " & DurationOfCaseExecution   ,4)


Call GenerateDetailedHtmlReport(intTestCaseCount,strTestCaseID,strTest_Case_Name,blnOverallTestCaseStatus,gtestcaselog,l_strsheetname)


End If

Loop  'loop until test ends

If instr(strTestCaseID,";")>0 Then
l_scriptArray=split(strTestCaseID,";")
intTestCaseCount = intTestCaseCount + ubound(l_scriptArray)+1
If  blnOverallTestCaseStatus=false Then
intFailCount=intFailCount+ ubound(l_scriptArray)+1
End If
else
intTestCaseCount = intTestCaseCount +1
If  blnOverallTestCaseStatus=false Then
intFailCount=intFailCount+ 1
End If
End If
End If
DataTable.GetSheet(tmpDataTbl).SetNextRow
Next

TestEndTime = Now()
intTestCaseCount=intTestCaseCount-intPreTestCaseCount
intFailCount=intFailCount-intPreFailCount
DurationOfTestExecution = DateDiff("n",TestStartTime,TestEndTime)      
Call GenerateFinalReports(intTestCaseCount,intFailCount,DurationOfTestExecution,l_strsheetname)

End Function
'*****************************************************************************

If you want to download the full source code, data sheets, sample scripts and examples, Please buy an e-book at below url.

QTP/UFT Framework

I will send you all the details along with pdf.

You may also like -
  1. QTP Questions and Answers for Experienced guys
  2. Advanced QTP Questions and answers
  3. Advanced QTP Tutorial
  4. UFT Master Page
Dear friend -  What do you think about this topic? Please express your thoughts via comment box.

No comments:

Post a Comment

Please Leave your reply. We value your feedback and inputs

Best QTP Books

Everything About QTP

Hello Friends,
You can find QTP study material, Multiple choice questions (mcq), QTP question bank, QTP question papers, QTP notes, QTP questionnaire, scenario based QTP interview questions, QTP tutorial and QTP training on this site.

If you are a fresher or experienced QTP professional with (1/2/3/4) years of experience, this blog is just for you.