【发布时间】:2012-01-18 05:09:15
【问题描述】:
在 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:
【问题讨论】:
-
您使用的是 python 2.6 或更低版本吗?我认为 GzipFile 直到 2.7 才支持上下文管理。如果是这样,您可能必须编写自己的(小)包装器。
-
GzipFile 支持迭代和 with 语句。根据文档docs.python.org/library/gzip.html
-
是的,正如我所说,这是 2.7 附带的,因为您运行的是 2.7,所以这不是问题。我认为发生的事情是存根版本没有以
__exit__结束。我认为你必须确保 with 被模拟(参见garybernhardt.github.com/python-mock-comparison 的示例——搜索“上下文管理器”并查看 Mox 示例。)
标签: python unit-testing gzip mox