我有以下代碼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
個案?