Python单元测试如何使用Mox来模拟带有语句的gzip

时间:2012-01-18 05:09:16

标签: python unit-testing gzip mox

在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:

1 个答案:

答案 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