如何使用带Python UnitTest decorator的mock_open?

2024-05-06 21:09:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个测试如下:

import mock

# other test code, test suite class declaration here

@mock.patch("other_file.another_method")
@mock.patch("other_file.open", new=mock.mock_open(read=["First line", "Second line"])
def test_file_open_and_read(self, mock_open_method, mock_another_method):
    self.assertTrue(True) # Various assertions.

我得到以下错误:

TypeError: test_file_open_and_read() takes exactly 3 arguments (2 given)

我试图指定我希望用mock.mock_open而不是mock.MagicMock来模拟另一个文件的__builtin__.open方法,这是patch装饰器的默认行为。我该怎么做?在


Tags: andtestimportselfreadlineanothercode
2条回答

应该使用new_callable而不是new。也就是说

@mock.patch("other_file.open", new_callable=mock.mock_open)
def test_file_open_and_read(self, mock_open_method):
    # assert on the number of times open().write was called.
    self.assertEqual(mock_open_method().write.call_count,
                     num_write_was_called)

注意,我们将函数句柄mock.mock_open传递给new_callable,而不是结果对象。这允许我们执行mock_open_method().write来访问write函数,就像{}文档中的示例所示。在

您错过了来自open内建的参数create。在

@mock.patch("other_file.open", new=mock.mock_open(read=["First line", "Second line"], create=True)

相关问题 更多 >