In Python, how do I mock an object created in a with statement using mox unit test library
Code
class MyCode:
def generate_gzip_file(self):
with gzip.GzipFile('file_name.txt.gz','wb') as f:
f.write('data')
Unit Test
class MyCodeTest(unittest.TestCase):
def test_generate_gzip_file(self):
mox = mox.Mox()
mock_gzip_file = self.mox.CreateMock(gzip.GzipFile)
mox.StubOutWithMock(gzip, 'GzipFile')
gzip.GzipFile('file_name.txt.gz','wb').AndReturn(mock_file)
mock_gzip_file.write('data')
mox.ReplayAll()
MyCode().generate_gzip_file()
mox.VerifyAll()
I get the error AttributeError: __exit__
on line
with gzip.GzipFile('file_name.txt.gz','wb') as f:
DSM is correct that the mocked instance of
gzip.GzipFile
isn't ending up with a__exit__
method for some reason. You'll get exactly the same error if you forget to define__exit__
on a class you use with awith
statement. For example:Fortunately, you can work around the problem by using Mox's
CreateMockAnything()
method to create amock_gzip_file
object that doesn't enforce a particular interface. You'll need to be careful to ensure that you set up the expectations for themock_gzip_file
object correctly (i.e. that you set up expectations for when and how the__enter__()
and__exit__(...)
methods will be called). Here's an example that worked for me:When I run this I get: