Exceptions#

Exception assertion helpers for verifying raised exceptions.

Provides the raises class which can verify that a callable raises an exception of the expected type using either Python 3.11+ generic syntax or an explicit expect keyword argument.

Example#

from punit import exceptions

class MyException(Exception):
    pass

def raises_exception():
    raise MyException()

assert exceptions.raises[MyException](raises_exception)
assert exceptions.raises[MyException](raises_exception, exact=True)
class raises(action, *, exact=False, expect=None)#

Bases: Generic[TError]

Assert that a callable raises an expected exception.

Use raises to verify that a function, method, or lambda expression raises an exception of the expected type. Two syntaxes are supported:

  • Python >=3.11 generic syntax: raises[MyException](action)

  • Explicit expect argument (for <=3.11): raises(action, expect=MyException)

The exact parameter controls whether the raised exception must be an exact type match (not a subclass) of the expected type.

Example#

class MyException(Exception):
    pass

def raises_exception():
    raise MyException()

assert raises[MyException](raises_exception)
assert not raises[ValueError](raises_exception)
assert raises[MyException](raises_exception, exact=True)