如何在test注释中使用带有patch.object()的mock_open()

时间:2013-09-18 08:51:00

标签: python unit-testing mocking

我正在尝试模拟从文件读取。使用示例可以使用如下结构:

with patch('__builtin__.open', mock_open(read_data='1'), create=True) as m:
    with open('foo') as h:
        result = h.read()

我想知道,有没有办法使用我的testcase注释来模拟open函数。像:

@patch.object(__builtin__, 'open')
def test_check_status_running(self, m_open):

我找不到正确的方法,因为对我来说它适用于int而不适用于字符串:

@patch.object(__builtin__, 'open')
def test_check_status_running1(self, m_open):
    m_open = mock_open(read_data='1')
    pid = open('testfile').read().strip()
    print type(pid)                    # <class 'mock.MagicMock'>
    self.assertEqual(1, int(pid))      # Pass
    self.assertEqual('1', pid)         # Fails MismatchError: '1' != <MagicMock name='open().read()' id='39774928'>

2 个答案:

答案 0 :(得分:10)

您可以通过多种方式修补open方法。我更喜欢修补builtins.open并将模拟对象传递给测试方法,如下所示:

from unittest.mock import patch, mock_open
from mymodule import method_that_read_with_open

class TestPatch(unittest.TestCase):
    @patch('builtins.open', new_callable=mock_open, read_data='1')
    def test_open_file(self, m):
        string_read = method_that_read_with_open()
        self.assertEqual(string_read, '1')
        m.assert_called_with('filename', 'r')

请注意,我们正在传递mock_open函数而不调用它!

但是因为你正在修补内置方法,你也可以这样做:

class TestPatch(unittest.TestCase):
    @patch('builtins.open', mock_open(read_data='1'))
    def test_open_file(self):
        string_read = method_that_read_with_open()
        self.assertEqual(string_read, '1')
        open.assert_called_with('filename', 'r')

这两个例子基本上是等价的:在第一个例子中,我们给补丁方法一个工厂函数,他将调用它来创建模拟对象,在第二个我们使用已经创建的对象作为参数。

答案 1 :(得分:1)

将mock_open实例分配给new_callable参数:

class TestClass(unittest.TestCase):
    @mock.patch('file_tested.open', new_callable=mock.mock_open())
    def test_function(self, mock_open):
        pass