使用pytest.raises检查自定义异常属性

问题描述 投票:1回答:1
class CustomException(ValueError):
  def __init__(self, foo, bar):
    self.foo = foo
    self.bar = bar

我有一个类,如上所述的例外。引发错误的函数使用foobar来为调用类提供有关异常的一些额外信息。

我试图像这样测试这种行为:

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的一个例子。有没有办法保留和检查引发的原始异常?

python unit-testing exception pytest
1个回答
2
投票

实际的异常对象可用作ce.value,因此您的断言需要写为:

assert ce.value.foo == 'blah'
assert not ce.value.bar
© www.soinside.com 2019 - 2024. All rights reserved.