我有一个要单元测试的函数包含调用其他两个函数。我不确定如何使用补丁正确地同时模拟这两个函数。我在下面提供了一个例子来说明我的意思。当我运行鼻子测试时,测试通过了,但我觉得必须有一种更清洁的方法来做到这一点,我并不真正理解关于 f.close() 的文章......
目录结构如下所示:
program/
program/
data.py
tests/
data_test.py
数据.py:
import cPickle
def write_out(file_path, data):
f = open(file_path, 'wb')
cPickle.dump(data, f)
f.close()
数据测试.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