# How do you test that a Python function throws an exception?

PythonServer Side ProgrammingProgramming

We write a unittest that fails only if a function doesn't throw an expected exception.

We also test if a Python function throws an exception.

For example, see the sample code we paste into the Python shell to test Python's type-safety:

## Example

import unittest
class MyTestCase(unittest.TestCase):
with self.assertRaises(TypeError):
1 + '1'
import operator
unittest.main(exit=False)

Running the tests

## Output

And the terminal outputs the following −

..

----------------------------------------------------------------------

Ran 2 tests in 0.001s

OK

Test one uses assertRaises as a context manager, which ensures that the error is properly caught and cleaned up, while recorded.

We could also write it without the context manager, see test two. The first argument would be the error type you expect to raise, the second argument, the function you are testing, and the remaining args and keyword args will be passed to that function.

It's far more simple, and readable to just use the context manager.

We see that as we expect, attempting to add a 1 and a '1' result in a TypeError.

Published on 07-Dec-2017 17:36:57