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

Ant*_*shy 3 python unit-testing exception pytest

class CustomException(ValueError):
  def __init__(self, foo, bar):
    self.foo = foo
    self.bar = bar
Run Code Online (Sandbox Code Playgroud)

我有一个像上面这样的例外的类。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
Run Code Online (Sandbox Code Playgroud)

但是,ceExceptionInfopy.test 给我的一个实例,而不是CustomException. 有没有办法保留和检查引发的原始异常?

jwo*_*der 5

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

assert ce.value.foo == 'blah'
assert not ce.value.bar
Run Code Online (Sandbox Code Playgroud)