如何在Python中用doctest检查异常是否抛出?
有没有办法写一个 doctest
单元测试,来检查是否抛出了异常?
比如说,如果我有一个函数 foo(x)
,它应该在 x < 0
的时候抛出异常,那我该怎么为这个函数写 doctest
呢?
3 个回答
5
>>> import math
>>> math.log(-2)
Traceback (most recent call last):
...
ValueError: math domain error
省略号标志 # doctest: +ELLIPSIS 不是在 Traceback doctest 中使用 ... 的必要条件。
15
>>> scope # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NameError: name 'scope' is not defined
我不知道之前的回答为什么没有提到 IGNORE_EXCEPTION_DETAIL。我需要这个才能让它正常工作。Python 版本:3.7.3。
117
是的,你可以这样做。doctest模块的文档和维基百科上有一个示例可以参考。
>>> x
Traceback (most recent call last):
...
NameError: name 'x' is not defined