Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pytest.raises to inspect custom exception attributes

class CustomException(ValueError):
  def __init__(self, foo, bar):
    self.foo = foo
    self.bar = bar

I have a class with an exception like the above. foo and bar are used by the function raising the error to supply some extra information about the exception to the calling class.

I'm trying to test this behavior like this:

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

However, ce is an instance of ExceptionInfo that py.test gives me, and not an instance of CustomException. Is there any way to retain and inspect the original exception that was raised?

like image 278
Antrikshy Avatar asked Sep 05 '18 22:09

Antrikshy


Video Answer


1 Answers

The actual exception object is available as ce.value, so your asserts need to be written as:

assert ce.value.foo == 'blah'
assert not ce.value.bar
like image 199
jwodder Avatar answered Oct 02 '22 19:10

jwodder