我有一个函数,我想单元测试包含调用两个其他函数。我不确定如何能够同时正确地使用补丁模拟这两个功能。我举了一个例子来说明我在下面的意思。当我运行 nosetest 时,测试通过了,但是我觉得必须有一个更干净的方法来做这件事,而且我并不真正理解关于 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()
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