@@ -94,7 +94,7 @@ def match(self, path):
9494class FileContains (Matcher ):
9595 """Matches if the given file has the specified contents."""
9696
97- def __init__ (self , contents = None , matcher = None ):
97+ def __init__ (self , contents = None , matcher = None , encoding = None ):
9898 """Construct a ``FileContains`` matcher.
9999
100100 Can be used in a basic mode where the file contents are compared for
@@ -103,9 +103,14 @@ def __init__(self, contents=None, matcher=None):
103103 matched against an arbitrary matcher (by passing ``matcher`` instead).
104104
105105 :param contents: If specified, match the contents of the file with
106- these contents.
106+ these contents. If bytes, the file will be opened in binary mode.
107+ If str, the file will be opened in text mode using the specified
108+ encoding (or the default encoding if not specified).
107109 :param matcher: If specified, match the contents of the file against
108110 this matcher.
111+ :param encoding: Optional text encoding to use when opening the file
112+ in text mode. Only used when contents is a str (or when using a
113+ matcher for text content). Defaults to the system default encoding.
109114 """
110115 if contents == matcher is None :
111116 raise AssertionError ("Must provide one of `contents` or `matcher`." )
@@ -115,19 +120,23 @@ def __init__(self, contents=None, matcher=None):
115120 )
116121 if matcher is None :
117122 self .matcher = Equals (contents )
123+ self ._binary_mode = isinstance (contents , bytes )
118124 else :
119125 self .matcher = matcher
126+ self ._binary_mode = False
127+ self .encoding = encoding
120128
121129 def match (self , path ):
122130 mismatch = PathExists ().match (path )
123131 if mismatch is not None :
124132 return mismatch
125- f = open (path )
126- try :
127- actual_contents = f .read ()
128- return self .matcher .match (actual_contents )
129- finally :
130- f .close ()
133+ if self ._binary_mode :
134+ with open (path , "rb" ) as f :
135+ actual_contents : bytes | str = f .read ()
136+ else :
137+ with open (path , encoding = self .encoding ) as f :
138+ actual_contents = f .read ()
139+ return self .matcher .match (actual_contents )
131140
132141 def __str__ (self ):
133142 return f"File at path exists and contains { self .matcher } "
0 commit comments