使用补丁模拟两个函数进行单元测试

时间:2013-04-02 11:52:29

标签: python unit-testing testing mocking nose

我有一个函数我要单元测试包含调用其他两个函数。我不确定如何使用补丁同时模拟两个函数。我在下面提供了一个我的意思的例子。当我运行测试时,测试通过,但我觉得必须有一个更清洁的方法来做这个,我真的不明白关于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

3 个答案:

答案 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