目录结构如下所示:
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
答案 0 :(得分:72)
您可以使用修补程序装饰器简化测试并将其嵌套(默认情况下它们是MagicMock
个对象):
@patch('cPickle.dump')
@patch('__builtin__.open')
def test_write_out(mock_open, mock_pickle):
path = '~/collection'
f = mock_open.return_value
f.method.return_value = path
write_out(path, 'data')
mock_open.assert_called_once_with('~/collection', 'wb')
mock_pickle.assert_called_once_with('data', f)
f.close.assert_any_call()
对MagicMock
实例的调用返回一个新的MagicMock
实例,因此您可以检查返回的值是否像任何其他模拟对象一样被调用。在这种情况下,f
是名为MagicMock
的{{1}}(尝试打印'open()'
)。
答案 1 :(得分:34)
除了响应@Matti John之外,您还可以在函数patch
内使用test_write_out
:
from mock import MagicMock, patch
def test_write_out():
path = '~/collection'
with patch('__builtin__.open') as mock_open, \
patch('cPickle.dump') as mock_pickle:
f = mock_open.return_value
...
答案 2 :(得分:2)
以下是一个简单示例,说明如何使用mock在ConflictError
函数中测试create_collection
:
import os
from unittest import TestCase
from mock import patch
from ..program.data import ConflictError, create_collection
class TestCreateCollection(TestCase):
def test_path_exists(self):
with patch.object(os.path, 'exists') as mock_method:
mock_method.return_value = True
self.assertRaises(ConflictError, create_collection, 'test')
另请参阅mock docs和Michael Foord的精彩introduction to mock。