Search code examples
pythonexceptionpython-3.xpython-2.xdoctest

How to test exceptions with doctest in Python 2.x and 3.x?


I defined an exception class SpamException in a module spam. Now I want to test a function spam_function, that raises this exception. So I wrote the following doctest.

>>> spam_function()
Traceback (most recent call last):
    ....
SpamException

The test succeeds on Python 2.x, but on Python 3.x the test fails. The following test works on Python 3.x.

>>> spam_function()
Traceback (most recent call last):
    ....
spam.SpamException

The notable difference here is the inclusion of the module name in the exception name. So how can I write a doctest that works on both Python 2.x and 3.x?


Solution

  • I would turn on the doctest.IGNORE_EXCEPTION_DETAIL directive, like this:

    >>> spam_function() # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last)
        ...
    SpamException: 'lovely spam'
    

    But note that IGNORE_EXCEPTION_DETAIL doesn't work for plain exception objects (with no associated arguments). In particular, the following example isn't portable to Python 3, because there's nothing following the exception name:

    >>> spam_function() # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last)
        ...
    SpamException