【问题标题】:How do I patch mock multiple calls from os in python?如何在 python 中修补来自 os 的模拟多个调用?
【发布时间】:2021-09-17 07:29:31
【问题描述】:

我有一个方法可以执行以下操作:

    import os

    ...

    if not os.path.exists(dirpath):
        os.makedirs(dirpath)

我正在尝试模拟 makedirspath.exists,但是当我使用 patch 执行此操作时,模拟冲突:

@patch('os.makedirs')
@patch('os.path.exists')
def test_foo(self, makedirs, exists):
    c = Config()
    c.foo()

    assert makedirs.called
    assert exists.called

如果我禁用makedirsexists,它们都可以正常工作,但一起使用时会出现问题。

我也尝试过使用with patch('os.makedirs') as makedirs: 语法,它不会改变任何东西。

有谁知道他们为什么会发生冲突或者我可以做些什么来解决这个问题?

谢谢!

【问题讨论】:

    标签: python mocking python-unittest python-unittest.mock


    【解决方案1】:

    如果你像这样模拟os.path.exists,它将返回一个模拟,它总是评估为True - 所以你的代码永远不会到达os.makedirs。为了使这个工作,你必须为模拟提供一个返回值:

    @patch('os.makedirs')
    @patch('os.path.exists', return_value=False)
    def test_foo(self, exists, makedirs):
        c = Config()
        c.foo()
    
        makedirs.assert_called_once()
        exists.assert_called_once()
    

    另请注意,在您的代码中模拟的顺序已恢复 - 最后一个补丁装饰器的参数必须放在第一位。

    我还用xx.assert_called_once() 替换了assert xx.called - Mockassert_called_... 方法为检查提供了更细粒度的可能性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 2023-03-28
      • 2015-11-25
      • 1970-01-01
      • 2013-09-24
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多