Testing warnings with doctest
Posted
by Eli Courtwright
on Stack Overflow
See other posts from Stack Overflow
or by Eli Courtwright
Published on 2010-03-10T16:24:50Z
Indexed on
2010/03/19
8:21 UTC
Read the original article
Hit count: 510
I'd like to use doctests to test the presence of certain warnings. For example, suppose I have the following module:
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)
If I run python -m doctest testdocs.py to run the doctest in my class and make sure that the warning is printed, I get:
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.
It looks like the warning is getting printed but not captured or noticed by doctest. I'm guessing that this is because warnings are printed to sys.stderr instead of sys.stdout. But this happens even when I say sys.stderr = sys.stdout at the end of my module.
So is there any way to use doctests to test for warnings? I can find no mention of this one way or the other in the documentation or in my Google searching.
© Stack Overflow or respective owner