TestComplete Tip: Comparing text files in VBScript

  September 29, 2006

Sometimes testers face a quite common task - compare a text file generated by the tested software (e.g. a report file) with some predefined template file. Standard means for comparing files can be ineffective in this case if the generated file contains date and time stamps inside - they make comparing of such files fail even if the meaningful content of the compared files is absolutely identical.

This problem can be solved quite easy with help of regular expressions which allows isolating variable date and time stamps from comparing. VBScript has internal support of regular expressions and you can find documentation on this feature in the following MSDN article:

The script below shows how it is possible to use regular expressions to compare text files in TestComplete scripts ignoring the date/time stamps (for example: 4/25/2006 10:51:35AM).

' TestComplete VBScript
Sub Main

  fileName1 = "d:text1.txt"

  fileName2 = "d:text2.txt"

  If CompareFiles(fileName1, fileName2) Then
    Call Log.Message("The files are equal")
    Call Log.Error("The files are different")
  End If
End Sub

Function CompareFiles(fileName1, fileName2)
  Const ForReading = 1
  Const ForWriting = 2
  Const ForAppending = 8

  'Creates the FileSystemObject object
  Set fso = Sys.OleObject("Scripting.FileSystemObject")

  'Reads the first text file
  Set file1 = fso.OpenTextFile(fileName1, ForReading)

  fileText1 = file1.ReadAll


  'Reads the second text file
  Set file2 = fso.OpenTextFile(fileName2, ForReading)

  fileText2 = file2.ReadAll


  'Creates the regular expression object
  Set regEx = New RegExp

  'Specifies the pattern for the date/time mask
  'MM/DD/YYYY HH:MM:SSLL (for example: 4/25/2006 10:51:35AM)

  regEx.Pattern = "d{1,2}.d{1,2}.d{2,4}sd{1,2}:d{2}:d{2}w{2}"

  regEx.IgnoreCase = True

  regEx.Global = True

  'Replaces the text matching the specified date/time format with <ignore>

  newText1 = regEx.Replace(fileText1, "<ignore>")

  newText2 = regEx.Replace(fileText2, "<ignore>")

  'Compares the text
  If newText1 = newText2 Then

    CompareFiles = True

    CompareFiles = False
  End If
End Function