在Python中,如何使用mox单元测试库
模拟在with语句中创建的对象代码
class MyCode:
def generate_gzip_file(self):
with gzip.GzipFile('file_name.txt.gz','wb') as f:
f.write('data')
单元测试
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()
我在行
上收到错误AttributeError: __exit__
with gzip.GzipFile('file_name.txt.gz','wb') as f:
答案 0 :(得分:3)
DSM是正确的,gzip.GzipFile
的模拟实例由于某种原因没有以__exit__
方法结束。如果您忘记在使用__exit__
语句的类上定义with
,则会得到完全相同的错误。例如:
>>> class C(object):
... def __enter__(self):
... return self
...
>>> with C() as c:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __exit__
幸运的是,您可以使用Mox的CreateMockAnything()
方法创建一个不强制执行特定接口的mock_gzip_file
对象来解决此问题。您需要小心确保正确设置mock_gzip_file
对象的期望值(即您设置了对__enter__()
和__exit__(...)
方法的时间和方式的期望所谓的)。这是一个适合我的例子:
import gzip
import mox
import unittest
class MyCode:
def generate_gzip_file(self):
with gzip.GzipFile('file_name.txt.gz', 'wb') as f:
f.write('data')
class MyCodeTest(unittest.TestCase):
def test_generate_gzip_file(self):
mymox = mox.Mox()
mock_gzip_file = mymox.CreateMockAnything()
mymox.StubOutWithMock(gzip, 'GzipFile')
gzip.GzipFile('file_name.txt.gz', 'wb').AndReturn(mock_gzip_file)
mock_gzip_file.__enter__().AndReturn(mock_gzip_file)
mock_gzip_file.write('data')
mock_gzip_file.__exit__(None, None, None).AndReturn(None)
mymox.ReplayAll()
MyCode().generate_gzip_file()
mymox.VerifyAll()
if __name__ == '__main__':
unittest.main()
当我跑步时,我得到:
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK