all Python 3unittestfunction
unittest.TestCase.assertRaises()
checks
Assert that code raises the expected exception: as a context manager (with) it checks a block, or pass a callable to check a single call.
Syntax
with self.assertRaises(ExcType): ...
self.assertRaises(ExcType, callable, *args)
In the callable form the usual slip is passing the result of the call instead of the function itself: it runs before assertRaises ever sees it, the exception escapes and the test simply errors out — hand over the function and its arguments separately. The assertion also accepts subclasses, so assertRaises(Exception) passes on almost any breakage; name the specific class, and to inspect the message use the with ... as cm form and its exception attribute, or assertRaisesRegex.
Examples
import unittest
class Tests(unittest.TestCase):
def test_raises(self):
with self.assertRaises(ValueError):
int('abc')
def test_raises_call(self):
self.assertRaises(ZeroDivisionError, lambda: 1 / 0)
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy