Data driven testing using excel in QTP
This is script for data driven using excel sheet.
In this script we are not importing excel sheet to datatable. Directly values are supplied to application from excel sheet.
set ex= CreateObject("Excel.Application")
Set a=ex.Workbooks.open("D:\excel.xls")
Set b=a.worksheets("Sheet1")
dim login, pwd
for i=1 to 3
login=b.Cells(i,"A").value
pwd=b.Cells(i,"B").value
msgbox login
msgbox pwd
next
"D:\excel.xls" is path of excel sheet.
"sheet1" indicates sheet name in which values are present.
A,B are column names in excel sheet.
we have excel sheet with values as shown below in d drive.
A B
1 2
3 4
5 6
0 comments
Labels: Descriptive Programming, Functions
Count & Close all browsers
QTP Script to get total count, names of all open browsers and to close them using descriptive programming..
Set ab=Description.Create
ab("micclass").value="Browser"
Set obj=Desktop.ChildObjects(ab)
msgbox obj.count
For i=0 to obj.count-1
c=obj(i).getroproperty("name")
msgbox(c)
obj(i).Close
Next
0 comments
Labels: Functions
Descriptive programming example
This is an example for descriptive programming in QTP for a checkbox.
In this script we will check whether yahoologinpage(www.yahoomail.com) checkbox is checked or not
Set g=Browser("name:=Yahoo.*").Page("title:=Yahoo.*")
Set obj=Description.Create
obj("htmltag").value="Input"
obj("ClassName").value="webcheckbox"
obj("type").value="checkbox"
Set a=g.childobjects(obj)
c=a(0).getroproperty("checked")
msgbox(c)
If c=0 Then
msgbox "checkbox is not checked"
else
msgbox"checkbox is checked"
End If
0 comments
Labels: Descriptive Programming, Functions, VBscript
Data Driven Testing using Notepad in QTP
Set
f=createobject("scripting.filesystemobject")
Set f1=f.createtextfile("d://file1.txt")
f1.writeline"aaa bbb"
f1.writeline"ccc ddd"
f1.writeline"eee fff"
f1.writeline"ggg hhh"
f1.writeline"iii jjj"
The above script creates a notepad in "d" drive with name file1
aaa bbb
ccc ddd
eee fff
ggg hhh
iii jjj
values are stored in file1.txt.
Set f2=f.opentextfile("d://file1.txt")
While f2.atendofstream<>true
f3=f2.readline
x=split(f3," ")
msgbox x(0)
msgbox x(1)
Wend
The above script is used for data driven using notepad directly.here we are not importing data to excel sheet.
directly values are retreived from notepad.
we are using while loop and reading each line till the end.
split function splits the line where space(" ")occurs.
line is divided to 2 parts.one before space and other after space
for example we have 1st line in notepad as aaa bbb
here aaa is 1st part and bbb is 2nd part
x(0)=aaa
x(1)=bbb
all values are read this way using while loop.
One point to note here is if any line is empty in notepad datadriven testing is stopped before that line.
It will not proceed further.so we have to give values without any empty lines in notepad.
To make u more clear,
suppose u have
aaa bbb
ccc ddd
Datadriven is stopped at aaa and bbb only because next line is empty.datadriven is stopped after 1st line.
0 comments
Labels: Data Table, Database, Functions
Some common QTP functions
In this article I captured some functions which are captured from various sources.
How to check for the broken links (both textlinks and image links) on the page with VB script and not the checkpoints.
---------------------------------------------------------
set
obj=Browser("name:=Blackboard.*").Page("title:=Blackboard.*").Frame("name:=main.*").object.all.tags("IMG")
msgbox obj.length
For each element in obj
s1=element.nameProp
If Browser().Page().Frame().Image("file
name:="&s1,"index:=0").exist(0) then
If Browser().Page().Frame().Image("file
name:="&s1,"index:=0").Object.complete="True" then
msgbox "pass"
else
msgbox "fail"
end if
end if
Next
---------------------------------------------------------
Multiple Exit ways
It’s very easy to control the entry gate to an action or function - there’s only one way to enter them. However, the number of exit gates can vary widely from 1 to many according to the inner logic of the action/function. Today I’m going to address managing multiple exit gates in actions and functions.
When everything goes according to plan, an action flow tends to be very simple. There may be inner loops, If or Select switches, but for the most part, the flow just runs straight down to the last line. The problems usually appear when… well, problems appear. If an application error occurs, or even just an unexpected business logic behavior, there might be no escape from immediately exiting the action. There’s no point trying to input 20 data fields, if the form they’re in didn’t even open, is there?The function is something like the following:
‘.Action Code
If CritialCondition = False Then ExitAction
‘.Continue Action
But this is uninformative. So we add a reporter command:
If CritialCondition = False Then
Reporter.ReportEvent MicFail, "Something terrible has happened", "Aborting"
ExitAction
End If
And we probably got some objects to remove from memory:
If CritialCondition = False Then
Reporter.ReportEvent MicFail, "Something terrible has happened", "Aborting"
oFile.Close
Set oFile = Nothing
ExitAction
End If
============================================
Ho wait, we’ve gathered some data we need to report back:
If CritialCondition = False Then
Reporter.ReportEvent MicFail, "Something terrible has happened", "Aborting"
oFile.Close
Set oFile = Nothing
DataTable("out_EntityID", dtlocalsheet) = sEntityID
‘More here
ExitAction
End If
========================
Well, you probably get the picture. Pretty soon we get massive amounts of code in all the exit gates. This means we have duplicate code to maintain. Duplicate code is the digital manifestation of pure evil – and it’s never a good idea to have pure evil in you actions. Seriously though, this is exactly the kind of things that produces untraceable bugs, and it must be avoided at all cost.
So, how can we deal with this situation? One way is to create an exit gate function. It’s the ONLY function I ever put within an action, and not in an external file. Here’s an example of my action template, with the function:
Dim sResult ‘I store result data and values to be reported up the
‘action-call chain
Dim sActionReport ‘Instead of flooding the log with inner-action messages,
‘I store them, and report all of them at the exit gate.
‘Errors are still reported on-the-fly
‘Action code goes here
‘All the exit gates execute only one command : ActionEnd.
‘It receives two parameters: Boolean for Pass/Fail,
’string for the exit reason
If CriticalCondition = False Then Call ActionEnd(False, "Reason for exiting")
‘Rest of action
‘Even the normal successful action exit is managed through ActionEnd,
’so the last line in every action is:
Call ActionEnd(True, "Action successful")
Sub ActionEnd(bStatus, sReason)
‘Report details
Reporter.ReportEvent MicGeneral, "Inner Action Logs", sActionReport
If bStatus = True Then
Reporter.ReportEvent MicFail, "An error has occurred", sReason
Else
Reporter.ReportEvent MicPass, "Action successful", "See inner logs"
End if
‘Plant datatable info for action-call chain
DataTable("out_Status", dtlocalsheet) = bStatus
DataTable("out_Result", dtlocalsheet) = sResult
‘More if needed
‘Close objects and set to nothing here
‘Other needed exit code
ExitActionIteration
End Sub
With this mechanism, maintaining the exit code becomes very simple, and the logs are much more readable. Ok, so this solves the problem for actions, but what about functions? Well, obviously we can write an inner function within a function, but there is an alternative solution. It’s less elegant than the ActionEnd solution by far, and is harder to maintain, so I recommend using it only in a small number of very complex functions.
The solution is based on the Execute command, so I recommend reading about it in QTP’s help file in case you’re not familiar with it. In a nutshell, the Execute command takes a string, and runs its contents as if it were VBScript code. So for instance the command Execute "msgbox(2)" will pop a message box with the number 2. Here’s an example for the solution, applied to the ComplexFunc function:
Function ComplexFunc
Dim sExitCode
Dim sResult
Dim oFile ‘will be FSO textstream
’separate code lines by vbcrlf or ":"
sExitCode = "oFile.Close" & vbcrlf & _
"Set oFile = Nothing" & vbcrlf & _
"ComplexFunc = sResult"
‘More exit code
‘Function code goes here
‘Exit Gate
If CriticalCondition = False then
sResult = "False, No Connection"
Execute sExitCode
Exit Function
End if
‘More function code
‘Successful exit
Execute sExitCode
End Function
Creating and Calling user define funtion
Test Conditons: Creating and Calling user define funtion
1. Crate small add function and make it compile module.
2. calling that function in other test (using user defined data values)
[ Pre Requesties : Nothing ]
1a. open win runner blank test and add this below data
public function add(in a, in b)
{
return a+b;
}
1b. Go to File menu --> Test Properties (Test Properties window will open)
in General Tab --> Test Type= Compile module and ok
1c.Save the test in some location (Ex c:/tt )
2a.Before writing code , you have to load the funtction in to your folder , globally available to all tests.
2b. Go to Tools menu --> General Options
--- Select Folder option in the left pan.
-- Search Path for called test below enter the path of compile module
(c:/tt) and press "+" button to add in to.
2c. Write down the bleow code in the new test
load("c:/tt");
l= create_input_dialog("Enter First value");
j=create_input_dialog("Enter Second Value");
k=add(l,j);
report_msg(k);
unload("c:/tt");
1 comments
Labels: Functions
Verify Broken Links using VBscript (without checkpoints)
One of my friends just wanted to check for the broken links (both textlinks and image links) on the page with VB script and not the checkpoints.
So the answer for that was the following code
---------------------------------------------------------
set
obj=Browser("name:=Blackboard.*").Page("title:=Blackboard.*").Frame("name:=main.*").object.all.tags("IMG")
msgbox obj.length
For each element in obj
s1=element.nameProp
If Browser().Page().Frame().Image("file
name:="&s1,"index:=0").exist(0) then
If Browser().Page().Frame().Image("file
name:="&s1,"index:=0").Object.complete="True" then
msgbox "pass"
else
msgbox "fail"
end if
end if
Next
---------------------------------------------------------
Code provided by my friend Shiva
0 comments
Labels: Checkpoint, Functions, VBscript
Multiple Exit ways
It’s very easy to control the entry gate to an action or function - there’s only one way to enter them. However, the number of exit gates can vary widely from 1 to many according to the inner logic of the action/function. Today I’m going to address managing multiple exit gates in actions and functions.
When everything goes according to plan, an action flow tends to be very simple. There may be inner loops, If or Select switches, but for the most part, the flow just runs straight down to the last line. The problems usually appear when… well, problems appear. If an application error occurs, or even just an unexpected business logic behavior, there might be no escape from immediately exiting the action. There’s no point trying to input 20 data fields, if the form they’re in didn’t even open, is there?
Thankfully, the nice guys and gals at Mercury have taken this into account, and have provided us with the ExitAction and ExitActionIteration commands. So usually we’ve got something like the following:
‘.Action Code
If CritialCondition = False Then ExitAction
‘.Continue Action
But this is uninformative. So we add a reporter command:
If CritialCondition = False Then
Reporter.ReportEvent MicFail, "Something terrible has happened", "Aborting"
ExitAction
End If
And we probably got some objects to remove from memory:
If CritialCondition = False Then
Reporter.ReportEvent MicFail, "Something terrible has happened", "Aborting"
oFile.Close
Set oFile = Nothing
ExitAction
End If
============================================
Ho wait, we’ve gathered some data we need to report back:
If CritialCondition = False Then
Reporter.ReportEvent MicFail, "Something terrible has happened", "Aborting"
oFile.Close
Set oFile = Nothing
DataTable("out_EntityID", dtlocalsheet) = sEntityID
‘More here
ExitAction
End If
========================
Well, you probably get the picture. Pretty soon we get massive amounts of code in all the exit gates. This means we have duplicate code to maintain. Duplicate code is the digital manifestation of pure evil – and it’s never a good idea to have pure evil in you actions. Seriously though, this is exactly the kind of things that produces untraceable bugs, and it must be avoided at all cost.
So, how can we deal with this situation? One way is to create an exit gate function. It’s the ONLY function I ever put within an action, and not in an external file. Here’s an example of my action template, with the function:
Dim sResult ‘I store result data and values to be reported up the
‘action-call chain
Dim sActionReport ‘Instead of flooding the log with inner-action messages,
‘I store them, and report all of them at the exit gate.
‘Errors are still reported on-the-fly
‘Action code goes here
‘All the exit gates execute only one command : ActionEnd.
‘It receives two parameters: Boolean for Pass/Fail,
’string for the exit reason
If CriticalCondition = False Then Call ActionEnd(False, "Reason for exiting")
‘Rest of action
‘Even the normal successful action exit is managed through ActionEnd,
’so the last line in every action is:
Call ActionEnd(True, "Action successful")
Sub ActionEnd(bStatus, sReason)
‘Report details
Reporter.ReportEvent MicGeneral, "Inner Action Logs", sActionReport
If bStatus = True Then
Reporter.ReportEvent MicFail, "An error has occurred", sReason
Else
Reporter.ReportEvent MicPass, "Action successful", "See inner logs"
End if
‘Plant datatable info for action-call chain
DataTable("out_Status", dtlocalsheet) = bStatus
DataTable("out_Result", dtlocalsheet) = sResult
‘More if needed
‘Close objects and set to nothing here
‘Other needed exit code
ExitActionIteration
End Sub
With this mechanism, maintaining the exit code becomes very simple, and the logs are much more readable. Ok, so this solves the problem for actions, but what about functions? Well, obviously we can write an inner function within a function, but there is an alternative solution. It’s less elegant than the ActionEnd solution by far, and is harder to maintain, so I recommend using it only in a small number of very complex functions.
The solution is based on the Execute command, so I recommend reading about it in QTP’s help file in case you’re not familiar with it. In a nutshell, the Execute command takes a string, and runs its contents as if it were VBScript code. So for instance the command Execute "msgbox(2)" will pop a message box with the number 2. Here’s an example for the solution, applied to the ComplexFunc function:
Function ComplexFunc
Dim sExitCode
Dim sResult
Dim oFile ‘will be FSO textstream
’separate code lines by vbcrlf or ":"
sExitCode = "oFile.Close" & vbcrlf & _
"Set oFile = Nothing" & vbcrlf & _
"ComplexFunc = sResult"
‘More exit code
‘Function code goes here
‘Exit Gate
If CriticalCondition = False then
sResult = "False, No Connection"
Execute sExitCode
Exit Function
End if
‘More function code
‘Successful exit
Execute sExitCode
End Function
0 comments
Labels: Functions
Creating and Calling user define funtion
Test Conditons: Creating and Calling user define funtion
1. Crate small add function and make it compile module.
2. calling that function in other test (using user defined data values)
[ Pre Requesties : Nothing ]
1a. open win runner blank test and add this below data
public function add(in a, in b)
{
return a+b;
}
1b. Go to File menu --> Test Properties (Test Properties window will open)
in General Tab --> Test Type= Compile module and ok
1c.Save the test in some location (Ex c:/tt )
2a.Before writing code , you have to load the funtction in to your folder , globally available to all tests.
2b. Go to Tools menu --> General Options
--- Select Folder option in the left pan.
-- Search Path for called test below enter the path of compile module
(c:/tt) and press "+" button to add in to.
2c. Write down the bleow code in the new test
load("c:/tt");
l= create_input_dialog("Enter First value");
j=create_input_dialog("Enter Second Value");
k=add(l,j);
report_msg(k);
unload("c:/tt");
[ load( ) , unload ( ) - to lload and unload from the memory ]
[Same way You can use Winrunner TSL Script to User Defined function
0 comments
Labels: Functions
Using Database Functions
The code below contains a set of useful functions that can be used in QuickTest Professional.
'Example of how to use functions.
''******************************************************************************************
' Example of how to use DSN created for the database of sample Flight application.
''******************************************************************************************
SQL="SELECT * FROM ORDERS"
connection_string="QT_Flight32"
isConnected = db_connect ( curConnection ,connection_string )
If isConnected = 0 then
' Execute the basic SQL statement
set myrs=db_execute_query( curConnection , SQL )
' Report the query and the connection string
Reporter.ReportEvent micInfo ,"Executed query and created recordset ","Connection_string is ==> " & connection_string & " SQL query is ===> " & SQL
' Show the number of rows in the table using a record set
msgBox " Quantity of rows in queried DB ( db_get_rows_count )==> " & db_get_rows_count( myrs )
' Show the number of rows in the table using a new SQL statement
msgBox " Quantity of rows in queried DB (db_get_rows_count_SQL ) ==> " & db_get_rows_count_SQL( curConnection , "SELECT COUNT(*) FROM ORDERS" )
' Change a value of a field in an existing row
rc = db_set_field_value (curConnection, "ORDERS" , "Agents_Name" , "test", "Agents_Name", "AGENT_TESTER")
' Examples of how to retrieve values from the table
msgBox "val row 0 col 0: " & db_get_field_value( myrs , 0 , 0 )
msgBox "val row 0 col 1: " & db_get_field_value( myrs , 0 , 1 )
msgBox "val row 1 col Name: " & db_get_field_value( myrs , 1 , "Agents_Name" )
msgBox "val SQL row 1 col Name: " & db_get_field_value_SQL( curConnection , "ORDERS" , 1 , "Agents_Name" )
db_disconnect curConnection
End If
''******************************************************************************************
' Database Functions library
''******************************************************************************************
'db_connect
' ---------------
' The function creates a new connection session to a database.
' curSession - The session name (string)
' connection_string - A connection string
' for example the connection_string can be "DSN=SQLServer_Source;UID=SA;PWD=abc123"
''******************************************************************************************
Function db_connect( byRef curSession ,connection_string)
dim connection
on error Resume next
' Opening connection
set connection = CreateObject("ADODB.Connection")
If Err.Number <> 0 then
db_connect= "Error # " & CStr(Err.Number) & " " & Err.Description
err.clear
Exit Function
End If
connection.Open connection_string
If Err.Number <> 0 then
db_connect= "Error # " & CStr(Err.Number) & " " & Err.Description
err.clear
Exit Function
End If
set curSession=connection
db_connect=0
End Function
''******************************************************************************************
' db_disconnect
' ---------------------
' The function disconnects from the database and deletes the session.
' curSession - the session name (string)
''******************************************************************************************
Function db_disconnect( byRef curSession )
curSession.close
set curSession = Nothing
End Function
''******************************************************************************************
' db_execute_query
' ---------------------------
' The function executes an SQL statement.
' Note that a db_connect for (arg1) must be called before this function
' curSession - The session name (string)
' SQL - An SQL statement
''******************************************************************************************
Function db_execute_query ( byRef curSession , SQL)
set rs = curSession.Execute( SQL )
set db_execute_query = rs
End Function
''******************************************************************************************
' db_get_rows_count
' ----------------------------
' The function returns the number of rows in the record set
' curRS - Variable, containing a record set, that contains all values that retrieved from the database by query execution
''******************************************************************************************
Function db_get_rows_count( byRef curRS )
dim rows
rows = 0
curRS.MoveFirst
Do Until curRS.EOF
rows = rows+1
curRS.MoveNext
Loop
db_get_rows_count = rows
End Function
''******************************************************************************************
' db_get_rows_count_SQL
' ------------------------------------
' The function returns the number of rows that are the result of a given SQL statement
' curSession - The session name (string)
' CountSQL - SQL statement
''******************************************************************************************
Function db_get_rows_count_SQL( byRef curSession ,CountSQL )
dim cur_rs
set cur_rs = curSession.Execute( CountSQL )
db_get_rows_count_SQL = cur_rs.fields(0).value
End Function
''******************************************************************************************
' db_get_field_value_SQL
' -----------------------------------
' curSession - Variable that denotes the current active connection
' tableName - Name of the table, from which the value should be retrieved
' rowIndex - Row number
' colName - The column name
''******************************************************************************************
Function db_get_field_value_SQL( curSession , tableName , rowIndex , colName )
dim rs
SQL = " select " & colName & " from " & tableName
set rs = curSession.Execute( SQL )
rs.move rowIndex
db_get_field_value_SQL = rs.fields(colName).value
End Function
''******************************************************************************************
' db_get_field_value
' --------------------------
' The function returns the value of a single item of an executed query.
' Note that a db_execute_query for (arg1) must called before this function
' curRecordSet - Variable, containing a record set, that contains all values retrieved from the database by query execution
' rowIndex - The row index number (zero-based)
' colIndex - The column index number (zero-based) or the column name.
' returned values
' -1 - Requested field index more than exists more than once in record set
''******************************************************************************************
Function db_get_field_value( curRecordSet , rowIndex , colIndex )
dim curRow
curRecordSet.MoveFirst
count_fields = curRecordSet.fields.count-1
If ( TypeName(colIndex)<> "String" ) and ( count_fields < colIndex ) then
db_get_field_value = -1 'requested field index exists more than once in recordset
Else
curRecordSet.Move rowIndex
db_get_field_value = curRecordSet.fields(colIndex).Value
End If
End Function
''******************************************************************************************
' db_set_field_value
' ---------------------------
' The function changes the value of a field according to a search criteria.
' We search for a certain row according to a column name and the desired vale, then we change a value in that row according
' to a desired columns
' curConnection - The session name (string)
' tableName - Name of the table from which the value should be retrieved
' colFind - The column which to search for the criteria
' colFindValue - The value for which to search in the column
' colChange - The column in which we want to change the value
' colChangeValue - The new value
' returned values
' -1 - Requested field index that does not exist in the recordset
''******************************************************************************************
Function db_set_field_value(curConnection, tableName , colFind , colFindValue, colChange, colChangeValue)
dim curRow
dim updateSQL
dim checkSQL
checkSQL = "select * from Details"
set myrs1 = db_execute_query( curConnection , SQL )
myrs1.MoveFirst
count_fields = myrs1.fields.count
If ( TypeName(colFind)<> "String" ) or ( TypeName(colChange)<> "String" ) then
db_set_field_value = -1 'requested field index that does not exists in the record set
Else
updateSQL = "UPDATE " & tableName & " SET " & colChange & "='" & colChangeValue & "' WHERE " & colFind & "='" & colFindValue & "'"
set myrs1 = db_execute_query( curConnection , updateSQL )
db_set_field_value = 1 'operation suceeded
End If
End Function
''******************************************************************************************
' db_add_row
' -----------------
' The function adds a new row to the desired table
' curConnection - Variable, containing a recordset, that contains all the values to be retrieved from the database by query execution
' tableName - Name of the table, from which the value should be retrieved
' values - Array that contains values to be entered in a new row to the table
' Note: The function must receive values for all the columns in the table.
' returned value.
' -1 - The number of values to be entered to the table does not match the number of columns
' 1 - Execution of the query succeed and the data was entered to the table
''******************************************************************************************
Function db_add_row(curConnection, tableName , byRef values)
dim i
dim updateSQL
dim myrs1
updateSQL = "INSERT INTO " & tableName & " VALUES ("
arrLen = UBound (values) - LBound (values) + 1
set myrs1=db_execute_query( curConnection , SQL )
myrs1.MoveFirst
count_fields = myrs1.fields.count
' Check whether the number of values match the number of columns
If arrLen <> count_fields then
db_add_row = -1
Else
For i = 0 to arrLen-1
updateSQL = updateSQL & values (i)
If i <> arrLen-1 then
updateSQL = updateSQL & ","
End If
Next
updateSQL = updateSQL & ")"
set myrs1 = db_execute_query( curConnection , updateSQL )
db_add_row = 1
End If
End Function
''******************************************************************************************
' represent_values_of_RecordSet
' ---------------------------------------------
' The function reports all the values of fields in a record set
' curRS - Variable, containing the recordset, that contains all the values that were retrieved from the database by the query execution
''******************************************************************************************
Function represent_values_of_RecordSet( myrs)
dim curRowString
myrs.MoveFirst
reporter.ReportEvent 4,"Fields quantity" , myrs.fields.count
count_fields = myrs.fields.count-1
curRow=0
Do Until myrs.EOF
curRowString= ""
curRow = curRow+1
For ii=0 to count_fields
curRowString = curRowString& "Field " &"==> " & myrs.fields(ii).Name &" : Value ==>" & myrs.fields(ii).Value & vbCrLf
Next
myrs.MoveNext
reporter.ReportEvent 4,"Current row"& curRow , curRowString
Loop
End Function
PreviousNext
0 comments
Labels: Functions
Using the File System Object (FSO)
The following code includes a set of complex and simple functions to serve as examples of the possible uses and applications of Microsoft FSO.
dim oFSO
' Create the file system object
set oFSO = CreateObject ("Scripting.FileSystemObject")
'Option Explicit
' *******************************************************************************************
' Create a new txt file
' Parameters:
' FilePath - location of the file and its name
' *******************************************************************************************
Function CreateFile (FilePath)
' Variable that will hold the new file object
dim NewFile
' Create the new text ile
set NewFile = oFSO.CreateTextFile(FilePath, True)
set CreateFile = NewFile
End Function
' *******************************************************************************************
' Check if a specific file exist
' Parameters:
' FilePath - Location of the file and its name
' *******************************************************************************************
Function CheckFileExists (FilePath)
' Check if the file exists
CheckFileExists = oFSO.FileExists(FilePath)
End Function
' *******************************************************************************************
' Write data to file
' Parameters:
' FileRef - Reference to the file
' str - Data to be written to the file
*******************************************************************************************
Function WriteToFile (byref FileRef,str)
' Write str to the text file
FileRef.WriteLine(str)
End Function
' *******************************************************************************************
' Read line from file
' Parameters:
' FileRef - reference to the file
' *******************************************************************************************
Function ReadLineFromFile (byref FileRef)
' Read line from text file
ReadLineFromFile = FileRef.ReadLine
End Function
' *******************************************************************************************
' Closes an open file.
' Parameters:
' FileRef - Reference to the file
' *******************************************************************************************
Function CloseFile (byref FileRef)
FileRef.close
End Function
'******************************************************************************************
' Opens a specified file and returns an object that can be used to
' read from, write to, or append to the file.
' Parameters:
' FilePath - Location of the file and its name
' mode options are:
' ForReading - 1
' ForWriting - 2
' ForAppending - 8
' *******************************************************************************************
Function OpenFile (FilePath,mode)
' Open the txt file and return the File object
set OpenFile = oFSO.OpenTextFile(FilePath, mode, True)
End Function
' *******************************************************************************************
' Closes an open file.
' Parameters:
' FilePathSource - Location of the source file and its name
' FilePathDest - Location of the destination file and its name
' *******************************************************************************************
Sub FileCopy ( FilePathSource,FilePathDest)
' copy source file to destination file
oFSO.CopyFile FilePathSource, FilePathDest
End Sub
' *******************************************************************************************
' Delete a file.
' Parameters:
' FilePath - Location of the file to be deleted
' *******************************************************************************************
Sub FileDelete ( FilePath)
' Copy source file to destination file
oFSO.DeleteFile ( FilePath)
End Sub
' *******************************************************************************************
' Compare two text files.
'
' Parameters:
' FilePath1 - Location of the first file to be compared
' FilePath2 - Location of the second file to be compared
' FilePathDiff - Location of the differences file
' ignoreWhiteSpace - Controls whether or ignore differences in white space characters
' true - Ignore differences in white space
' false - Do not ignore difference in white space
' Return Value: true if files are identical, false otherwise'
' *******************************************************************************************
Function FileCompare (byref FilePath1, byref FilePath2, byref FilePathDiff, ignoreWhiteSpace)
dim differentFiles
differentFiles = false
dim f1, f2, f_diff
' Open the files
set f1 = OpenFile(FilePath1,1)
set f2 = OpenFile(FilePath2,1)
set f_diff = OpenFile(FilePathDiff,8)
dim rowCountF1, rowCountF2
rowCountF1 = 0
rowCountF2 = 0
dim str
' Count how many lines there are in the first file
While not f1.AtEndOfStream
str = ReadLineFromFile(f1)
rowCountF1= rowCountF1 + 1
Wend
' Count how many lines there are in the second file
While not f2.AtEndOfStream
str = ReadLineFromFile(f2)
rowCountF2= rowCountF2 + 1
Wend
' Re-open the files to go back to the first line in the files
set f1 = OpenFile(FilePath1,1)
set f2 = OpenFile(FilePath2,1)
' compare the number of lines in the two files.
' assign biggerFile - The file that contain more lines
' assign smallerFile - The file that contain fewer lines
dim biggerFile, smallerFile
set biggerFile = f1
set smallerFile = f2
If ( rowCountF1 < rowCountF2) Then
set smallerFile = f1
set biggerFile = f2
End If
dim lineNum,str1, str2
lineNum = 1
str = "Line" & vbTab & "File1" & vbTab & vbTab & "File2"
WriteToFile f_diff,str
' Loop on all the lines in the smaller file
While not smallerFile.AtEndOfStream
' read line from both files
str1 = ReadLineFromFile(f1)
str2 = ReadLineFromFile(f2)
' Check if we need to ignore white spaces, if yes, trim the two lines
If Not ignoreWhiteSpace Then
Trim(str1)
Trim(str2)
End If
' If there is a difference between the two lines, write them to the differences file
If not (str1 = str2) Then
differentFiles = true
str = lineNum & vbTab & str1 & vbTab & vbTab & str2
WriteToFile f_diff,str
End If
lineNum = lineNum + 1
Wend
' Loop through the bigger lines, to write its line to the different file
While not biggerFile.AtEndOfStream
str1 = ReadLineFromFile(biggerFile)
str = lineNum & vbTab & "" & vbTab & vbTab & str2
WriteToFile f_diff,str
lineNum = lineNum + 1
Wend
FileCompare = Not differentFiles
End function
' ************** Example of using these functions **********************
FilePath1 = "D:\temp\FSO\txt1.txt"
FilePath2 = "D:\temp\FSO\txt2.txt"
FilePathDiff = "D:\temp\FSO\txt_diff.txt"
d = FileCompare(FilePath1,FilePath2,FilePathDiff,false)
FilePath = "D:\temp\FSO\txt.txt"
set fold = FolderCreate ( "D:\temp\FSO
set f = OpenFile(FilePath,8)
' = WriteToFile(f,"test line")
d = CloseFile(f)
set f = CreateFile(FilePath)
Fexist= CheckFileExists(FilePath)
d = WriteToFile(f,"first line")
d = WriteToFile(f,"second line")
d = CloseFile(f)
FileCopy "D:\temp\FSO\txt.txt","D:\temp\FSO\txt1.txt"
FileDelete "D:\temp\FSO\txt1.txt"
0 comments
Labels: Functions
Using Microsoft Word Spell Check
The following code shows a function for checking the number of spelling and grammar errors in a string.
Function NumberOfSpellErrors(strText)
Dim objMsWord
Set objMsWord = CreateObject("Word.Application")
objMsWord.WordBasic.FileNew
objMsWord.WordBasic.Insert strText
NumberOfSpellErrors = objMsWord.ActiveDocument.SpellingErrors.Count
objMsWord.Documents.Close (False)
objMsWord.Quit ' close the application
Set objMsWord = Nothing' Clear object memory
End Function
' The following function uses the Spell errors function to check a specific property
' of all the objects with a given description which are under a given parent
Sub CheckAllObjects(ParentObj, ObjDesc, PropName)
Dim ObjCol, idx, PropValue, OldReportMode
OldReportMode = Reporter.Filter
Reporter.Filter = 2 ' Report only errors
If (IsNull(ParentObj)) Then
Set ObjCol = Desktop.ChildObjects(ObjDesc)
Else
Set ObjCol = ParentObj.ChildObjects(ObjDesc)
End If
For idx=0 to ObjCol.count-1
PropValue = ObjCol.Item(idx).GetROProperty(PropName)
RetVal = NumberOfSpellErrors(PropValue) ' The actual spell check result
If (RetVal > 0) Then
ReportText = "Object #" & idx+1 & ": The '" & PropName & "' Property has " & RetVal & " spell errors (" & PropValue & ")"
Reporter.ReportEvent 1, "Spell Check", ReportText
End If
Next
Reporter.Filter = OldReportMode
End Sub
'''''''''''''''''''''''''''''''''''''
' An example of usage:
' Go over all the static objects in the Login window of the Flight Application
' and for each object check the text for spelling and grammatical errors
'''''''''''''''''''''''''''''''''''''
' Go over all the links in the page and report all the ones that fail the spellcheck
Set Desc = Description.Create()
Desc("nativeclass").Value = "Static"
Set Obj = Dialog("nativeclass:=#32770", "text:=Login")
' Invoke the Flight Application before calling the function
CheckAllObjects Obj, Desc, "text"
0 comments
Labels: Functions
Using Microsoft Excel Objects in QTP
The following code includes a set of complex and simple functions to serve as examples of the possible uses and applications of Microsoft Excel objects.
Dim ExcellApp 'As Excel.Application
Dim excelSheet1 'As Excel.worksheet
Dim excelSheet2 'As Excel.worksheet
Set ExcelApp = CreateExcel()
'Create a workbook with two worksheets
ret = RenameWorksheet(ExcelApp, "Book1", "Sheet1", "Example1 Sheet Name")
ret = RenameWorksheet(ExcelApp, "Book1", "Sheet2", "Example2 Sheet Name")
ret = RemoveWorksheet(ExcelApp, "Book1", "Sheet3")
'Save as the workbook under a different name
ret = SaveWorkbook(ExcelApp, "Book1", "D:\Example1.xls")
'Fill the worksheets
Set excelSheet1 = GetSheet(ExcelApp, "Example1 Sheet Name")
Set excelSheet2 = GetSheet(ExcelApp, "Example2 Sheet Name")
For column = 1 to 10
For row = 1 to 10
SetCellValue excelSheet1, row, column, row + column
SetCellValue excelSheet2, row, column, row + column
Next
Next
'Compare the two worksheets
ret = CompareSheets(excelSheet1, excelSheet2, 1, 10, 1, 10, False)
If ret Then
MsgBox "The two worksheets are identical"
End If
'Change the values in one sheet
SetCellValue excelSheet1, 1, 1, "Yellow"
SetCellValue excelSheet2, 2, 2, "Hello"
'Compare the worksheets again
ret = CompareSheets(excelSheet1, excelSheet2, 1, 10, 1, 10, True)
If Not ret Then
MsgBox "The two worksheets are not identical"
End If
'Save the workbook by index identifier
SaveWorkbook ExcelApp, 1, ""
'Close the Microsoft Excel application
CloseExcel ExcelApp
' *************************** Function Library **************************************
Dim ExcelApp 'As Excel.Application
Dim excelSheet 'As Excel.worksheet
Dim excelBook 'As Excel.workbook
Dim fso 'As Scripting.FileSystemObject
' This function returns a new Microsoft Excel object with a default new workbook
Function CreateExcel() 'As Excel.Application
Dim excelSheet 'As Excel.worksheet
Set ExcelApp = CreateObject("Excel.Application") 'Create a new Microsoft Excel object
ExcelApp.Workbooks.Add
ExcelApp.Visible = True
Set CreateExcel = ExcelApp
End Function
'This function closes the given Microsoft Excel object
'excelApp - an Excel application object to be closed
Sub CloseExcel(ExcelApp)
Set excelSheet = ExcelApp.ActiveSheet
Set excelBook = ExcelApp.ActiveWorkbook
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.CreateFolder "C:\Temp"
fso.DeleteFile "C:\Temp\ExcelExamples.xls"
excelBook.SaveAs "C:\Temp\ExcelExamples.xls"
ExcelApp.Quit
Set ExcelApp = Nothing
Set fso = Nothing
Err = 0
On Error GoTo 0
End Sub
'The SaveWorkbook method saves a workbook according to the workbook identifier.
'The method overwrites the previously saved file in the given path.
'excelApp - a reference to the Microsoft Excel application
'workbookIdentifier - The name or number of the requested workbook
'path - The location to which the workbook should be saved
'Returns "OK" on success and "Bad Workbook Identifier" on failure
Function SaveWorkbook(ExcelApp, workbookIdentifier, path) 'As String
Dim workbook 'As Excel.workbook
On Error Resume Next
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
On Error GoTo 0
If Not workbook Is Nothing Then
If path = "" Or path = workbook.FullName Or path = workbook.Name Then
workbook.Save
Else
Set fso = CreateObject("Scripting.FileSystemObject")
'If the path has no file extension then add the 'xls' extension
If InStr(path, ".") = 0 Then
path = path & ".xls"
End If
On Error Resume Next
fso.DeleteFile path
Set fso = Nothing
Err = 0
On Error GoTo 0
workbook.SaveAs path
End If
SaveWorkbook = "OK"
Else
SaveWorkbook = "Bad Workbook Identifier"
End If
End Function
'The SetCellValue method sets the given 'value' in the cell which is identified by
'its row, column, and parent Microsoft Excel sheet
'excelSheet - The Microsoft Excel sheet that is the parent of the requested cell
'row - the cell's row in the excelSheet
'column - the cell's column in the excelSheet
'value - the value to be set in the cell
Sub SetCellValue(excelSheet, row, column, value)
On Error Resume Next
excelSheet.Cells(row, column) = value
On Error GoTo 0
End Sub
'The GetCellValue returns the cell's value according to its row, column, and sheet
'excelSheet - The Microsoft Excel sheet in which the cell exists
'row - The cell's row
'column - The cell's column
'return 0 if the cell cannot be found
Function GetCellValue(excelSheet, row, column)
value = 0
Err = 0
On Error Resume Next
tempValue = excelSheet.Cells(row, column)
If Err = 0 Then
value = tempValue
Err = 0
End If
On Error GoTo 0
GetCellValue = value
End Function
'The GetSheet method returns a Microsoft Excel sheet according to the sheet Identifier
'ExcelApp - The Microsoft Excel application which is the parent of the requested sheet
'sheetIdentifier - The name or the number of the requested Microsofr Excel sheet
'return Nothing on failure
Function GetSheet(ExcelApp, sheetIdentifier) 'As Excel.worksheet
On Error Resume Next
Set GetSheet = ExcelApp.Worksheets.Item(sheetIdentifier)
On Error GoTo 0
End Function
'The InsertNewWorksheet method inserts a new worksheet into the active workbook or
'the workbook identified by the workbookIdentifier. The new worksheet will get a default
'name if the sheetName parameter is empty, otherwise the sheet has the sheetName
'as its name.
'Return - The new sheet as an object
'ExcelApp - The Microsoft Excel application object into which the new worksheet should be added
'workbookIdentifier - An optional identifier of the worksheet into which the new worksheet should be added
'sheetName - The optional name of the new worksheet.
Function InsertNewWorksheet(ExcelApp, workbookIdentifier, sheetName) 'As Excel.worksheet
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
'If the workbookIdentifier is empty, work on the active workbook
If workbookIdentifier = "" Then
Set workbook = ExcelApp.ActiveWorkbook
Else
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
Set InsertNewWorksheet = Nothing
Err = 0
Exit Function
End If
On Error GoTo 0
End If
sheetCount = workbook.Sheets.Count
workbook.Sheets.Add , sheetCount
Set worksheet = workbook.Sheets(sheetCount + 1)
'If the sheetName is not empty, set the new sheet's name to sheetName
If sheetName <> "" Then
worksheet.Name = sheetName
End If
Set InsertNewWorksheet = worksheet
End Function
'The RenameWorksheet method renames a worksheet'
'ExcelApp - The Microsoft Excel application that is the worksheet's parent
'workbookIdentifier - The worksheet's parent workbook identifier
'worksheetIdentifier - The worksheet's identifier
'sheetName - The new name for the worksheet
Function RenameWorksheet(ExcelApp, workbookIdentifier, worksheetIdentifier, sheetName) 'As String
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
RenameWorksheet = "Bad Workbook Identifier"
Err = 0
Exit Function
End If
Set worksheet = workbook.Sheets(worksheetIdentifier)
If Err <> 0 Then
RenameWorksheet = "Bad Worksheet Identifier"
Err = 0
Exit Function
End If
worksheet.Name = sheetName
RenameWorksheet = "OK"
End Function
'The RemoveWorksheet method removes a worksheet from a workbook
'ExcelApp - The Microsoft Excel application that is the worksheet's parent
'workbookIdentifier - The worksheet's parent workbook identifier
'worksheetIdentifier - The worksheet's identifier
Function RemoveWorksheet(ExcelApp, workbookIdentifier, worksheetIdentifier) 'As String
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
RemoveWorksheet = "Bad Workbook Identifier"
Exit Function
End If
Set worksheet = workbook.Sheets(worksheetIdentifier)
If Err <> 0 Then
RemoveWorksheet = "Bad Worksheet Identifier"
Exit Function
End If
worksheet.Delete
RemoveWorksheet = "OK"
End Function
'The CreateNewWorkbook method creates a new workbook in the Microsoft Excel application
'ExcelApp - The Microsoft Excel application to which an new Microsoft Excel workbook will be added
Function CreateNewWorkbook(ExcelApp)
Set NewWorkbook = ExcelApp.Workbooks.Add()
Set CreateNewWorkbook = NewWorkbook
End Function
'The OpenWorkbook method opens a previously saved Microsoft Excel workbook and adds it to the Application
'excelApp - The Microsoft Excel application to which the workbook will be added.
'path - The path of the workbook that will be opened
'Returns Nothing on failure
Function OpenWorkbook(ExcelApp, path)
On Error Resume Next
Set NewWorkbook = ExcelApp.Workbooks.Open(path)
Set OpenWorkbook = NewWorkbook
On Error GoTo 0
End Function
'The ActivateWorkbook method sets one of the workbooks in the application as the active workbook
'ExcelApp - The workbook's parent Microsft Excel application
'workbookIdentifier - The name or the number of the workbook
Sub ActivateWorkbook(ExcelApp, workbookIdentifier)
On Error Resume Next
ExcelApp.Workbooks(workbookIdentifier).Activate
On Error GoTo 0
End Sub
'The CloseWorkbook method closes an open workbook
'ExcelApp - The parent Microsoft Excel application of the workbook
'workbookIdentifier - The name or the number of the workbook
Sub CloseWorkbook(ExcelApp, workbookIdentifier)
On Error Resume Next
ExcelApp.Workbooks(workbookIdentifier).Close
On Error GoTo 0
End Sub
'The CompareSheets method compares two sheets.
'If there is a difference between the two sheets then the value in the second sheet
'will be changed to red and contain the string:
'"Compare conflict - Value was 'Value2', Expected value is 'value2'"
'sheet1, sheet2 - The Microsoft Excel sheets to be compared
'startColumn - The column to start comparing in the two sheets
'numberOfColumns - The number of columns to be compared
'startRow - The row to start comparing in the two sheets
'numberOfRows - The number of rows to be compared
Function CompareSheets(sheet1, sheet2, startColumn, numberOfColumns, startRow, numberOfRows, trimed) 'As Boolean
Dim returnVal 'As Boolean
returnVal = True
'If one of the sheets does not exist, do not continue the process
If sheet1 Is Nothing Or sheet2 Is Nothing Then
CompareSheets = False
Exit Function
End If
'Loop through the table and fill values into the two worksheets
For r = startRow to (startRow + (numberOfRows - 1))
For c = startColumn to (startColumn + (numberOfColumns - 1))
Value1 = sheet1.Cells(r, c)
Value2 = sheet2.Cells(r, c)
'If 'trimed' equals True then user wants to ignore blank spaces
If trimed Then
Value1 = Trim(Value1)
Value2 = Trim(Value2)
End If
'if the values of a cell are not equal in the two worksheets
'create an indicator that the values are not equal and set the return value
'to False
If Value1 <> Value2 Then
Dim cell 'As Excel.Range
sheet2.Cells(r, c) = "Compare conflict - Value was '" & Value2 & "', Expected value is '" & Value1 & "'."
Set cell = sheet2.Cells(r, c)
cell.Font.Color = vbRed
returnVal = False
End If
Next
Next
CompareSheets = returnVal
End Function
0 comments
Labels: Functions
Highlighting Objects from the Same Class
The code below helps resolve the Object not unique problem in QTP. It highlights all the runtime objects that have the same description.
' Sample usage: Assume that WinButton description is not unique
HighlightAll Dialog("Options").WinButton("Browse")
' Routine that highlights all the objects
Sub HighlightAll(TestObject)
Dim Parent, Desc, Props, PropsCount, MaxIndex, i, Objs
If IsEmpty(TestObject.GetTOProperty("parent")) Then
Set Parent = Desktop
Else
Set Parent = TestObject.GetTOProperty("parent")
End If
Set Desc = Description.Create
Set Props = TestObject.GetTOProperties
PropsCount = Props.Count - 1
For i = 0 to PropsCount
Desc(Props(i).Name).Value = Props(i).Value
Next
Set Objs = Parent.ChildObjects(Desc)
MaxIndex= Objs.Count - 1
For i = 0 to MaxIndex
Objs.Item(i).Highlight
Next
End Sub
0 comments
Labels: Functions
Enumerating Application Objects
The code below illustrates one way of enumerating the application objects while performing an operation on each object.
Function EnumerateApp(ParentObj, Desc, OperationMethod, PostOperationMethod, RestoreMethod)
dim ObjCol, CurrentObj, idx
idx = 0
' Retrieve a collection of all the objects of the given description
Set ObjCol = ParentObj.ChildObjects(Desc)
Do While (idx < ObjCol.Count)
' Get the current object
set CurrentObj = ObjCol.item(idx)
' Perform the desired operation on the object
eval("CurrentObj." & OperationMethod)
' Perform the post operations (after the object operation)
eval(PostOperationMethod & "(ParentObj, CurrentObj)")
' Return the application to the original state
eval(RestoreMethod & "(ParentObj, CurrentObj)")
idx = idx + 1
' Retrieve the collection of objects
' (Since the application might have changed)
Set ObjCol = ParentObj.ChildObjects(Desc)
Loop
End Function
' ********************************** An Example of usage **********************
' Report all the pages referred to by the current page
' ***********************************************************************************
Function ReportPage(ParentObj, CurrentObj)
dim FuncFilter, PageTitle
PageTitle = ParentObj.GetROProperty("title")
FuncFilter = Reporter.Filter
Reporter.Filter = 0
Reporter.ReportEvent 0, "Page Information", "page title " & PageTitle
Reporter.Filter = FuncFilter
End Function
Function BrowserBack(ParentObj, CurrentObj)
BrowserObj.Back
End Function
' Save the Report Filter mode
OldFilter = Reporter.Filter
Reporter.Filter = 2 ' Enables Errors Only
' Create the description of the Link object
Set Desc = Description.Create()
Desc("html tag").Value = "A"
Set BrowserObj = Browser("creationtime:=0")
Set PageObj = BrowserObj.Page("index:=0")
' Start the enumeration
call EnumerateApp(PageObj, Desc, "Click", "ReportPage", "BrowserBack")
Reporter.Filter = OldFilter ' Returns the original filter
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment