Hel*_*hne 13 python doctest exception python-2.x python-3.x
我SpamException在模块中定义了一个异常类spam.现在我想测试一个spam_function引发此异常的函数.所以我写了下面的doctest.
>>> spam_function()
Traceback (most recent call last):
....
SpamException
Run Code Online (Sandbox Code Playgroud)
测试在Python 2.x上成功,但在Python 3.x上测试失败.以下测试适用于Python 3.x.
>>> spam_function()
Traceback (most recent call last):
....
spam.SpamException
Run Code Online (Sandbox Code Playgroud)
这里的显着区别是在异常名称中包含模块名称.那么如何编写适用于Python 2.x和3.x的doctest?
我会打开doctest.IGNORE_EXCEPTION_DETAIL指令,像这样:
>>> spam_function() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last)
...
SpamException: 'lovely spam'
Run Code Online (Sandbox Code Playgroud)
但请注意,IGNORE_EXCEPTION_DETAIL这对普通的异常对象(没有关联的参数)不起作用.特别是,以下示例不能移植到Python 3,因为在异常名称后面没有任何内容:
>>> spam_function() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last)
...
SpamException
Run Code Online (Sandbox Code Playgroud)