Search This Blog

Welcome to Machers Blog

Blogging the world of Technology and Testing which help people to build their career.

Wednesday, January 25, 2012

CNG Filling Points In Hyderabad, AP, India

CNG refueling points operated by BGL(Bhagyanagar Gas) in collaboration with HPCL in Hyderabad till Dec'2011 are

1. BGL Mother Station, Shamirpet, Hyderabad-Karimnagar Route
2. COCO BGL Saroornagar, Near Saroornagar stadium, Hyderabad-Vijayawada Highway (Operates from 7AM- 7PM)
3. Autocare Centre,R.P.road, Secunderabad- Near Bible House, Adjacent to Jirra
4. Chakra Filling Station, Nampally Station road, Nampally - on Abids to Nampally route, besides Pullareddy sweet house
5. Sapthagiri Filling Station, Meerpet, Near Champapet
6. Daraboina Filling Station, Uppal-Nagole ring road, Near Nagole bridge
7. Radharaman Service Station, Narayanguda - Opposite to Bloodbank, Narayanguda
8. K.V.S Service Station, Bowenpally, Hyd-Nizamabad-Nagpur Highway starting
9. Ramesh Fuel Point, Dhoolpet
10. Habib Fuel Station, Langarhouse, near Mehdipatnam

and another 50 filling stations are yet to be alloted by Dec'2012 as per sources.

Monday, October 3, 2011

Comparing Excel sheets, workbooks

'Call CompareExcelAndProvideResultInAnotherSheet("C:\Documents and Settings\Metson\Desktop\test Excel\Book2.xls", "C:\Documents and Settings\Metson\Desktop\test Excel\Book1.xls")
'Call Compare2ExcelsCellByCell("C:\Documents and Settings\Metson\Desktop\test Excel\Book2.xls", "C:\Documents and Settings\Metson\Desktop\test Excel\Book1.xls")
Call Compare2ExcelsCellByCell("C:\Jackson-Works\BIChangedTxt\Test_USAGE_090602.csv", "C:\Jackson-Works\BIChangedTxt\POM_ADHOC_090602.csv")
Msgbox "Done Comparing Results"

Function CompareExcelAndProvideResultInAnotherSheet(inputFile1, inputFile2)
Set objExcel=CreateObject("Excel.Application")
objExcel.Visible=True
Set objWorkBook1=objExcel.Workbooks.Open(inputFile1)
Set objWorkBook2=objExcel.Workbooks.Open(inputFile2)

msgbox objWorkBook1.Worksheets.count

Set objWorksheet1=objWorkBook1.Worksheets(1)
Set objWorkSheet2=objWorkBook2.Worksheets(1)

For each cell in objWorkSheet1.UsedRange
c1=cell.Value
c2=objWorksheet2.Range(cell.Address).Value
Set rc=New RegExp
rc.Pattern=c1
rc.IgnoreCase=True
rc.Global=True
'Msgbox s
'Msgbox ptn
'MsgbOx rc.Test(s)

If rc.Test(c2) Then
cell.Value="Pass"
'c2.Interior.ColorIndex = 0
Else
' cell.Value= "Fail"
c2.Interior.ColorIndex = 3
End If
Next

Set objExcel=Nothing
End Function
Msgbox "Done"

Function Compare2ExcelsCellByCell(inputFile1, inputFile2)

'Compare 2 Excel sheets cell by cell and making the cell background as Red for the unmatched Cell value
'=============================================
'This code will open two excel sheet and compare each sheet cell by cell, if any changes there in cells , it will highlight the cells in red color in the first sheet.
Set objExcel = CreateObject("Excel.Application")
'objExcel.Visible = True
Set objWorkBook1=objExcel.Workbooks.Open(inputFile1)
Set objWorkBook2=objExcel.Workbooks.Open(inputFile2)
msgbox objWorkBook1.Worksheets.count
For i = 1 to objWorkBook1.Worksheets.count
If (objWorkBook1.Worksheets(i).UsedRange.Rows.Count=1) And (objWorkBook1.Worksheets(i).UsedRange.Columns.Count=1)Then
objWorkBook1.Worksheets(i).Delete
End If
Next
For i = 1 to objWorkBook2.Worksheets.count
If (objWorkBook2.Worksheets(i).UsedRange.Rows.Count=1) And (objWorkBook2.Worksheets(i).UsedRange.Columns.Count=1)Then
objWorkBook1.Worksheets(i).Delete
End If
Next

Set objWorksheet1=objWorkBook1.Worksheets(1)
Set objWorkSheet2=objWorkBook2.Worksheets(1)

For Each cell In objWorksheet1.UsedRange
If cell.Value <> objWorksheet2.Range(cell.Address).Value Then
cell.Interior.ColorIndex = 3 'Highlights in red color if any changes in cells
Else
cell.Interior.ColorIndex = 5
End If
Next
objWorkBook1.Save
objWorkBook2.Save
objExcel.Quit
set objExcel=nothing
End Function

Working with dotnetfactory in qtp for database retrieval

dim objConDotnet, objCmdDotnet

Set objConDotnet=DotNetFactory.CreateInstance("System.Data.Odbc.OdbcConnection","System.Data")
'objConDotnet.ConnectionString="Server=xxx; UID=yyy; DataBase=zzz"
strCon="DRIVER={Microsoft ODBC for Oracle};SERVER=XXX; UID=YYY; PWD=ZZZ"
objConDotnet.ConnectionString=strCon
Print objConDotnet.ConnectionString
Print TypeName(objConDotnet)
objConDotnet.ConnectionTimeOut=0
objConDotnet.Open()
Print Cstr(objConDotnet.State)
strSql= "Select Count(*) from where columnName=valuetoSearch"
Set objCmdDotnet=DotNetFactory.CreateInstance("System.Data.Odbc.OdbcCommand","System.Data")
objCmdDotnet.CommandText=strSql
objCmdDotnet.Connection= objConDotnet
strValue = objCmdDotnet.ExecuteScalar()
Print "The return Count is : " & CInt(strValue)
objConDotnet.Close()
Print Cstr(objConDotnet.State)

Monday, May 9, 2011

Comparing Two excel files and finding mismatch rows

Set objExcel = CreateObject ("Excel.Application")
objExcel.Visible = True

Set resultWb = objExcel.Workbooks.Add
Set resultWs = resultWb.Worksheets("Sheet1")

resultrow =1
Set objWorkbook1= objExcel.Workbooks.Open("C:\Excel\BI_TEST\TEST_090602_1.xls")
Set objWorkbook2= objExcel.Workbooks.Open("C:\Excel\BI_PROD\PROD_090602_1.xls")

Set objWorksheet1= objWorkbook1.Worksheets(1)
Set objWorksheet2= objWorkbook2.Worksheets(1)
Const xlAscending = 1'represents the sorting type 1 for Ascending 2 for Desc
Const xlYes = 1
'Set objRange =objWorksheet1.UsedRange 'which select the range of the cells has some data other than blank
'Set objRange2 = objWorksheet1.Range("A1") 'select the column to sort

'objRange.Sort objRange2, xlAscending, , , , , , xlYes

'Set objRange12 =objWorksheet2.UsedRange 'which select the range of the cells has some data other than blank
'Set objRange22 = objWorksheet2.Range("A1") 'select the column to sort

'objRange12.Sort objRange22, xlAscending, , , , , , xlYes

resultWs.Cells (resultrow, 1).Value ="Cell Address"
resultWs.Cells (resultrow, 2).Value ="Sheet1 Value"
resultWs.Cells (resultrow, 3).Value ="Sheet2 Value"

dim counter
counter = 0
For Each cell In objWorksheet1.UsedRange
If cell.Value <> objWorksheet2.Range(cell.Address).Value Then
cell.Interior.ColorIndex = 3'Highlights in red color if any changes in cells
resultrow = resultrow+1
resultWs.Cells (resultrow, 1).Value =cell.Address
resultWs.Cells (resultrow, 2).Value =cell.VALUE
resultWs.Cells (resultrow, 3).Value= objWorksheet2.Range(cell.Address).Value
End If
counter = counter +1
Next

resultWb.SaveAs("C:\Excel\Result\Result_090602_1.xls")

Wednesday, December 16, 2009

Working with Arraylist of Dot Net in Qtp's VbScript

Set array1 = CreateObject( "System.Collections.ArrayList" )

Set array2 = CreateObject( "System.Collections.ArrayList" )



Private Sub PrintInfo( ByVal title )

dim str

str="title" & vbNewLine

str1= "array1 Capacity = " & array1.Capacity & vbcrlf

str2= "array2 Capacity = " & array2.Capacity & vbcrlf

str3= "array1 Count = " & array1.Count & vbcrlf

str4= "array2 Count = " & array2.Count & vbcrlf

str5= "array1 IsFixedSize = " & array1.IsFixedSize & vbcrlf

str6= "array2 IsFixedSize = " & array2.IsFixedSize & vbcrlf

str7= String( 50, "*" ) & vbcrlf

Msgbox str & str1 & str2 &str3 & str4 & str5 & str6 & str7

End Sub

array2.Capacity = 10

Call PrintInfo( "Before adding items." )

' ** Adding an item to arrays

array1.Add "New York" : array2.Add "New York"

Call PrintInfo( "After adding 1 item." )

array1.Add "Boston" : array2.Add "Boston"

array1.Add "Dallas" : array2.Add "Dallas"

array1.Add "Chicago" : array2.Add "Chicago"

Call PrintInfo( "After adding 3 more items" )

array1.Remove( "Boston" )

Call PrintInfo( "After removing 1 item form array1" )

Some Basic Useful re-usable Scripts in QTP

General Functions which might be useful in the projects:-

Array Basics
Some basic info about creating and using arrays.
' The easiest way create an array is to simply declare it as follows
Dim strCustomers()
' Another method is to define a variable and then set it as an array afterwards
Dim strStaff
strStaff = Array("Alan","Brian","Chris")
' Yet another way is to use the split command to create and populate the array
Dim strProductArray
strProductArray = "Keyboards,Laptops,Monitors"
strProductArray = Split(strProductArray, ",")
' To itterate through the contents of an array you can use the For Each loop
Dim strItem
For Each strItem In strProductArray
MsgBox strItem
Next
' This will also itterate through the loop
Dim intCount
For intCount = LBound(strProductArray) To UBound(strProductArray)
Msgbox strProductArray(intCount)
Next
' This will itterate through the array backwards
For intCount = UBound(strProductArray) To LBound(strProductArray) Step -1
Msgbox strProductArray(intCount)
Next
' To add extra data to an array use Redim Preserve
Redim Preserve strProductArray(3)
strProductArray(3) = "Mice"
' To store the contents of an array into one string, use Join
Msgbox Join(strProductArray, ",")
' To delete the contents of an array, use the Erase command
Erase strProductArray
Date Manipulation Examples
Some date manipulation functions.

' show todays date
MsgBox Date

' show the time
MsgBox Time

' show both the date and time
MsgBoxNow

' calculate the minimum Date of Birth for someone who is 18 years old
strMinDoB = DateAdd("yyyy", -18, Date)
MsgBox strMinDob

' show the number of years difference between strMinDob and today
MsgBox DateDiff("yyyy", strMinDob, Date)

' show the hour portion of the time
MsgBox DatePart("h", Time)

' show the day portion of the date
MsgBox Day(strMinDob)

' show the month portion of the date
MsgBox Month(strMinDob)

' show the year portion of the date
MsgBox Year(strMinDob)

' show the weekday portion of the date
' Sunday=1, Monday=2, --> Saturday=7
MsgBox WeekDay(strMinDob)



Note: Acceptable 'Interval' parameters for DatePart, DateAdd and DateDiff...

"yyyy" = Year
"q" = Quarter
"m" = Month
"y" = Day of year
"d" = Day
"w" = Weekday
"ww" = Week of year
"h" = Hour
"n" = Minute
"s" = Second

Get Child Obects
Find all checkboxes on a webpage.
Here's a basic example that will find and tick all of the checkboxes on the QTP Helper login screen.
Dim objDescription
Dim objCheckBoxes
Dim iCount

' create description objects used to locate check boxes
Set objDescription = Description.Create()

' set the object properties so it looks only for web check boxes
objDescription("micclass").Value = "WebCheckBox"

' check that the user isn't already logged in
If Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton("Name:=Logout").Exist(1) Then

' click logout
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton("Name:=Logout").Click

End If

' get the check boxes from the page
Set objCheckBoxes = Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").ChildObjects(objDescription)

' for each check box found
For iCount = 0 to objCheckBoxes.Count - 1

' tick the check box
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebCheckBox(objCheckBoxes(iCount)).Set "ON"

Next


Compare Arrays
Compare the contents of two arrays.
' Example usage
sA = Array("A", "B", "D")
sB = Array("A", "C", "B")

MsgBox CompareArrays(sA, sB)
' =============================================================
' function: CompareArrays
' desc : Compares the content of two arrays and checks that
' they each contain the same data, even if in a
' different order
' params : arrArray1 is the base array
' arrArray2 is the array to compare
' returns : True if they contain same data, False otherwise
' =============================================================
Function CompareArrays(arrArray1, arrArray2)

Dim intA1
Dim intA2
Dim blnMatched

' check that the arrays are the same size
If UBound(arrArray1) <> UBound(arrArray2) then

' arrays are different size, so return false and exit function
CompareArrays = False
Exit Function

End if

' for each element in the first array
For intA1 = LBound(arrArray1) to UBound(arrArray1)

' initialise this to false
blnMatched = False

' for each element in the second array
For intA2 = LBound(arrArray2) to UBound(arrArray2)

' compare the content of the two arrays
If arrArray1 (intA1) = arrArray2 (intA2) Then
blnMatched = True
Exit For
End If

Next ' next element in second array

' if the element was not found in array two, return false and exit function
If Not blnMatched then
CompareArrays = False
Exit Function
End If

Next ' next element in first array

' if the function got this far, then the arrays contain the same data
CompareArrays = True

End Function ' CompareArrays


Custom Report Entry
Creating a customised entry in the results.

' Example usage
CustomReportEntry micFail, "Custom Report Example", "
This is a custom report entry!
"

' =============================================================
' function: CustomReportEntry
' desc : Creates a customized entry in the result file, you
' can use standard HTML tags in the message.
' params : strStatus is the result, micPass, micFail etc
' strStepName is the name of the step
' strMessage is the failure message, this can contain
' html tags
' returns : Void
' =============================================================
Function CustomReportEntry(strStatus, strStepName, strMessage)

' create a dictionary object
Set objDict = CreateObject("Scripting.Dictionary")

' set the object properties
objDict("Status") = strStatus
objDict("PlainTextNodeName") = strStepName
objDict("StepHtmlInfo") = strMessage
objDict("DllIconIndex") = 206
objDict("DllIconSelIndex") = 206
objDict("DllPAth") = "C:\Program Files\Mercury Interactive\QuickTest Professional\bin\ContextManager.dll"

' report the custom entry
Reporter.LogEvent "User", objDict, Reporter.GetContext

End Function 'CustomReportEntry









Bcreating Custom Libraries
An example of how to create your own custom library.
This example will show you how to create your own customised code
library, using Visual Basic 6 as an example.

First thing to do is open Visual Basic and create a new Active X DLL project...


Before we add any code, we should give the Project and the Class Library sensible names.

Here I've called the project "QTP"...


For the Class Library I've simply called it "Library"...


Now we can add a function to our Library. For this example I'm going to use a very
basic function which will simply display a message box with a given parameter value...



Next thing we need to do is create the DLL, this can be done from the File menu in Visual Basic...


Note that during the development of the DLL, you can simply press F5 to run the code in Visual
Basic. We can then still call the function from QTP, this allows us to put break-points inside
the Visual Basic code and do some debugging.

Another thing to note is that when you finish the DLL and want to use it on other machines,
you will need to register the DLL on the system. This can be done by simply dragging and dropping
the DLL onto the file "RegSvr32.exe", which can be found in your Windows\System32 folder.

Now that we have our new library ready, we can call the functions from QTP...


Dim objDLL

' create an object for our new library
Set objDLL = CreateObject("QTP.Library")

' call the function from the library
objDLL.QTPHelper_Example "Easy!"

' destroy the object
Set objDLL = Nothing


And here is the end result...


Using methods like this will open up several new doors for your automation by allowing you to
execute code which isn't as easy to implement in VB Script as it is in other languages.



Running DOS Commands
Running Dos Commands

' =============================================================
' Sub : ExecuteDosCommand
' desc : Run a single-line DOS command
' params : Command to run
' returns : void
' =============================================================
Sub ExecuteDosCommand(strCommand)

Dim objShell

' create the shell object
Set objShell = CreateObject("WSCript.shell")

' run the command
objShell.run strCommand

' destroy the object
Set objShell = Nothing

End Sub 'ExecuteDosCommand



Export Data Sheet
Export a data sheet at runtime.
' =============================================================
' function: ExportDataSheet
' desc : Exports a data sheet
' params : strFile - full path to save the exported xls, note
' that any existing xls will be deleted
' strSheet - sheet to export
' returns : void
' =============================================================
Function ExportDataSheet(strFile, strSheet)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the xls doesn't already exist
If objFS.FileExists(strFile) Then
' delete it if it exists
ObjFS.DeleteFile strFile

End If
' export the data table
DataTable.ExportSheet strFile, strSheet
' destroy the object
Set objFS = Nothing
End Function 'ExportDataSheet


Execute a Stored Procedure
Some code that should help you execute a stored procedure.

' set the parameters of your database here
strDatabaseName = ""
strUser = ""
strPassword = ""
strStoredProcedureName = ""

' create the database object
Set objDB = CreateObject("ADODB.Command")
' set the connection string
objDB.ActiveConnection = "DRIVER={Microsoft ODBC for Oracle}; " & _
"SERVER=" & strDatabaseName & _
";User ID=" & strUser & ";Password=" & strPassword & " ;"

' set the command type to Stored Procedures
objDB.CommandType = 4
objDB.CommandText = strStoredProcedureName

' define Parameters for the stored procedure
objDB.Parameters.Refresh
' set parameters for stored procedure (i.e. two parameters here)
objDB.Parameters(0).Value = "Param1"
objDB.Parameters(1).Value = "Param2"

' execute the stored procedure
objDB.Execute()
' destroy the object
Set objDB = Nothing

Execute Method In Regular Expressions
Executing a regular expression to find text within a string.

MsgBox RegularExpExample("QTP.", "QTP1 QTP2 qtp3 QTP4")

' =============================================================
' function: RegularExpExample
' desc : Example of how to use the regular expression object
' to find text within a string
' params : strPattern is the regular expression
' strString is the string to use the expression on
' returns : An example string showing the results of the search
' =============================================================
Function RegularExpExample(strPattern, strString)

Dim objRegEx, strMatch, strMatches
Dim strRet

' create regular expression object
Set objRegEx = New RegExp

' set the pattern
objRegEx.Pattern = strPattern

' set it be not case sensitive
objRegEx.IgnoreCase = True

' set global flag so we search all of the string, instead of just searching
' for the first occurrence
objRegEx.Global = True

' execute search
Set strMatches = objRegEx.Execute(strString)

' for each match
For Each strMatch in strMatches

strRet = strRet & "Match found at position '" & _
strMatch.FirstIndex & "' - Matched Value is '" & _
strMatch.Value & "'" & vbCRLF

Next

RegularExpExample = strRet

End Function ' RegularExpExample



Export Data Table
Export a data table at runtime.
' =============================================================
' function: ExportDataTable
' desc : Exports a data table
' params : strFile - full path to save the exported xls, note
' that any existing xls will be deleted
' returns : void
' =============================================================
Function ExportDataTable(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the xls doesn't already exist
If objFS.FileExists(strFile) Then
' delete it if it exists
ObjFS.DeleteFile strFile

End If
' export the data table
DataTable.Export strFile
' destroy the object
Set objFS = Nothing
End Function 'ExportDataTable
Export Data Sheet
Export a data sheet at runtime.
' =============================================================
' function: ExportDataSheet
' desc : Exports a data sheet
' params : strFile - full path to save the exported xls, note
' that any existing xls will be deleted
' strSheet - sheet to export
' returns : void
' =============================================================
Function ExportDataSheet(strFile, strSheet)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the xls doesn't already exist
If objFS.FileExists(strFile) Then
' delete it if it exists
ObjFS.DeleteFile strFile

End If
' export the data table
DataTable.ExportSheet strFile, strSheet
' destroy the object
Set objFS = Nothing
End Function 'ExportDataShee

Read From Excel File
Read all the data from an Excel file.

' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)

Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol

' create the file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' ensure that the xls file exists
If Not objFS.FileExists(strFileName) Then

' issue a fail if the file wasn't found
Reporter.ReportEvent micFail, "Read XLS", "Unable to read XLS file, file not found: " & strFileName
' file wasn't found, so exit the function
Exit Function

End If ' file exists

' create the excel object
Set objExcel = CreateObject("Excel.Application")

' open the file
objExcel.Workbooks.open strFileName

' select the worksheet
Set objSheet = objExcel.ActiveWorkbook.Worksheets(strSheetName)

' select the used range
Set objRange = objSheet.UsedRange

' count the number of rows
intTotalRow=CInt(Split(objRange.Address, "$")(4)) - 1

' count the number of columns
intTotalCol= objSheet.Range("A1").CurrentRegion.Columns.Count

' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)

' for each row
For intRow = 0 to intTotalRow - 1

' for each column
For intCol =0 to intTotalCol - 1

' store the data from the cell in the array
strData(intRow, intcol) = Trim(objSheet.Cells(intRow + 2,intcol + 1).Value)

Next ' column

Next ' row

' close the excel object
objExcel.DisplayAlerts = False
objExcel.Quit

' destroy the other objects
Set objFS = Nothing
Set objExcel = Nothing
Set objSheet = Nothing

' return the array containing the data
ReadXLS = strData

End Function ' ReadXLS

File Browser
Opens a standard dialog which allows the user to choose a file.
' =============================================================
' function : FileBrowser
' desc : Opens a standard Open File Dialog
' params : strTitle - the title to apply to the dialog
' strFilter - the filter to apply to the dialog
' returns : The selected file, including path
' =============================================================
Public Function FileBrowser(strTitle, strFilter)

Dim objDialog
' create a common dialog object
Set objDialog = CreateObject("MSComDlg.CommonDialog")
' set the properties and display the dialog
With objDialog
.DialogTitle = strTitle
.Filter = strFilter
.MaxFileSize = 260
.ShowOpen
End With
' return the selected file
FileBrowser = objDialog.FileName
' destroy the object
Set objDialog = Nothing

End Function ' FileBrowser
File Exists
Check to see if a local or network file exists.
' =============================================================
' function: CheckFileExists
' desc : Checks to see if a file exists
' params : strFile - full path of the file to find
' returns : True if file exists, False otherwise
' =============================================================
Function CheckFileExists(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FileExists(strFile) Then
' file exists, return true
CheckFileExists = True

Else

' file exists, return false
CheckFileExists = False

End If

End Function 'CheckFileExists


Folder Exists
Check to see if a local or network folder exists.
' =============================================================
' function: CheckFolderExists
' desc : Checks to see if a folder exists
' params : strFolder - full path of the folder to find
' returns : True if folder exists, False otherwise
' =============================================================
Function CheckFolderExists(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FolderExists(strFolder) Then
' file exists, return true
CheckFolderExists = True

Else

' file exists, return false
CheckFolderExists = False

End If
' destroy the object
Set objFS = Nothing

End Function 'CheckFolderExists


Create Folder
Create a local or network folder.
' =============================================================
' function: FolderCreate
' desc : Creates a folder
' params : strFolderPath - the folder to create (full path)
' returns : void
' =============================================================
Function FolderCreate(strFolderPath)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' create the folder
If Not objFS.FolderExists(strFolderPath) Then
objFS.CreateFolder strFolderPath
End If
' destroy the object
Set objFS = Nothing

End Function 'FolderCreate


Delete Folder
Delete a local or network folder.
' =============================================================
' function: FolderDelete
' desc : Deletes a folder and all of it's contents
' params : strFolder - the folder to delete
' returns : void
' =============================================================

Function FolderDelete(strFolder)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Delete Folder", "Unable to Delete Folder '"& strFolder &"', It Does Not Exist"
Else
' delete the folder
objFS.DeleteFolder strFolder

End If
' destroy the object
Set objFS = Nothing

End Function 'FolderDelete
Move Folder
Move a local or network folder.
' =============================================================
' function: FolderMove
' desc : Moves a folder and all of its files to a new path
' params : strSourceFolder - the folder to copy
' strDestinationFolder - the location to copy to
' returns : void
' =============================================================
Function FolderMove(strSourceFolder, strDestinationFolder)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strSourceFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Move Folder", "Source Folder '"& strSourceFolder &"' Does Not Exist"
Else
' check that the destination folder doesn't already exist
If Not objFS.FolderExists(strDestinationFolder) Then

' move the folder
objFS.MoveFolder strSourceFolder, strDestinationFolder
Else
' fail if the target folder was already in place
reporter.ReportEvent micFail, "Move Folder", "Unable to Move Folder as the Target '" & strDestinationFolder & "' Already Exists"

End If

End If
' destroy the object
Set objFS = Nothing

End Function 'FolderMove
Copy Folder
Copy a local or network folder.
' =============================================================
' function: FolderCopy
' desc : Copys a folder and all of its files to a new path
' params : strSourceFolder - the folder to copy
' strDestinationFolder - the location to copy to
' returns : void
' =============================================================

Function FolderCopy(strSourceFolder, strDestinationFolder)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strSourceFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Copy Folder", "Source Folder '"& strSourceFolder &"' Does Not Exist"
Else
' create the destination folder if it doesn't already exist
If Not objFS.FolderExists(strDestinationFolder) Then
objFS.CreateFolder(strDestinationFolder)
End If
' copy the folder
objFS.CopyFolder strSourceFolder, strDestinationFolder

End If
' destroy the object
Set objFS = Nothing

End Function 'FolderCopy
Folder Exists
Check to see if a local or network folder exists.
' =============================================================
' function: CheckFolderExists
' desc : Checks to see if a folder exists
' params : strFolder - full path of the folder to find
' returns : True if folder exists, False otherwise
' =============================================================
Function CheckFolderExists(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FolderExists(strFolder) Then
' file exists, return true
CheckFolderExists = True

Else

' file exists, return false
CheckFolderExists = False

End If
' destroy the object
Set objFS = Nothing

End Function 'CheckFolderExists
Read a Text File
Example of how to read a text file line-by-line.

' reading a file line by line

Const ForReading = 1

' create file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' first check that the file exists
If objFS.FileExists("c:\TextFile.txt") Then

' open the text file for reading
Set objFile = objFS.OpenTextFile("c:\TextFile.txt", ForReading, False)

' do until at end of file
Do Until objFile.AtEndOfStream

' store the value of the current line in the file
strLine = objFile.ReadLine

' show the line from the file
MsgBox strLine

Loop ' next line

' close the file
objFile.Close

Set objFile = Nothing

Else ' file doesn't exist

' report a failure
Reporter.ReportEvent micFail, "Read File", "File not found"

End if ' file exists

' destroy the objects
Set objFS = Nothing


Write to a File
Example of how to write text to a file.

' =============================================================
' function: AppendFile
' desc : Writes a line of text to a text file, text file is
' created if it doesn't already exist
' params : strFileName is the name of the file to write to
' strLine is the text to write to the file
' returns : void
' =============================================================
Function AppendFile(strFileName, strLine)

Dim objFS

Const ForAppending = 8

' create the file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' open/create the text file
Set objFile = objFS.OpenTextFile(strFilename, ForAppending, True)

' write the line
objFile.WriteLine strLine

' close the file
objFile.Close

End Function ' AppendFile


Get Temporary File Name
Generate a unique temporary file name.
' =============================================================
' function: GetTemporaryFileName
' desc : Generates a unique file name in the windows
' temporary folder
' params : none
' returns : A unique temporary file, including path
' =============================================================
Function GetTemporaryFileName
Const TemporaryFolder = 2
Dim objFS
Dim objTempFolder
' create the file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' get the path to the temporary folder
Set objTempFolder = objFS.GetSpecialFolder(TemporaryFolder)
' return the path plus a unique temporary file name
GetTemporaryFileName = objTempFolder.Path & "\" & objFS.GetTempName
' destroy the object
Set objFS = Nothing
Set objTempFolder = Nothing
End Function 'GetTemporaryFileName
Create Unique File Name
Create a unique file name.

' =============================================================
' function: UniqueFileName
' desc : Creates a unique file name
' params : strType - file extension
' returns : unique file name of specified type
' =============================================================
Function UniqueFileName(strType)

dim strReturn

' make sure there is a dot before the type
If left(strType,1) <> "." then strType = "." & strType

' create the file name using the date & time, and remove the / and : chars
strReturn = day(date) & month(date) & year(date) & hour(time) & minute(time) & second(time) & strType

' return the file name
UniqueFileName = strReturn

End Function 'UniqueFileName


Compare Files
Compare the contents of two text files.

' =============================================================
' function: CompareFiles
' desc : Compares two text files
' params : strFile1 is the first file
' strFile2 is the second file
' returns : True if they are the same, False otherwise
' =============================================================
Function CompareFiles(strFile1, strFile2)

Dim objFS
Dim objFileA, objFileB
Dim strLineA, strLineB
dim intCompareResult

' create a file scripting object
Set objFS = CreateObject("Scripting.FileSystemObject")

' open each of the files for reading
Set objFileA = objFS.OpenTextFile(strFile1, 1)
Set objFileB = objFS.OpenTextFile(strFile2, 1)

' repeat the following until we hit the end of one of the files
Do While ((objFileA.AtEndOfStream <> True) OR (objFileB.AtEndOfStream <> True))

' read the next line from both files
strLineA = objFileA.ReadLine
strLineB = objFileB.ReadLine

' perform a comparison on the line from each file
intCompareResult = StrComp(strLineA,strLineB,0)

' if the value of the comparison is not 0, lines are different
If (intCompareResult <> 0) Then

' found a difference in the files, so close them both
objFileA.Close
objFileB.Close

' destroy the object
Set objFS = Nothing

' return false
CompareFiles = False

' exit the function
Exit Function

End If ' if different

Loop ' until end of file

' close both files
objFileA.Close
objFileB.Close

' destroy the object
Set objFS = Nothing

' if function got this far, means files are the same, so return True
CompareFiles = True

End Function 'CompareFiles

Create Desktop Shortcut
Create a shortcut on the desktop.

' =============================================================
' function: CreateDesktopShortcut
' desc : Creates a shortcut on the desktop
' params : strTargetPath is the full path to the file you
' are creating the shortcut to, i.e. c:\doc\me.txt
' strLinkName is the name of the shortcut, as it
' appears on the desktop
' strDesc is the description to set within the shortcut
' returns : void
' =============================================================
Sub CreateDesktopShortcut(strTargetPath, strLinkName, strDesc)

Dim objShell, objShortCut
Dim strDesktopFolder

' ensure that the link name is valid
if Right(Lcase(strLinkName,4)) <> ".lnk" Then strLinkName = strLinkName & ".lnk"

' create a shell object
Set objShell = CreateObject("WScript.Shell")

' get the desktop folder
strDesktopFolder = objShell.SpecialFolders("AllUsersDesktop")

' create required shortcut object on the desktop
Set objShortCut = objShell.CreateShortcut(strDesktopFolder & "\" & strLinkName)

' set the path within the shortcut
objShortCut.TargetPath = strTargetPath

' set the description
objShortCut.Description = strDesc

' save the shortcut
objShortCut.Save

End Sub ' CreateDesktopShortcut


Read From Excel File
Read all the data from an Excel file.

' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)

Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol

' create the file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' ensure that the xls file exists
If Not objFS.FileExists(strFileName) Then

' issue a fail if the file wasn't found
Reporter.ReportEvent micFail, "Read XLS", "Unable to read XLS file, file not found: " & strFileName
' file wasn't found, so exit the function
Exit Function

End If ' file exists

' create the excel object
Set objExcel = CreateObject("Excel.Application")

' open the file
objExcel.Workbooks.open strFileName

' select the worksheet
Set objSheet = objExcel.ActiveWorkbook.Worksheets(strSheetName)

' select the used range
Set objRange = objSheet.UsedRange

' count the number of rows
intTotalRow=CInt(Split(objRange.Address, "$")(4)) - 1

' count the number of columns
intTotalCol= objSheet.Range("A1").CurrentRegion.Columns.Count

' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)

' for each row
For intRow = 0 to intTotalRow - 1

' for each column
For intCol =0 to intTotalCol - 1

' store the data from the cell in the array
strData(intRow, intcol) = Trim(objSheet.Cells(intRow + 2,intcol + 1).Value)

Next ' column

Next ' row

' close the excel object
objExcel.DisplayAlerts = False
objExcel.Quit

' destroy the other objects
Set objFS = Nothing
Set objExcel = Nothing
Set objSheet = Nothing

' return the array containing the data
ReadXLS = strData

End Function ' ReadXLS


Get Child Obects
Find all checkboxes on a webpage.
Here's a basic example that will find and tick all of the checkboxes on the QTP Helper login screen.
Dim objDescription
Dim objCheckBoxes
Dim iCount

' create description objects used to locate check boxes
Set objDescription = Description.Create()

' set the object properties so it looks only for web check boxes
objDescription("micclass").Value = "WebCheckBox"

' check that the user isn't already logged in
If Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton("Name:=Logout").Exist(1) Then

' click logout
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton("Name:=Logout").Click

End If

' get the check boxes from the page
Set objCheckBoxes = Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").ChildObjects(objDescription)

' for each check box found
For iCount = 0 to objCheckBoxes.Count - 1

' tick the check box
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebCheckBox(objCheckBoxes(iCount)).Set "ON"

Next


Get Disk Information
Get information about one of your disk drives.

Dim intSectors, intBytes, intFreeC, intTotalC, intTotal ,intFreeb

' include this windows api
extern.Declare micLong, "GetDiskFreeSpace", "kernel32.dll", "GetDiskFreeSpaceA", micString+micByref, micLong+micByref, micLong+micByref,micLong+micByref,micLong+micByref

' set these values
intSectors = 255
intBytes = 255
intFreeC = 255
intTotalC = 255

' calculate the disk space, using C: in this example
intSpaceAvailable = extern.GetDiskFreeSpace("c:\", intSectors, intBytes, intFreeC, intTotalC)

' calculate the totals
intTotal = intTotalC * intSectors * intBytes
intFreeb = intFreeC * intSectors * intBytes

' show the outputs
msgBox intSectors
msgBox intBytes
msgBox intFreeC
msgBox intTotalC
msgbox intTotal
msgBox intFreeb
Get IP Address
Get your machines IP address.

' =============================================================
' function: GetIPAddress
' desc : Returns the IP address of the PC
' params : Void
' returns : IP Address
' =============================================================
Function GetIPAddress()

' get the ip addresses
Set IPConfigSet = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
("select IPAddress from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")

' for each item in the collection
For Each IPConfig in IPConfigSet

' if the item isn't empty
If Not IsNull(IPConfig.IPAddress) Then

' loop through the addresses
For i = LBound(IPConfig.IPAddress) to UBound(IPConfig.IPAddress)

' set the return alue
ipAddr = IPConfig.IPAddress(i)

Next

End If

Next

' destroy the object
Set IPConfigSet = Nothing

' return the ip
GetIPAddress = ipAddr

End Function ' GetIPAddress

Get System Information
Get system information like User Name and Computer Name.

Dim objNet

' create a network object
Set objNet = CreateObject("WScript.NetWork")

' show the user name
MsgBox "User Name: " & objNet.UserName

' show the computer name
MsgBox "Computer Name: " & objNet.ComputerName

' show the domain name
MsgBox "Domain Name: " & objNet.UserDomain

' destroy the object
Set objNet = Nothing

Get System Variable Value
Get a value from a Windows System Variable.

' for example to get the oracle home path
MsgBox GetSystemVariable("ORACLE_HOME")

' =============================================================
' function: GetSystemVariable
' desc : Get the value of a system variable
' params : strSysVar is the variable name
' returns : Content of variable name
' =============================================================
Function GetSystemVariable(strSysVar)

Dim objWshShell, objWshProcessEnv

' create the shell object
Set objWshShell = CreateObject("WScript.Shell")
Set objWshProcessEnv = objWshShell.Environment("Process")

' return the system variable content
GetSystemVariable = objWshProcessEnv(strSysVar)

End Function ' GetSystemVariable

Get Temporary File Name
Generate a unique temporary file name.
' =============================================================
' function: GetTemporaryFileName
' desc : Generates a unique file name in the windows
' temporary folder
' params : none
' returns : A unique temporary file, including path
' =============================================================
Function GetTemporaryFileName
Const TemporaryFolder = 2
Dim objFS
Dim objTempFolder
' create the file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' get the path to the temporary folder
Set objTempFolder = objFS.GetSpecialFolder(TemporaryFolder)
' return the path plus a unique temporary file name
GetTemporaryFileName = objTempFolder.Path & "\" & objFS.GetTempName
' destroy the object
Set objFS = Nothing
Set objTempFolder = Nothing
End Function 'GetTemporaryFileName
Import Data Sheet
Import a data sheet into your test at runtime.
' =============================================================
' function: ImportDataSheet
' desc : Imports a single data sheet
' params : strFile - full path of the xls file with the sheet
' strSource - name of the sheet on the xls
' strTarget - name of the sheet to import it to
' returns : void
' =============================================================
Function ImportDataSheet(strFile, strSource, strTarget)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FileExists(strFile) Then
' ensure that our target sheet exists
DataTable.AddSheet strTarget
' import the sheet
DataTable.Importsheet strFile, strSource, strTarget
Else
' fail if the xls was not found
Reporter.ReportEvent micFail, "Import Data Table", "Unable to Import Data Table From '" & strFile & "', File Does Not Exist"
End If
' destroy the object
Set objFS = Nothing
End Function 'ImportDataSheet


Import Data Table
Import a data table into your test at runtime.
' =============================================================
' function: ImportDataTable
' desc : Imports a data table
' params : strFile - full path of the xls file to import
' returns : void
' =============================================================
Function ImportDataTable(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FileExists(strFile) Then
' import the data table
DataTable.Import strFile
Else
' fail if the xls was not found
Reporter.ReportEvent micFail, "Import Data Table", "Unable to Import Data Table From '" & strFile & "', File Does Not Exist"
End If
' destroy the object
Set objFS = Nothing
End Function 'ImportDataTable


Sending Key Presses (SendKeys)
Examples of how to simulate key presses.
Dim objShell
' Create the shell object
Set objShell = CreateObject ("WSCript.shell")
' Various key press examples
objShell.SendKeys "Hello" ' Hello
objShell.SendKeys "{F4}" ' F4
objShell.SendKeys "^{F4}" ' CTRL-F4
objShell.SendKeys "+{F4}" ' SHIFT-F4
objShell.SendKeys "%{F4}" ' ALT-F4
' Destroy the object
Set objShell = Nothing

Locate Method (Checking text within text)
Using Locate to determine if specific text exists within a string.

MsgBox LocateText("www.QTPHelper.com", "QTP")
MsgBox LocateText("www.QTPHelper.com", "QTP.*.com")

' =============================================================
' function: LocateText
' desc : Uses a regular expression to locate text within a string
' params : strString is the string to perform the search on
' strPattern is the regular expression
' returns : True if the pattern was found, False otherwise
' =============================================================
Function LocateText(strString, strPattern)

Dim objRegEx

' create the regular expression
Set objRegEx = New RegExp

' set the pattern
objRegEx.Pattern = strPattern

' ignore the casing
objRegEx.IgnoreCase = True

' perform the search
LocateText = objRegEx.Test(strString)

' destroy the object
Set objRegEx = Nothing

End Function ' LocateText


Write to a Log File
Write information to a log file.

' =============================================================
' function: WriteLog
' desc : Writes a message to a log file. File is created
' inside a Log folder of the current directory
' params : strCode is a code to prefix the message with
' strMessage is the message to add to the file
' returns : void
' =============================================================
Function WriteLog(strCode, strMessage)

Dim objFS
Dim objFile
Dim objFolder
Dim strFileName

' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' is there a log folder in the directory that we are currently working
If Not objFS.FolderExists(objFS.GetAbsolutePathName(".") & "\log") Then

' if there is no log folder, create one
Set objFolder = objFS.CreateFolder(objFS.GetAbsolutePathName(".") & "\log")

End If ' folder exists

' set a name for the log file using year, month and day values
strFileName = objFS.GetAbsolutePathName(".") & "\log\" & year(date) & month(date) & day(date) & ".log"

' create the log file
Set objFile = objFS.OpenTextFile(strFileName, 8, True)

' in case of any issues writing the file
On Error Resume Next

' write the log entry, include a carriage return
objFile.Write Date & ", " & Time & ", " & strCode & ", " & strMessage & vbcrlf

' disable the on error statement
On Error GoTo 0

' close the log file
objFile.Close

' destrory the object
Set objFS = Nothing

End Function ' WriteLog


Loop Basics
Some basic information about various loop types.
' Loops allow you to run a group of statements repeatidly.
'
' There are four types of loop available, all very easy to
' use and understand. This code sample will explain how
' to use each type of loop.
'

' Do...Loop

' The Do...Loop will run a block of statements repeatidly
' while a condition is True, or until a condition becomes True

' Check these two examples of Do...While, there is one major difference
' between them. In Example A the cose will check the value of intCounter
' before it enters the loop, but in Example B the code will enter the
' loop regardless of the value of intCounter.

' Example A
intCounter = 0
Do While intCounter < 5
intCounter = intCounter + 1
MsgBox intCounter
Loop

' Example B
intCounter = 0
Do
intCounter = intCounter + 1
MsgBox intCounter
Loop While intCounter <5

' Here is the same examples using the Do...Until
' Example A
intCounter = 0
Do Until intCounter = 6
intCounter = intCounter + 1
MsgBox intCounter
Loop

' Example B
intCounter = 0
Do
intCounter = intCounter + 1
MsgBox intCounter
Loop Until intCounter = 6
' For...Next

' For...Next Loops will execute a series of statements until a specific counter value
' is reached.
For iCounter = 1 To 5
MsgBox iCounter
Next

' You can add a Step keyword to define how much the counter should increase with each
' itteration of the loop
For iCounter = 1 To 10 Step 2
MsgBox iCounter
Next

' The Step keyword can also be used to itterate backwards
For iCounter = 5 to 1 Step -1
MsgBox iCounter
Next


' For...Each

' Another variation on the For...Next loop is the For...Each loop. The For...Each
' loop is used to execute a series of statements for each object in a collection,
' i.e. each element of an array. For example...
Dim strPeopleList
Dim strPerson
strPeopleList = Array("Alan", "Bob", "Craig", "Dan")
For Each strPerson in strPeopleList
MsgBox strPerson
Next


' While...Wend Loops
'
' This type of loop will execute a series of statements as long as
' a given condition is true.
' Note: It's advisable to avoid using this type of loop, you should
' us the Do...Loop instead
' Here's an example anyway...
iCounter = 0
While iCounter < 5
iCounter = iCounter + 1
Msgbox iCounter
Wend
Minimize QTP
Minimize the main QTP window.

' =============================================================
' function: MinimizeQTP
' desc : Minimize QTP window
' params : None
' returns : void
' =============================================================
Function MinimizeQTP()

dim objQTP

' create a qtp object
Set objQTP = getObject("","QuickTest.Application")

' set the window state to minimized
objQTP.WindowState = "Minimized"

' destroy the object
Set objQTP = Nothing

End Function 'MinimizeQTP


Move File
Move a file from one location to another.
' =============================================================
' function: FileMove
' desc : Moves a file from one location to another
' params : strFile - full path to the source file
' strTarget - the folder to move the file to
' returns : void
' =============================================================
Function FileMove(strFile, strTarget)

Dim objFS

' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' check that the source file exists
If Not objFS.FileExists(strFile) Then

' fail if the source does not exist
reporter.ReportEvent micFail, "Move File", "Unable to Move the File '"& strFile &"', It Does Not Exist"

Else

' create the destination folder if it doesn't already exist
If Not objFS.FolderExists(strTarget) Then

objFS.CreateFolder(strTarget)

End If

' move the file
objFS.MoveFile strFile, strTarget

End If

' destroy the object
Set objFS = Nothing

End Function 'FileMove
Move Folder
Move a local or network folder.
' =============================================================
' function: FolderMove
' desc : Moves a folder and all of its files to a new path
' params : strSourceFolder - the folder to copy
' strDestinationFolder - the location to copy to
' returns : void
' =============================================================
Function FolderMove(strSourceFolder, strDestinationFolder)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strSourceFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Move Folder", "Source Folder '"& strSourceFolder &"' Does Not Exist"
Else
' check that the destination folder doesn't already exist
If Not objFS.FolderExists(strDestinationFolder) Then

' move the folder
objFS.MoveFolder strSourceFolder, strDestinationFolder
Else
' fail if the target folder was already in place
reporter.ReportEvent micFail, "Move Folder", "Unable to Move Folder as the Target '" & strDestinationFolder & "' Already Exists"

End If

End If
' destroy the object
Set objFS = Nothing

End Function 'FolderMove
Displaying Dialog Boxes
How to display and use various types of dialog box.
' display a basic message box
MsgBox "Hi, this is a message box", vbOkOnly, "Message Title"


' prompt the user with a question
strAnswer = InputBox("Hi, how are you today?","Question")
' show the user what they just typed
MsgBox "You are - " & strAnswer


' ask the user to select an option
strAnswer = MsgBox("Do you want to proceed?", vbYesNo, "Question")
' show the user what they just selected
If strAnswer = vbNo Then
MsgBox "You selected No"
Else
MsgBox "You selected Yes"
End If
Note: Here are the various message types you can play with...
vbOKOnly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
vbCritical
vbQuestion
vbExclamation
vbInformation


Capture Screenshot
Capture and save a PNG of the entire screen.
' =============================================================
' function: ScreenShot
' desc : Creates a png of the entire screen
' params : n/a
' returns : name of saved png
' =============================================================
Function ScreenShot()
dim strPNG
dim objDesktop
' set a unique file name using the date/time
strPNG = "C:\Screenshot_" & day(date) & month(date) & year(date) & _
& hour(time) & minute(time) & second(time) & ".png"
' desktop object
Set objDesktop = Desktop
' capture a png of the desktop
obj.CaptureBitmap strPNG, true
' return the file name
ScreenShot = strPNG
' destroy the object
Set objDesktop = Nothing
End Function 'ScreenShot


Override Existing Object Method
Override an existing object method.
' override the Set method with SetWithDebug
RegisterUserFunc "WebEdit", "Set", "SetWithDebug"

' =============================================================
' function : SetWithDebug
' desc : Sets the value of an edit box with additional logging
' =============================================================
Function SetWithDebug(objEdit, strValue)

' your additional logging here
' set the text
SetWithDebug = objEdit.Set(strValue)

End Function


Registering a Procedure
Register a procedure with an object class.

' add GetItemsCount as a method of the WebList class
RegisterUserFunc "WebList", "GetItemsCount", "GetItemsCountFunction"

' =============================================================
' function : GetItemsCountFunction
' desc : Returns the number of items from a weblist
' =============================================================
Function GetItemsCountFunction(objWebList)

If (objWebList = Nothing) Then
GetItemsCount = 0
Else
GetItemsCount = objWebList.GetROProperty("Items Count")
End If

End Function

Using Programmatic Descriptions
Using Programmatic Descriptions to interact with a web page.
This example will illustrate how to use programmatic descriptions to interact with a web page, www.QTPHelper.com to be more exact...
Note that I've used a simple regular expression in the Browser and Page description, just in case the titles change in the future.
' click the Home link
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").Link("Text:=Home").Click

' check that the user isn't already logged in
If Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton("Name:=Logout").Exist(1) Then

' click logout
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton("Name:=Logout").Click

End If ' user logged in

' set the username
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebEdit("Name:=username").Set "User"

' set the password
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebEdit("Name:=passwd").Set "Password"

' tick the remember-me tickbox
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebCheckBox("Name:=remember").Set "ON"


Query a Database
Simple example of how to query an access database.
dim objDB
dim objRS
dim intCounter
' create a database and recordset objects
Set objDB = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.RecordSet")
' configure the connection
objDB.Provider="Microsoft.Jet.OLEDB.4.0"
objDB.Open "c:\MyTestDatabase.mdb"
' count the number of records in the employee table
objRS.Open "SELECT COUNT(*) from Employee" , objDB
Msgbox "There are " & objRS.Fields(0).Value & " records in the employee table."
' destroy the objects
Set objDB = Nothing
Set objRS = Nothing
Read a Text File
Example of how to read a text file line-by-line.

' reading a file line by line

Const ForReading = 1

' create file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' first check that the file exists
If objFS.FileExists("c:\TextFile.txt") Then

' open the text file for reading
Set objFile = objFS.OpenTextFile("c:\TextFile.txt", ForReading, False)

' do until at end of file
Do Until objFile.AtEndOfStream

' store the value of the current line in the file
strLine = objFile.ReadLine

' show the line from the file
MsgBox strLine

Loop ' next line

' close the file
objFile.Close

Set objFile = Nothing

Else ' file doesn't exist

' report a failure
Reporter.ReportEvent micFail, "Read File", "File not found"

End if ' file exists

' destroy the objects
Set objFS = Nothing


Read From Excel File
Read all the data from an Excel file.

' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)

Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol

' create the file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' ensure that the xls file exists
If Not objFS.FileExists(strFileName) Then

' issue a fail if the file wasn't found
Reporter.ReportEvent micFail, "Read XLS", "Unable to read XLS file, file not found: " & strFileName
' file wasn't found, so exit the function
Exit Function

End If ' file exists

' create the excel object
Set objExcel = CreateObject("Excel.Application")

' open the file
objExcel.Workbooks.open strFileName

' select the worksheet
Set objSheet = objExcel.ActiveWorkbook.Worksheets(strSheetName)

' select the used range
Set objRange = objSheet.UsedRange

' count the number of rows
intTotalRow=CInt(Split(objRange.Address, "$")(4)) - 1

' count the number of columns
intTotalCol= objSheet.Range("A1").CurrentRegion.Columns.Count

' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)

' for each row
For intRow = 0 to intTotalRow - 1

' for each column
For intCol =0 to intTotalCol - 1

' store the data from the cell in the array
strData(intRow, intcol) = Trim(objSheet.Cells(intRow + 2,intcol + 1).Value)

Next ' column

Next ' row

' close the excel object
objExcel.DisplayAlerts = False
objExcel.Quit

' destroy the other objects
Set objFS = Nothing
Set objExcel = Nothing
Set objSheet = Nothing

' return the array containing the data
ReadXLS = strData

End Function ' ReadXLS

Read from the Registry
Read a value from a key in the registry.

' =============================================================
' function : RegistryRead
' desc : Read a value from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to read, i.e.
' "Software\Test\Automation"
' returns : Value from the registry key
' =============================================================
Function RegistryRead(strRoot, strPath)

' create the shell object
Set objShell = CreateObject("WScript.Shell")

' read the key
strValue = objShell.RegRead(strRoot & "\" & strPath)

' return the value
RegistryRead = strValue

' destroy the object
Set objShell = Nothing

End Function 'RegistryRead

Registering a Procedure
Register a procedure with an object class.

' add GetItemsCount as a method of the WebList class
RegisterUserFunc "WebList", "GetItemsCount", "GetItemsCountFunction"

' =============================================================
' function : GetItemsCountFunction
' desc : Returns the number of items from a weblist
' =============================================================
Function GetItemsCountFunction(objWebList)

If (objWebList = Nothing) Then
GetItemsCount = 0
Else
GetItemsCount = objWebList.GetROProperty("Items Count")
End If

End Function

Replace Method
Using the replace method to find and replace text in a string.

MsgBox ReplaceText("Automating with QTP is rubbish.", "rubbish.", "great!")

MsgBox ReplaceText("QTP is a great automation tool but I can't use it","but.*","!")

' =============================================================
' function: ReplaceText
' desc : Uses a regular expression to replace text within a string
' params : strString is the string to perform the replacement on
' strPattern is the regular expression
' strReplacement is the replacement string
' returns : The finished string
' =============================================================
Function ReplaceText(strString, strPattern, strReplacement)

Dim objRegEx

' create the regular expression
Set objRegEx = New RegExp

' set the pattern
objRegEx.Pattern = strPattern

' ignore the casing
objRegEx.IgnoreCase = True

' make the replacement
ReplaceText = objRegEx.Replace(strString, strReplacement)

' destroy the object
Set objRegEx = Nothing

End Function ' ReplaceText


Write to the Registry
Write a value to the Registry.

' =============================================================
' Sub : RegistryWrite
' desc : Writes a key value to the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to create, i.e.
' "Software\Test\Automation"
' strValue is the value to write in the key
' returns : void
' =============================================================
Function RegistryWrite(strRoot, strPath, strValue)

' create the shell object
Set objShell = CreateObject("WScript.Shell")

' write the key
objShell.RegWrite strRoot & "\" & strPath, strValue, "REG_SZ"

' destroy the object
Set objShell = Nothing

End Function 'RegistryWrite


Read from the Registry
Read a value from a key in the registry.

' =============================================================
' function : RegistryRead
' desc : Read a value from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to read, i.e.
' "Software\Test\Automation"
' returns : Value from the registry key
' =============================================================
Function RegistryRead(strRoot, strPath)

' create the shell object
Set objShell = CreateObject("WScript.Shell")

' read the key
strValue = objShell.RegRead(strRoot & "\" & strPath)

' return the value
RegistryRead = strValue

' destroy the object
Set objShell = Nothing

End Function 'RegistryRead


Delete from the Registry
Delete a key from the registry.

' =============================================================
' function: RegistryDelete
' desc : Deletes a key from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to delete, i.e.
' "Software\Test\Automation"
' returns : void
' =============================================================
Function RegistryDelete(strRoot, strPath)

' create the shell object
Set objShell = CreateObject("WScript.Shell")

' delete the key
strValue = objShell.RegDelete(strRoot & "\" & strPath)

' destroy the object
Set objShell = Nothing

End Function 'RegistryDelete


Custom Report Entry
Creating a customised entry in the results.

' Example usage
CustomReportEntry micFail, "Custom Report Example", "
This is a custom report entry!
"

' =============================================================
' function: CustomReportEntry
' desc : Creates a customized entry in the result file, you
' can use standard HTML tags in the message.
' params : strStatus is the result, micPass, micFail etc
' strStepName is the name of the step
' strMessage is the failure message, this can contain
' html tags
' returns : Void
' =============================================================
Function CustomReportEntry(strStatus, strStepName, strMessage)

' create a dictionary object
Set objDict = CreateObject("Scripting.Dictionary")

' set the object properties
objDict("Status") = strStatus
objDict("PlainTextNodeName") = strStepName
objDict("StepHtmlInfo") = strMessage
objDict("DllIconIndex") = 206
objDict("DllIconSelIndex") = 206
objDict("DllPAth") = "C:\Program Files\Mercury Interactive\QuickTest Professional\bin\ContextManager.dll"

' report the custom entry
Reporter.LogEvent "User", objDict, Reporter.GetContext

End Function 'CustomReportEntry


Write to a Log File
Write information to a log file.

' =============================================================
' function: WriteLog
' desc : Writes a message to a log file. File is created
' inside a Log folder of the current directory
' params : strCode is a code to prefix the message with
' strMessage is the message to add to the file
' returns : void
' =============================================================
Function WriteLog(strCode, strMessage)

Dim objFS
Dim objFile
Dim objFolder
Dim strFileName

' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")

' is there a log folder in the directory that we are currently working
If Not objFS.FolderExists(objFS.GetAbsolutePathName(".") & "\log") Then

' if there is no log folder, create one
Set objFolder = objFS.CreateFolder(objFS.GetAbsolutePathName(".") & "\log")

End If ' folder exists

' set a name for the log file using year, month and day values
strFileName = objFS.GetAbsolutePathName(".") & "\log\" & year(date) & month(date) & day(date) & ".log"

' create the log file
Set objFile = objFS.OpenTextFile(strFileName, 8, True)

' in case of any issues writing the file
On Error Resume Next

' write the log entry, include a carriage return
objFile.Write Date & ", " & Time & ", " & strCode & ", " & strMessage & vbcrlf

' disable the on error statement
On Error GoTo 0

' close the log file
objFile.Close

' destrory the object
Set objFS = Nothing

End Function ' WriteLog
Check Service is Running
Check to see if a windows service is running.

' =============================================================
' function: CheckIfServiceIsRunning
' desc : Check to see if a service is running
' params : strServiceName is the name of the service
' returns : True if running, False otherwise
' =============================================================
Function CheckIfServiceIsRunning(strServiceName)

Dim objShell, blnStatus

' create the shell object
Set objShell= CreateObject("Shell.Application")
blnStatus = objShell.IsServiceRunning(strServiceName)

' return status of service
CheckIfServiceIsRunning = blnStatus

End Function 'CheckIfServiceIsRunning


Basic String Manipulation
Basic functions for string manipulation.

Function: String
Accepts a number and a character. Returns a string created with the character that is repeated the given number of times.

' example
MsgBox String(5,"A")


Function: Len
Returns the number of characters from a given string.

' example
strMyName = "Joe Bloggs"
MsgBox "The Name '" & strMyName & "' is " & Len(strMyName) & " characters long"


Function: Instr
Accepts two strings and returns True if the second string is contained within the first.

' example
If Instr("Hello, welcome to www.QTPHelper.com!", "QTP")>0 Then MsgBox "Found"


Function: Left
Returns the given number of left-most characters from a string

' example
MsgBox Left("Joe Bloggs", 3)


Function: Right
Returns the given number of right-most characters from a string

' example
MsgBoxRight("Joe Bloggs", 6)


Function: LCase
Returns a given string in lower-case

' example
MsgBox LCase("JoE BloGGs")


Function: UCase
Returns a given string in upper-case

' example
MsgBox UCase("joe bloggs")
Get System Information
Get system information like User Name and Computer Name.

Dim objNet

' create a network object
Set objNet = CreateObject("WScript.NetWork")

' show the user name
MsgBox "User Name: " & objNet.UserName

' show the computer name
MsgBox "Computer Name: " & objNet.ComputerName

' show the domain name
MsgBox "Domain Name: " & objNet.UserDomain

' destroy the object
Set objNet = Nothing


Get Disk Information
Get information about one of your disk drives.

Dim intSectors, intBytes, intFreeC, intTotalC, intTotal ,intFreeb

' include this windows api
extern.Declare micLong, "GetDiskFreeSpace", "kernel32.dll", "GetDiskFreeSpaceA", micString+micByref, micLong+micByref, micLong+micByref,micLong+micByref,micLong+micByref

' set these values
intSectors = 255
intBytes = 255
intFreeC = 255
intTotalC = 255

' calculate the disk space, using C: in this example
intSpaceAvailable = extern.GetDiskFreeSpace("c:\", intSectors, intBytes, intFreeC, intTotalC)

' calculate the totals
intTotal = intTotalC * intSectors * intBytes
intFreeb = intFreeC * intSectors * intBytes

' show the outputs
msgBox intSectors
msgBox intBytes
msgBox intFreeC
msgBox intTotalC
msgbox intTotal
msgBox intFreeb

Get System Variable Value
Get a value from a Windows System Variable.

' for example to get the oracle home path
MsgBox GetSystemVariable("ORACLE_HOME")

' =============================================================
' function: GetSystemVariable
' desc : Get the value of a system variable
' params : strSysVar is the variable name
' returns : Content of variable name
' =============================================================
Function GetSystemVariable(strSysVar)

Dim objWshShell, objWshProcessEnv

' create the shell object
Set objWshShell = CreateObject("WScript.Shell")
Set objWshProcessEnv = objWshShell.Environment("Process")

' return the system variable content
GetSystemVariable = objWshProcessEnv(strSysVar)

End Function ' GetSystemVariable

Using Description Objects
Using Description Objects to interact with a web page.
This example will illustrate how to use description objects to interact with a web page, www.QTPHelper.com to be more exact...
Note that for the Browser and Page I've used programmatic descriptions, but for the buttons, edits and check-boxes I've used Description Objects. Also take note of the regular expression in the Browser and Page description, just in case the titles change in the future.
You can add more properties to your description objects if you need to, i.e. if your web page has numerous objects of the same type with similar property values.
Dim objLogout
Dim objUser
Dim objPass
Dim objRemember

' create description objects for each item we are dealing with
Set objLogout = Description.Create()
Set objUser = Description.Create()
Set objPass = Description.Create()
Set objRemember = Description.Create()

' define the properties of each item
objLogout("Name").Value = "Logout"
objUser("Name").Value = "username"
objPass("Name").Value = "passwd"
objRemember("Name").Value = "remember"

' check that the user isn't already logged in
If Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton(objLogout).Exist(1) Then

' click logout
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton(objLogout).Click

End If

' set the user name
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebEdit(objUser).Set "User"

' set the password
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebEdit(objPass).Set "Password"

' tick the remember-me tickbox
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebCheckBox(objRemember).Set "ON"


Using Programmatic Descriptions
Using Programmatic Descriptions to interact with a web page.
This example will illustrate how to use programmatic descriptions to interact with a web page, www.QTPHelper.com to be more exact...
Note that I've used a simple regular expression in the Browser and Page description, just in case the titles change in the future.
' click the Home link
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").Link("Text:=Home").Click

' check that the user isn't already logged in
If Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton("Name:=Logout").Exist(1) Then

' click logout
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebButton("Name:=Logout").Click

End If ' user logged in

' set the username
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebEdit("Name:=username").Set "User"

' set the password
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebEdit("Name:=passwd").Set "Password"

' tick the remember-me tickbox
Browser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").WebCheckBox("Name:=remember").Set "ON"









What is QuickTest Automation Object Model?
It's a way to write scripts so as to automate your QuickTest operations.

Some places where we can use AOM
This is a small list of places (but not limited to) where we can use AOM. Thumb Rule - Use it at any place where you find yourself doing repetitive tasks while using QTP.
• AOM can come handy when you have a large no of scripts to be uploaded to QC. A simple script can save you hours of manual work!
• Use AOM to initialize QTP options and settings like add-ins etc.
• You can use AOM to call QTP from other application: For ex: You can write a macro for calling QTP from excel.
Caution: AOM should be used outside of QTP and not within the script (during playback). Though there is no harm using it inside but some of the AOM statements might fail.

How to write AOM scripts?
You need to understand that the very root of QT AOM is Application Object. Every automation script begins with the creation of the QuickTest "Application" object. Creating this object does not start QuickTest. It simply provides an object from which you can access all other objects, methods and properties of the QuickTest automation object model.You can create only one instance of the Application object. You do not need to recreate the QuickTest Application object even if you start and exit QuickTest several times during your script. Once you have defined this object you can then successfully work and perform operations on other objects given in Quick Test Pro > Documentation > QuickTest Automation Reference.
For ex: Let us connect to TD QC using AOM and open a script "qtp_demo"
Dim qt_obj 'Define a Quick Test object
qt_obj = CreateObject("Quick Test.Application") ' Instantiate a QT Object. It does not start QTP.
qt_obj.launch ' Launch QT
qt_obj.visible ' Make QT visible
qt_obj.TDConnection.Connect "http://tdserver/tdbin", _ 'Referencing TDConnection Object
"TEST_DOMAIN", "TEST_Project", "Ankur", "Testing", False ' Connect to Quality Center
If qt_obj.TDConnection.IsConnected Then ' If connection is successful
qt_obj.Open "[QualityCenter] Subject\tests\qtp_demo", False ' Open the test
Else
MsgBox "Cannot connect to Quality Center" ' If connection is not successful, display an error message.
End If
To quickly generate an AOM script with the current QTP settings. Use the Properties tab of the Test Settings dialog box (File > Settings) OR the General tab of the Options dialog box (Tools > Options) OR the Object Identification dialog box (Tools > Object Identification). Each contain a "Generate Script" button. Clicking this button generates a automation script file (.vbs) containing the current settings from the corresponding dialog box.
You can run the generated script as is to open QuickTest with the exact configuration of the QuickTest application that generated the script, or you can copy and paste selected lines from the generated files into your own automation script.
Reference: Quick Test Pro > Documentation > QuickTest Automation Reference.





What is QuickTest Automation Object Model?
It's a way to write scripts so as to automate your QuickTest operations.

Some places where we can use AOM
This is a small list of places (but not limited to) where we can use AOM. Thumb Rule - Use it at any place where you find yourself doing repetitive tasks while using QTP.
• AOM can come handy when you have a large no of scripts to be uploaded to QC. A simple script can save you hours of manual work!
• Use AOM to initialize QTP options and settings like add-ins etc.
• You can use AOM to call QTP from other application: For ex: You can write a macro for calling QTP from excel.
Caution: AOM should be used outside of QTP and not within the script (during playback). Though there is no harm using it inside but some of the AOM statements might fail.

How to write AOM scripts?
You need to understand that the very root of QT AOM is Application Object. Every automation script begins with the creation of the QuickTest "Application" object. Creating this object does not start QuickTest. It simply provides an object from which you can access all other objects, methods and properties of the QuickTest automation object model.You can create only one instance of the Application object. You do not need to recreate the QuickTest Application object even if you start and exit QuickTest several times during your script. Once you have defined this object you can then successfully work and perform operations on other objects given in Quick Test Pro > Documentation > QuickTest Automation Reference.
For ex: Let us connect to TD QC using AOM and open a script "qtp_demo"
Dim qt_obj 'Define a Quick Test object
qt_obj = CreateObject("Quick Test.Application") ' Instantiate a QT Object. It does not start QTP.
qt_obj.launch ' Launch QT
qt_obj.visible ' Make QT visible
qt_obj.TDConnection.Connect "http://tdserver/tdbin", _ 'Referencing TDConnection Object
"TEST_DOMAIN", "TEST_Project", "Ankur", "Testing", False ' Connect to Quality Center
If qt_obj.TDConnection.IsConnected Then ' If connection is successful
qt_obj.Open "[QualityCenter] Subject\tests\qtp_demo", False ' Open the test
Else
MsgBox "Cannot connect to Quality Center" ' If connection is not successful, display an error message.
End If
To quickly generate an AOM script with the current QTP settings. Use the Properties tab of the Test Settings dialog box (File > Settings) OR the General tab of the Options dialog box (Tools > Options) OR the Object Identification dialog box (Tools > Object Identification). Each contain a "Generate Script" button. Clicking this button generates a automation script file (.vbs) containing the current settings from the corresponding dialog box.
You can run the generated script as is to open QuickTest with the exact configuration of the QuickTest application that generated the script, or you can copy and paste selected lines from the generated files into your own automation script.
Reference: Quick Test Pro > Documentation > QuickTest Automation Reference.

Tuesday, September 8, 2009

The A-B-C's of software testing models

Summary:-
This article provide you brief on testing methodologies in various software development models
Theme:-
One doesn't have to spend much time in the software industry to become familiar with several software development models. Some of the most commonly known include water fall, Iterative ,test-first or test –driven development (TFD or TDD), and Extreme Programming (XP). Interestingly, one needs to have a rather diverse set of software development experiences and needs to pay rather close attention to those experiences to realize that there are just as many models for testing software as there are for developing software -- and that the testing model a particular project follows need not be dictated by the software development model.
Categories of testing activities
To aid in this discussion, let's agree to think about software testing in terms of five general categories of activities:
1. Researching information to improve or enhance testing -- This information may come from specifications, use cases, technical design documentation, contracts, industry standards, competing applications, or almost anything else that is likely to improve a tester's ability to test the software deeper, faster or better.
2. Planning and/or designing tests -– This category would encompass such activities as writing test cases, developing test strategies, writing test plans, creating manual test scripts and preparing test data.
3. Scripting and/or executing tests –- Here is where tests are actually executed and/or automated. This is what most non-testers think of when they hear someone talk about software testing.
4. Analyzing test results and new information –- Not all tests produce results that clearly pass or fail. Many tests result in data that can only be understood by human judgment and analysis. Additionally, changing specifications, deadlines or project environments can make a test that had been clearly passing fail without anything changing in the software. This category is where this type of analysis occurs.
5. Reporting relevant information -- Reporting defects and preparing compliance reports are what come to mind first for most people, but a tester may need to report all kinds of additional information.
Again, these five categories are intended to be simple in order to make our discussion about testing models easier. They aren't intended to supplant your current terminology.
Testing waterfall-style
Just like developing software using the waterfall model, testing waterfall-style is a fundamentally linear process except for a minimal feedback loop created by the need to fix some of the problems in the software that are indicated by failing tests. Visually, that feedback loop is equivalent to the small eddy current at the bottom of a real waterfall.

Waterfall-style testing is rarely chosen voluntarily anymore. It is commonly a side effect of some logistical challenge that kept the testers from being able to interact with the application or the developers prior to the first -- and what they hope will be the only -- build of the software. Waterfall testing is occasionally appropriate for situations where it is reasonable to hope the software will "just work," such as applying a service release or a patch to a production application.
Testing, iterative-style
Iterative testing is similar to iterative development in that many of the test iterations happen to coincide with development releases. In that regard, it is like a bunch of waterfall testing cycles strung end to end. Testing iterations differ from development iterations in that there can be iterations prior to the first software build, and there can be multiple test iterations during a single software build. Another difference is that unlike a development iteration, a test iteration can seamlessly abort at any point during the iteration to return to a research mode. While a development iteration can also abort and restart at any time, doing so is quite likely to jeopardize the project schedule.
Iterative software testing is extremely common in the commercial market, though it has many variants. The V-Model, the spiral model, and Rational Unified Process (RUP) based testing are all derivatives of an iterative testing approach. Iterative testing generally works well on projects where software is being developed in pre-planned, predictable increments and on projects where the software is being developed and released in such rapid or unpredictable cycles that it is counter productive for testers to plan around scheduled releases.
Testing, agile-style
Agile-style testing more or less eliminates the element of pre-determined flow from the test cycle in favor of shifting among the five basic activities whenever it adds value to the project to do so. For example, while analyzing the results of a test, the tester may realize that his test was flawed and move directly back to planning and designing tests. In a waterfall or iterative flow, that test redesign would wait until after the current results were reported and preparations were being made for the next test iteration.
Agile-style testing can be implemented as an overall approach or as a complement to any other testing approach. For example, within an iterative test approach, a tester could be encouraged to enter a period of agile testing, side-by-side with a developer, while tracking down and resolving defects in a particular feature.
Agile-style testing is significantly more common than most people realize. As it turns out, this model is what is going on in the heads of many testers all the time, regardless of the external process they are following. Be that as it may, this approach isn't very popular with managers and process improvement specialists because it is misunderstood by many non-testers, and few testers following this process are able to express what they are doing in a manner that gives stakeholders confidence that they are actually doing organized and thoughtful testing.
End of document

The A-B-C's of software testing models

Summary:-
This article provide you brief on testing methodologies in various software development models
Theme:-
This article provide you brief on testing methodologies in various software development models

The Butterfly Model for Test Development (Part-2)

Theme:-

A Swarm of Testing
We have now examined how test analysis, test design, and test execution compose the body of the butterflies in this test development model. In order to understand how the butterfly model monitors and modifies the software development model, we need to digress slightly and reexamine the V software development model itself.
In Figure 1, not only have the micro-iterations naturally present in the design cycle been included, but the major design phase segments (characterized by their outputs) have been separated into smaller arrows to clearly define the transition point from one segment to the next. The test side of the V has been similarly separated, to demarcate the boundaries between successful formal execution of each level of testing. Complete Expanded V Development Model View
No micro-iterations on the test side of the V are shown in this depiction, although there are a few to be found – mostly around the phase segment transitions, where test execution documentary artifacts are formulated and preserved. The relative lack of micro-iterations on the test side of the V is due to the fact that it represents only the formal running of tests – the leg work of analysis and design are done elsewhere. The question, therefore, is: Where?
The answer to this all-important question is shown in Figure 2.
Figure 1. Illustration of the Butterfly Test Development Model
At all micro-iteration termini, and at some micro-iteration geneses, exists a small test butterfly. These tiny test insects each contribute to the overall testing effort, encapsulating the test analysis and design required by whatever minor change is represented by the micro-iteration.
Larger, heavier butterflies spring to life on the boundaries between design phase segments. These larger specimens carry with them the more formal analyses required to transition from one segment to the next. They also answer the call for coordination between the tests designed as part of their smaller brethren. Large butterflies also appear at the transition points between test phase segments, where documentary artifacts of test execution are created in order to claim credit for the formal execution of the test.
A single butterfly, by itself, is of no moment – it cannot possibly have much impact on the overall quality of the application and its tests. But a swarm of butterflies can blot out the sun, affecting great improvement in the product’s quality. The smallest insects handle the smallest changes, while the largest tie together the tests and analyses of them all.
The right-pointing lineage arrows, which show the roots of each test artifact in its corresponding design artifact, point to the moment in the software development model where the analysis and design of tests culminate in their formal execution.
Butterfly Thinking
“A butterfly flutters its wings in Asia, and the weather changes in Europe.” This colloquialism offers insight into the chaotic (in the mathematical sense of the word) nature of software development. Events that appear minor and far removed from relevance can have a profound impact on the software being created. Many seemingly minor and irrelevant events are just that – minor and irrelevant. But some such events, despite their appearance, are not.
Identifying these deceptions is a key outcome of the successful implementation of the butterfly model. The following paragraphs contain illustrations of this concept.
Left Wing Thinking
The FADEC must assert control over the engine’s operation within 300 msec of a power-on event.
This requirement, or a variant of it, appears in every system specification for a FADEC. It is important because it specifies the amount of time available for a cold-start initialization in the software.
The time allotted is explicit. No more than three tenths of a second may elapse before the FADEC asserts itself.
The commencement of that time period is well defined. The nearly vertical rising edge of the FADEC power signal as it moves from zero volts (off) to the operational voltage of the hardware marks the start line.
But what the heck does “assert control” mean?
While analyzing this requirement statement, that question should jump right off the written page at the tester. In one particular instance, the FADEC asserted control by crossing a threshold voltage on a specific analog signal coming out of the box. Unfortunately, that wasn’t in the specification. Instead, I had to ask the senior systems engineer, who had performed similar tests hundreds of times, how to tell when the FADEC asserted itself.
In other words, I couldn’t create a test sketch for the requirement because I couldn’t determine what the end point of the measurement should be. The system specification assumed that the reader held this knowledge, although anyone who was learning the ropes (as I was at that point) had no reasonable chance of knowing. As far as I know, this requirement has never been elaborated.
As a counterpoint example, consider the mass-market application that, according to the verbally preserved requirements, had to be “compelling”. What the heck is “compelling”, and how does one test for it?
In this case, it didn’t matter that the requirement was ill suited for testing. In fact, the testers’ opinions on the subject weren’t even asked for. But the application succeeded, as evidenced by the number of copies purchased. Customers found the product compelling, and therefore the project was a success.
But doesn’t this violate the “must be testable” rule for requirements? Not really. The need to be “compelling” doesn’t constitute a functional requirement, but is instead an aesthetic requirement. Part of the tester’s analysis should weed out such differences, where they exist.
Right Wing Thinking
Returning to our power-up timing example, how can we measure the time between two voltage-based events? There are many possibilities, although most can’t handle the precision necessary for a 300 msec window. Clocks, watches, and even stopwatches would be hideously unreliable for such a measurement.
The test stand workstation also couldn’t be used. That would require synchronization of the command to apply power with the actual application of power. There was a lag in the actual application of power, caused by the software-driven switch that had to be toggled in the test stand’s circuitry. Worse yet, detection of the output voltage required the use of a digital voltmeter, which injected an even larger amount of uncertainty into the measurement.
But a digital oscilloscope attached to a printer would work, provided that the scope was fast enough. The oscilloscope was the measurement device (obviously). The printer was required to “prove” that the test passed. This was, after all, an application subject to FAA certification.
As a non-certification counter example, consider the product whose requirements included the following statement:
Remove unneeded code where possible and prudent.
In other words, “Make the dang thing smaller”. The idea behind the requirement was to shrink the size of the executable, although eliminating unnecessary code is usually a good thing in its own right. No amount of pleading was able to change this requirement into a quantifiable statement, either.
So how the heck can we test for this? In this case, the tester might rephrase the requirement in his or her mind to read:
The downloadable installer must be smaller than version X.
This provides a measurable goal, albeit an assumed one. More importantly, it preserves the common thread between the two statements, which is that the product needed to shrink in size.
Body Thinking
To be honest, there isn’t all that much thought involved in formally executing thoroughly prepared test cases. The main aspect of formal execution is the collection of “evidence” to prove that the tests were run and that they passed. There is, however, the need to analyze the recorded evidence as it is amassed.
For example, aerospace applications commonly must be unit tested. Each individual function or procedure must be exercised according to certain rules. The generally large number of modules involved in a certification means that the unit testing effort required is big, although each unit test itself tends to be small. Naturally, the project’s management normally tries to get the unit testing underway as soon as possible to ensure completion by the “drop-dead” date for unit test completion implied in the V model.
As the established date nears, the test manager must account for every modified unit. The last modification of the unit must predate the configured test procedures and results for that unit. All of the tests must have been peer reviewed prior to formal execution. And all of the tests must have passed during formal execution.
In other words, “dot the I’s and cross the T’s”. It is largely an exercise in bookkeeping, but that doesn’t diminish its importance.
The Swarm Mentality
To better illustrate the swarm mentality, let’s look at an unmanned rocket project that utilized the myriad butterflies of this model to overwhelm bugs that could have caused catastrophic failure. This rocket was really a new version of an existing rocket that had successfully blasted off many, many times.
First, because the new version was to be created as a change to the older version’s software, a complete and thorough system specification analysis was performed, comparing the system specs for both versions. This analysis found that:
• The old version contained a feature that didn’t apply to the new version. A special extended calculation of the horizontal bias (BH) that allowed for late-countdown (between five and ten seconds before launch) holds to be restarted within a few minutes didn’t apply to the new version of the rocket. BH was known to be meaningless after either version left the launch pad, but was calculated in the older version for up to 40 seconds after liftoff.
• The updated flight profile for the new version had not been included in the updated specification, although this omission had been agreed to by all relevant parties. That meant that discrepancies between the early trajectory profiles between the two versions were not available for examination. The contractors building the rocket didn’t want to change their agreement on this subject, so the missing trajectory profile information was marked as a risk to be targeted with extra-detailed testing.
Because of the fairly serious questions raised in the system requirements analysis, the test engineers decided to really attack the early trajectory operation of the new version. Because this was an aerospace application, they knew that the subsystems had to be qualified for flight prior to integration into the overall system. That meant that the inertial reference system (SRI) that provided the raw data required to calculate BH would work, at least as far as it was intended to.
But how could they test the interaction of the SRI and the calculation of BH? The horizontal bias was also a product of the rocket’s acceleration, so they knew that they would have to at least simulate the accelerometer inputs to the control computer (it is physically impossible to make a vibration table approach the proper values for the rocket’s acceleration).
If they had a sufficiently detailed SRI model, they could also simulate the inertial reference system. Without a detailed simulation, they’d have to use a three-axis dynamic vibration table. Because the cost of using the table for an extended period of time was higher than the cost of creating a detailed simulation, they decided to go with the all simulation approach.
In the meantime, a detailed analysis of the software requirements for both versions revealed a previously unknown conceptual error. Every exception raised in the Ada software automatically shut down the processor – whether the exception was caused by a hardware or software fault!
The thinking behind this problem was that exceptions should only address random hardware failures, where the software couldn’t hope to recover. Clearly, software exceptions were possible, even if they were improbable. So, the exception handling in the software spec was updated to differentiate between hardware and software based exceptions.
Examining the design of the software, the test engineers were amazed to discover that the horizontal bias calculations weren’t protected for Operand Error, which is automatically raised in Ada when a floating point real to integer conversion exceeds the available range of the integer container. BH was involved just such a conversion!
The justification for omitting this protection was simple, at least for the older version of the rocket. The possible values of BH were physically limited in range so that the conversion couldn’t ever overflow. But the newer version couldn’t claim that fact, so the protection for Operand Error was put into the new version’s design. Despite the fact that this could put the 80% usage goal for the SRI computer at risk, the possibility that the computer could fail was simply too great.
Finally, after much gnashing of teeth, the test engineers convinced the powers that be to completely eliminate the prolonged calculation of horizontal bias because it was useless in the new version. The combined risks of the unknown trajectory data, the unprotected conversion to integer, and the money needed to fund the accurate SRI simulation was too much for the system’s developers. They at last agreed that it was better to eliminate the unnecessary processing, even though it worked for the previous version.
As a result, the maiden demonstration flight for the Ariane 5 rocket went off without a hitch.
That’s right – I have been describing the findings of the inquiry board for the Ariane 5 in light of how a full and rigorous implementation of the butterfly model would have detected, mitigated, or eliminated them [LION96].
Ariane 4 contained an extended operation alignment function that allowed for late-countdown holds to be handled without long delays. In fact, the 33rd flight of the Ariane 4 rocket used this feature in 1989.
The Ariane 5 trajectory profile was never added to the system requirements. Instead, the lower values in the Ariane 4 trajectory data were allowed to stand.
The SRI computers (with the deficient software) were therefore never tested to the updated trajectory telemetry.
The missing Operand Error exception handling for the horizontal bias therefore never occurred during testing, causing the SRI computer to shut down.
The flawed concept of all exceptions being caused by random hardware faults was therefore never exposed.
SRI 1, the first of the dual redundant components, therefore halted on an Operand Error caused by the conversion of BH in the 39th second after liftoff. SRI 2 immediately took over as the active inertial reference system.
But then SRI 2 failed because of the same Operand Error in the following data cycle (72 msec in duration).
And therefore, Ariane 5 self destructed in the 42nd second of its maiden voyage – all for lack of a swarm of butterflies.
The Butterfly Model within the V Model Context
The butterfly model of test development is not a component of the V software development model. Instead, the butterfly test development model is a superstructure imposed atop the V model that operates semi-independently, in parallel with the development of software.
The main relationship between the V model and the butterfly swarm of testing activity is timing, at least on the design side of the V. Test development is driven by software development, for software is what we are testing. Therefore, the macro and micro iterations of software development define the points at which test development activity is both warranted and required. The individual butterflies must react to the iterative software development activity that spawned them, while the whole of the swarm helps to shape the large and small perturbations in the software design stream.
On the test side of the V, the relationship is largely reversed – the software milestones of the V model are the results of butterfly activity on the design side. The differences between the models give latitude to both the developer and the tester to envision the act of testing within their particular operational context. The developer is free to see testing as the culmination of their development activity. The tester is likewise free to see the formal execution of testing as the end of the line – where all of the analytical and test design effort that shepherded the software design process is transformed into the test artifacts required for progression from development to delivery.
But the butterfly model does not entirely fall within the bounds of the V model, either. The third issue taken with the standardized V model stated that the roots of software testing lay mainly within the boundaries of the software to be tested. But proper performance of test analysis and design require knowledge outside the realm of the application itself.
Testers in the butterfly model require knowledge of testing techniques, tools, methodologies, and technologies. Books and articles about test theory are hugely important to the successful implementation of the butterfly model. Similarly, software testing conferences and proceedings are valuable resources.
Testers in this test development model also need to keep abreast of technological advancements related to the application being developed. Trade journals and periodicals are valuable sources for such information.
In the end, the tester is required to not only know the application being tested, but also to understand (at some level) software testing, valid testing techniques, software testing tools and technologies, and even a little about human nature.
Next Steps
The butterfly model of test development is far from complete. The model as described herein is a first step toward a complete and usable model. Some of the remaining steps to finish it include:
• Creating a taxonomy of test butterflies that describes each type of testing activity within the context of the software development activity it accompanies.
• Correlating the butterfly taxonomy with a valid taxonomy of software bugs (to understand what the butterflies eat).
• Formally defining and elaborating the “objectives” associated with various testing activities.
• Creating a taxonomy of “artifacts” to better define the parameters of the model’s execution.
• Expanding visualization of the model to cover the spiral development model.
• Defining the framework necessary to achieve full implementation of the model.
• Identifying methods of automating significant portions of the model’s implementation.
Summary
The butterfly model for software test development is a semi-dependent model that represents the bifurcated role of software testing with respect to software development. The underlying realization that software development and test development are parallel processes that are separate but complementary is embodied by the butterfly model’s superposition atop the V development model.
Correlating the V model and butterfly model requires understanding that the standard V model is a high-level view of software development that hides the myriad micro-iterations all along the design and test legs of the V. These micro-iterations are the core of successful software development. They represent the incorporation of new knowledge, new requirements, and lessons learned – primarily during the design phase of software development, although the formation of test artifacts also includes some micro-iterative activity.
Tiny test butterflies occupy the termini of these micro-iterations, as well as some of their geneses. Larger, more comprehensive butterflies occupy phase segment transition points, where the nature of work is altered to reach toward the next goal of the software’s development.
The parts of the butterfly represent the three legs of successful software testing – test analysis, test design, and formal test execution. Of the three, formal execution is the smallest, although it is the only piece explicitly represented in the V model. Test analysis and test design, ignored in the V model, are recognized in the butterfly model as shaping forces for software development, as well as being the foundation for test execution.
Finally, the butterfly model is in its infancy, and there is significant work to do before it can be fully described. However, the visualization of a swarm of testing butterflies darkening the sky while they steer software away from error injection is satisfying– at last we have a physical phenomena that represents the ephemeral act of software testing.

End of document