如何解决如何在 python 中修补来自 os 的模拟多个调用?
我有一个方法可以执行以下操作:
import os
...
if not os.path.exists(dirpath):
os.makedirs(dirpath)
我正在尝试模拟 makedirs
和 path.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
如果我禁用 makedirs
或 exists
,它们都可以正常工作,但一起使用时会出现问题。
我也试过使用 with patch('os.makedirs') as makedirs:
语法,它不会改变任何东西。
有谁知道他们为什么会发生冲突或我能做些什么来解决这个问题?
谢谢!
解决方法
如果你模拟 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()
另请注意,在您的代码中恢复了模拟的顺序 - 最后一个补丁装饰器的参数必须先行。
我还用 assert xx.called
替换了 xx.assert_called_once()
- assert_called_...
的 Mock
方法为检查提供了更细粒度的可能性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。