如何将 mock_open 与 Python UnitTest 装饰器一起使用?

YPC*_*ble 5 python unit-testing mocking python-mock python-unittest

我有一个测试如下:

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.
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

类型错误:test_file_open_and_read() 需要 3 个参数(给出 2 个)

我试图指定我想要__builtin__.open模拟另一个文件的方法,mock.mock_open而不是装饰器mock.MagicMock的默认行为patch。我怎样才能做到这一点?

小智 5

应该使用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)
Run Code Online (Sandbox Code Playgroud)

请注意,我们将函数句柄传递mock.mock_opennew_callable,而不是结果对象。这允许我们访问mock_open_method().writewrite函数,就像文档中的示例所示mock_open


Mau*_*ldi 2

create您错过了内置参数open

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