我想使用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 来测试警告吗?我在文档或我的谷歌搜索中找不到任何一种方式或其他方式。