We can use reporter.logevent method as explained in code/functions below to add results in tabular format in QTP test results. Below is an example on how to use reporter.logevent
Blog to understand automation concepts in QTP, Selenium Webdriver and Manual Testing concepts
Showing posts with label Test Scripts. Show all posts
Showing posts with label Test Scripts. Show all posts
QTP Script to convert content of excel into a html document
Labels:
QTP,
qtp Scripts,
Test Scripts
Suppose I have some data in excel file and I want to create a html table from the excel file content. Below code can create a html table based on the content of an excel file.We can understand how to create a html file using scripting.filesystemObject in QTP.
Example of how to call the function:
func_createHTMLTableFromExcel "E:/test.xlsx","Sheet1","e:/ht.htm"Code for the function:
Public Function func_createHTMLFromExcel(strDataFile,strWorksheetName,strHTMLFile)
Set objXlHandle = Createobject("Excel.Application")
objXlHandle.visible = false
Set objExcelWB = objXlHandle.Workbooks.Open(strDataFile)
Set objExcelWS = objExcelWB.Worksheets(strWorksheetName)
'Getting column and row count
strColumnCount = objExcelWS.UsedRange.Columns.Count
strTotRows = objExcelWS.UsedRange.Rows.Count
strTable = "<table border=""""2"""">"
'Creating a html table based on content of the excel file
For j=1 to strTotRows
strTable = strTable & "<tr>"
For i=1 to strColumnCount
strData = Trim(objExcelWS.Cells(j,i))
strTable= strTable & "<td>"& strData &"</td>"
Next
strTable =strTable & "</tr>"
Next
strTable = strTable & "</table>"
set objFSO=Createobject("scripting.FileSystemObject")
set objtxt = objFSO.createTextFile(strHTMLFile)
objtxt.write(strTable)
'Closing the workbook
objExcelWB.Close
set objFSO =nothing
End Function
How to add Attachments in QC during test script execution in QTP
Labels:
QTP,
qtp Scripts,
QTP-QC Integration,
Test Scripts
Using below code, we can add attachment to QC during test script execution:
''This function will add the required attachment in QC, for Location defined by argument strLocationinQC
Function func_AddAttachmentToQC(FilePath,strLocationinQC)
On Error Resume next
If (ucase(strLocationinQC) = "TEST") Then
Set objCurrentTest = QCUtil.CurrentTest.Attachments
Set objAttach = objCurrentTest.AddItem(Null)
ElseIf(ucase(strLocationinQC) = "TESTSET") Then
Set objCurrentTest = QCUtil.CurrentTestSet.Attachments
Set objAttach = objCurrentTest.AddItem(Null)
ElseIf(ucase(strLocationinQC) = "TESTRUN") Then
Set objCurrentTest = QCUtil.CurrentRun.Attachments
Set objAttach = objCurrentTest.AddItem(Null)
End If
objAttach.FileName = strFilePath
objAttach.Type = 1
objAttach.Post
objAttach.Refresh
End Function
Examples of Working with WebTable in QTP
Labels:
Advanced QTP,
QTP,
qtp Scripts,
Test Scripts
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.
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
Where r = row number and c = column number
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
set objChild= Browser("Google").Page("title:=.*").WebTable(“name:=TestTable").object.getElementsbyTagName(strTagName)
func_findObjectinaWebTable = objChild.length
End Function
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
Example 1: Validate if a webtable exist
boolExist = Browser(…).page(…).webtable(…).existExample 2 : To Find number of rows and columns in a web table
intRowCnt=Browser("Google").Page("title:=.*").WebTable(“name:= TTable").RowCountFor 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
How to Use GetElementsBytagName Method in QTP explained with Code
Labels:
HTML DOM,
QTP,
qtp Scripts,
Test Scripts
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
Labels:
QTP,
qtp Scripts,
Test Scripts,
VBScript,
VBScript Tutorials,
Working with excel
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
Labels:
Descriptive,
QTP,
qtp Scripts,
Test Scripts
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
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
Labels:
QTP,
qtp Scripts,
Test Scripts
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"
How to create and run a batch file
Labels:
File Comparision,
Test Scripts,
trivial,
VBScript
Batch
files help user to execute a set of command to be executed in the defined order
by executing a batch file. We can execute large number of commands
in one go using bat file.
Creating a batch file
A batch file has extension .bat .To create a new bat file, we
can save a file in text editor like notepad in format .bat.
Some useful batch commands
@echo off – this will not echo the text post the command and will show only the execution result in the command prompt.
@echo on – this will echo the text post the command and will show the command as well as the execution result in the command prompt.
Pause– If we use pause, the batch file execution is halted until further intervention of user by pressing keys.
Arguments %1,%2,….. – This gives the parameter for the batch file.
echo val will display val in the command prompt
:: and rem can be used to add remarks to the script
Cls can be used to clear the command prompt
Example :
For
e.g we need to compare 2 txt files, but name of files to be compared needs to
be passed dynamically and log path also needs to be defined dynamically.
The content of batch file for this will look like
@echo off
Fc %1 %2 /n>%3
Pause
To execute this bat file, we have to write in run as
D:\Sample\new.bat d:\Sample\test4.txt d:\Sample\test7.txt d:\Sample\test9.txt
How to compare content of files using fc command
Labels:
File Comparision,
FileSystem Object,
Test Scripts,
VBScript
I was having issues with comparison of two large csv files that I came across fc comparision command of Microsoft DOS. fc is a command line program that compares multiple files and outputs the differences between them
The syntax of fc Command and results of execution of fc with different arguments is shown below:
Syntax for fc command:
fc filename1 filename 2 [Parameter for comparision type] >Log File Path
where filename1 and filename2 are paths of the two files to be compared .
LogFilePath is path for saving result log
Commonly used Parameters are as described below:
/a : fc displays only the first and last line for each set of differences.
/b : Compares the files in binary mode.
/c : Ignores the case of letters.
/l : Fc compares the two files line by line and attempts to resynchronize the files after finding a mismatch.
/lbn : Sets the n number of lines for the internal line buffer.
/n : Displays the line numbers during an ASCII comparison.
Connecting to excel as database using Adodb in VBScript/QTP
Labels:
Test Scripts,
VBScript,
Working with database
We can connect to excel file using Adodb
object in vbscript. Following are the
steps in working with excel as database.
1. Create an instance of connection :
Set objConn = CreateObject("Adodb.connection")
2. Create connection string to connect to excel database as follows
strCon = "Driver={Driver do Microsoft Excel(*.xls)};DriverId=790;Dbq=" & Workbook &";"
Here we have created a database for excel
Workbook . The sheets in the workbook acts as table of the database.
3. Connect to database as shown below:
objConn.open strCon
Now we are done with the connection to excel ,
we require SQL to run on the data to extract required information .
4. Create a SQL as required as shown below:
strSQL = "select name from [Table1$];"
Note here, we have to give sheet name
acting as table within square bracket and with suffix “$” as shown above.
5. Create a recordset as shown below and execute the query using recordset, all the records based on query will be stored in recordset.
Set rs = CreateObject("ADODB.recordset")
rs.Open strSQL,objConn
6. We can transfer the data extracted from query back in excel using copyrecordset method
XLSheet.range("A2").copyfromrecordset rs
Where XLSheet is the reference of required
sheet in the excel file and A2 is the
location in sheet from which data will be pushed in the sheet.
Useful VB Script Functions for QTP - String, Date, Array and Control flows
Labels:
Test Scripts,
VBScript
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.
Subscribe to:
Posts (Atom)