94

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

3 回答 3

136

您可以通过使用补丁装饰器并像这样嵌套它们来简化测试(默认情况下它们是MagicMock对象):

from unittest.mock import patch

@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命名'open()'(尝试打印f)。

于 2013-04-10T09:47:39.613 回答
72

除了响应@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
        ...
于 2015-06-12T08:55:13.420 回答
2

这是一个关于如何使用模拟测试函数提升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 文档和 Michael Foord对 mock 的精彩介绍

于 2013-04-06T19:13:38.227 回答