PyDocs

Nav

Development Tools

TestCase.assertRaises

  • TestCase.assertRaises(exception, callable, *args, **kwds)
  • TestCase.assertRaises(exception, *, msg=None)
Fail unless an exception of class expected_exception is raised
by the callable when invoked with specified positional and
keyword arguments. If a different type of exception is
raised, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.

If called with the callable and arguments omitted, will return a
context object used like this::

     with self.assertRaises(SomeException):
         do_something()

An optional keyword argument 'msg' can be provided when assertRaises
is used as a context object.

The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::

    with self.assertRaises(SomeException) as cm:
        do_something()
    the_exception = cm.exception
    self.assertEqual(the_exception.error_code, 3)
Changed in 3.1, 3.2, 3.3
  • 3.1: Added the ability to use assertRaises() as a context manager.
  • 3.2: Added the exception attribute.
  • 3.3: Added the msg keyword argument when used as a context manager.
0 Examples
No examples for unittest/TestCase.assertRaises.
See Also
No see-alsos for unittest/TestCase.assertRaises
0 Notes
No notes for TestCase.assertRaises