我有以下代码Python测试:模拟导入错误
try:
from foo_fast import bar
except ImportError
from foo import bar
def some_function(a, b):
return foo(a, b)
我现在要测试的两种情况foo_fast
可以进口,它不能。
使用pytest和pytest-模拟,我自然要封装在一个pytest固定两种情况,所以我想我会用
@pytest.fixture(params=(True, False))
def use_fast(request, mock):
if request.param is not True:
mock.patch("foo_fast.bar", side_effect=ImportError)
return request.param
def test_foo(use_fast):
assert some_function(1, 2)
但是似乎import语句测试之前只运行一次开始,所以我不能嘲笑ImportError
。
如何模拟这些ImportError
个案?