如何在python 2.x和3.x中使用doctest测试异常? [英] How to test exceptions with doctest in Python 2.x and 3.x?

查看:114
本文介绍了如何在python 2.x和3.x中使用doctest测试异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模块 spam 中定义了一个异常类 SpamException 。现在,我想测试一个函数 spam_function ,该函数将引发此异常。因此,我编写了以下doctest。

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

该测试在Python 2.x上成功,但是在Python 3.x上该测试失败。以下测试适用于Python 3.x。

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

此处的显着区别是在异常名称中包含了模块名称。那么如何编写适用于Python 2.x和3.x的doctest?

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?

推荐答案

我将打开 doctest.IGNORE_EXCEPTION_DETAIL 指令,例如:

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'

但是请注意, IGNORE_EXCEPTION_DETAIL 不适用于普通异常对象(无关联参数)。特别是,以下示例不适用于Python 3,因为在异常名称之后没有任何内容。

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

这篇关于如何在python 2.x和3.x中使用doctest测试异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆