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

I defined the SpamException class in the spam module. Now I want to test the spam_function function that raises this exception. Therefore, I wrote the following doctrine.

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

The test succeeds in Python 2.x, but in Python 3.x the test failed. The following test runs on Python 3.x.

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

A 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?

+6
source share
1 answer

I would include the doctest.IGNORE_EXCEPTION_DETAIL directive, for example:

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

But IGNORE_EXCEPTION_DETAIL that IGNORE_EXCEPTION_DETAIL does not work for simple exception objects (without related arguments). In particular, the following example does not migrate to Python 3 because nothing follows the name of the exception:

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

Source: https://habr.com/ru/post/949531/


All Articles