【发布时间】:2023-03-22 17:40:01
【问题描述】:
大多数第三方 Python 库都会抛出自定义异常。其中许多异常都有其自身的依赖性和副作用。例如,考虑以下情况:
class ThirdPartyException(BaseException):
def __init__(self):
print("I do something arcane and expensive upon construction.")
print("Maybe I have a bunch of arguments that can't be None, too.")
def state(self) -> bool:
# In real life, this could be True or False
return True
此外,假设我必须处理这个异常,并且要做到这一点,我需要查看异常的状态。如果我想编写测试来检查处理此异常时的行为,我必须能够创建ThirdPartyException。但我可能连怎么做都想不通,更别提怎么便宜了。
如果这不是Exception 而我想编写测试,我会立即联系MagicMock。但我不知道如何使用MagicMock,但有一个例外。
如何测试以下代码中的错误处理案例,最好使用py.test?
def error_causing_thing():
raise ThirdPartyException()
def handle_error_conditionally():
try:
error_causing_thing()
exception ThirdPartyException as e:
if state:
return "Some non-error value"
else:
return "A different non-error value"
【问题讨论】:
-
要明确的是,
ThirdPartException是您无法控制的东西,并且您希望error_causing_thing提出具有特定状态值的东西吗? -
将异常 instance 作为属性或参数
side_effect提供给模拟或patch调用。 -
@chepner,是的。如果
state是布尔值,我将编写两个测试用例来练习我的函数如何处理ThirdPartyException。 -
@KlausD.,我想避免实际构建
ThirdPartyException。我试图用spec=ThirdPartyException模拟一个,但我得到一个错误,你不能提出任何不是BaseException子类的东西。当我尝试修补作为模拟时,我得到了同样的错误。当我尝试将补丁作为我自己的替代异常时,它根本没有得到处理(因为它未被识别为ThirdPartyException的实例)。 -
最好弄清楚如何让
error_causing_thing自然地引发适当的异常。
标签: python unit-testing exception-handling pytest