【问题标题】:How can I use mock_open with a Python UnitTest decorator?如何将 mock_open 与 Python UnitTest 装饰器一起使用?
【发布时间】:2016-09-12 22:31:48
【问题描述】:

我有一个测试如下:

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() 只需要 3 个参数(给定 2 个)

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

【问题讨论】:

    标签: python unit-testing mocking python-unittest python-mock


    【解决方案1】:

    您错过了来自open 内置参数create

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

    【讨论】:

    • 修补内置插件时不需要这样做,文档说“在 3.5 版中更改:如果您正在修补模块中的内置插件,那么您不需要传递 create=True,它将由默认。”我仍然遇到同样的错误。
    【解决方案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 函数,就像mock_open 文档中的示例所示。

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 2016-03-06
      • 2020-02-25
      • 2012-12-17
      • 2017-09-20
      相关资源
      最近更新 更多