unittest.TestCase.assertRaises()

assertRaises(exception, callable, *args, **kwds) assertRaises(exception, msg=None)

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.

If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function:

with self.assertRaises(SomeException):
    do_something()

When used as a context manager, assertRaises() accepts the additional keyword argument msg.

The context manager will store the caught exception object in its exception attribute. This can be useful if the intention is to perform additional checks on the exception raised:

with self.assertRaises(SomeException) as cm:
    do_something()

the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)

Changed in version 3.1: Added the ability to use assertRaises() as a context manager.

Changed in version 3.2: Added the exception attribute.

Changed in version 3.3: Added the msg keyword argument when used as a context manager.

doc_python
2016-10-07 17:46:23
Comments
Leave a Comment

Please login to continue.