我有一个要单元测试的功能,其中包含调用其他两个功能的功能。我不确定如何使用补丁同时模拟两个函数。我在下面提供了我的意思的示例。当我进行鼻子测试时,测试通过了,但是我觉得必须有一种更清洁的方法来进行测试,而我实际上并不了解有关f.close()的内容。
目录结构如下所示:
program/
program/
data.py
tests/
data_test.py
data.py:
import cPickle
def write_out(file_path, data):
f = open(file_path, 'wb')
cPickle.dump(data, f)
f.close()
data_test.py:
from mock import MagicMock, patch
def test_write_out():
path = '~/collection'
mock_open = MagicMock()
mock_pickle = MagicMock()
f_mock = MagicMock()
with patch('__builtin__.open', mock_open):
f = mock_open.return_value
f.method.return_value = path
with patch('cPickle.dump', mock_pickle):
write_out(path, 'data')
mock_open.assert_called_once_with('~/collection', 'wb')
f.close.assert_any_call()
mock_pickle.assert_called_once_with('data', f)
结果:
$ nosetests
.
----------------------------------------------------------------------
Ran 1 test in 0.008s
OK