class CustomException(ValueError):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
我有一个类,如上所述的例外。引发错误的函数使用foo
和bar
来为调用类提供有关异常的一些额外信息。
我试图像这样测试这种行为:
with pytest.raises(CustomException) as ce:
func_that_raises(broken_args)
assert ce.foo == 'blah'
assert not ce.bar # if `bar` is expected to be a boolean
然而,ce
是py.test给我的ExceptionInfo
的一个例子,而不是CustomException
的一个例子。有没有办法保留和检查引发的原始异常?
实际的异常对象可用作ce.value
,因此您的断言需要写为:
assert ce.value.foo == 'blah'
assert not ce.value.bar