Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 280
Helmut Grohne Avatar asked Jul 16 '13 08:07

Helmut Grohne


1 Answers

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
like image 96
jalanb Avatar answered Oct 16 '22 08:10

jalanb