如何从模拟实例的方法中抛出异常?
How to throw exception from mocked instance's method?
我要测试的这个演示功能非常简单。
def is_email_deliverable(email):
try:
return external.verify(email)
except Exception:
logger.error("External failed failed")
return False
这个函数使用了我想模拟的 external
服务。
但我不知道如何从 external.verify(email)
中抛出 exception
,即如何强制执行 except
子句。
我的尝试:
@patch.object(other_module, 'external')
def test_is_email_deliverable(patched_external):
def my_side_effect(email):
raise Exception("Test")
patched_external.verify.side_effects = my_side_effect
# Or,
# patched_external.verify.side_effects = Exception("Test")
# Or,
# patched_external.verify.side_effects = Mock(side_effect=Exception("Test"))
assert is_email_deliverable("some_mail@domain.com") == False
问题声称有答案,但对我不起作用。
您使用了 side_effects
而不是 side_effect
。
是这样的
@patch.object(Class, "attribute")
def foo(attribute):
attribute.side_effect = Exception()
# Other things can go here
顺便说一句,捕获所有 Exception
并根据它处理的方法不是很好。
我要测试的这个演示功能非常简单。
def is_email_deliverable(email):
try:
return external.verify(email)
except Exception:
logger.error("External failed failed")
return False
这个函数使用了我想模拟的 external
服务。
但我不知道如何从 external.verify(email)
中抛出 exception
,即如何强制执行 except
子句。
我的尝试:
@patch.object(other_module, 'external')
def test_is_email_deliverable(patched_external):
def my_side_effect(email):
raise Exception("Test")
patched_external.verify.side_effects = my_side_effect
# Or,
# patched_external.verify.side_effects = Exception("Test")
# Or,
# patched_external.verify.side_effects = Mock(side_effect=Exception("Test"))
assert is_email_deliverable("some_mail@domain.com") == False
您使用了 side_effects
而不是 side_effect
。
是这样的
@patch.object(Class, "attribute")
def foo(attribute):
attribute.side_effect = Exception()
# Other things can go here
顺便说一句,捕获所有 Exception
并根据它处理的方法不是很好。