使用open()库来模拟和测试mock返回的对象的代码是正确的?
whitelist_data.py
:
WHITELIST_FILE = "testdata.txt"
format_str = lambda s: s.rstrip().lstrip('www.')
whitelist = None
with open(WHITELIST_FILE) as whitelist_data:
whitelist = set(format_str(line) for line in whitelist_data)
if not whitelist:
raise RuntimeError("Can't read data from %s file" % WHITELIST_FILE)
def is_whitelisted(substr):
return 1 if format_str(substr) in whitelist else 0
以下是我尝试测试它的方法。
import unittest
import mock
TEST_DATA = """
domain1.com
domain2.com
domain3.com
"""
class TestCheckerFunctions(unittest.TestCase):
def test_is_whitelisted_method(self):
open_mock = mock.MagicMock()
with mock.patch('__builtin__.open',open_mock):
manager = open_mock.return_value.__enter__.return_value
manager.__iter__ = lambda s: iter(TEST_DATA.splitlines())
from whitelist_data import is_whitelisted
self.assertTrue(is_whitelisted('domain1.com'))
if __name__ == '__main__':
unittest.main()
python tests.py
的结果是:
$ python tests.py
E
======================================================================
ERROR: test_is_whitelisted_method (__main__.TestCheckerFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 39, in test_is_whitelisted_method
from whitelist_data import is_whitelisted
File "/Users/supa/Devel/python/whitelist/whitelist_data.py", line 20, in <module>
whitelist = set(format_str(line) for line in whitelist_data)
TypeError: 'Mock' object is not iterable
----------------------------------------------------------------------
Ran 1 test in 0.001s
UPD:感谢Adam,我重新安装了模拟库(pip install -e hg+https://code.google.com/p/mock#egg=mock
)并更新了tests.py.像魅力一样。
答案 0 :(得分:16)
您正在寻找MagicMock
。这支持迭代。
在模拟0.80beta4中,patch
返回MagicMock
。所以这个简单的例子有效:
import mock
def foo():
for line in open('myfile'):
print line
@mock.patch('__builtin__.open')
def test_foo(open_mock):
foo()
assert open_mock.called
如果你正在运行模拟0.7.x(它看起来像你),我认为你不能单独使用补丁来实现这一点。您需要单独创建模拟,然后将其传递给补丁:
import mock
def foo():
for line in open('myfile'):
print line
def test_foo():
open_mock = mock.MagicMock()
with mock.patch('__builtin__.open', open_mock):
foo()
assert open_mock.called
注意 - 我用py.test运行这些,但是,这些相同的方法也适用于unittest。