【发布时间】:2010-03-10 16:24:50
【问题描述】:
我想使用doctests 来测试某些警告是否存在。例如,假设我有以下模块:
from warnings import warn
class Foo(object):
"""
Instantiating Foo always gives a warning:
>>> foo = Foo()
testdocs.py:14: UserWarning: Boo!
warn("Boo!", UserWarning)
>>>
"""
def __init__(self):
warn("Boo!", UserWarning)
如果我运行 python -m doctest testdocs.py 在我的班级中运行 doctest 并确保打印警告,我会得到:
testdocs.py:14: UserWarning: Boo!
warn("Boo!", UserWarning)
**********************************************************************
File "testdocs.py", line 7, in testdocs.Foo
Failed example:
foo = Foo()
Expected:
testdocs.py:14: UserWarning: Boo!
warn("Boo!", UserWarning)
Got nothing
**********************************************************************
1 items had failures:
1 of 1 in testdocs.Foo
***Test Failed*** 1 failures.
看起来警告正在打印,但没有被 doctest 捕获或注意到。我猜这是因为警告打印到sys.stderr 而不是sys.stdout。但即使我在模块末尾说sys.stderr = sys.stdout,也会发生这种情况。
那么有什么方法可以使用 doctests 来测试警告吗?我在文档或我的 Google 搜索中找不到任何提及这一点的方法。
【问题讨论】: