Testing functions that raise exceptions
Good Python includes docstrings inside every module, class, function, and method. One important element of a docstring is an example. This can include examples of common exceptions. There's one complicating factor, however, to including exceptions.
When an exception is raised, the traceback messages created by Python are not completely predictable. The message may include object ID values that are impossible to predict or module line numbers that may vary slightly depending on the context in which the test is executed. The matching rules doctest
uses to compare expected and actual results aren't appropriate when exceptions are involved.
Our testing frameworks provide ways to be sure the right exceptions are raised by a test case. This will involve using a special doctest
provision for identifying the traceback messages exceptions produce.
Getting ready
We'll look at a small function definition as well as a class...