如何修补 python 中来自 os 的模拟多个调用?
How do I patch mock multiple calls from os in python?
我有一个方法可以执行以下操作:
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
,它将 return 一个模拟,其计算结果始终为 True
- 因此您的代码永远不会达到 os.makedirs
。要使其工作,您必须为模拟提供 return 值:
@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
- Mock
的 assert_called_...
方法为检查提供了更细粒度的可能性。
我有一个方法可以执行以下操作:
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
,它将 return 一个模拟,其计算结果始终为 True
- 因此您的代码永远不会达到 os.makedirs
。要使其工作,您必须为模拟提供 return 值:
@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
- Mock
的 assert_called_...
方法为检查提供了更细粒度的可能性。