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

一笑奈何 提交于 2019-12-08 15:00:34

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/17671147/how-to-test-exceptions-with-doctest-in-python-2-x-and-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!