Note that there are some explanatory texts on larger screens.

plurals
  1. POTesting warnings with doctest
    text
    copied!<p>I'd like to use <a href="http://docs.python.org/library/doctest.html" rel="noreferrer">doctests</a> to test the presence of certain warnings. For example, suppose I have the following module:</p> <pre><code>from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; foo = Foo() testdocs.py:14: UserWarning: Boo! warn("Boo!", UserWarning) &gt;&gt;&gt; """ def __init__(self): warn("Boo!", UserWarning) </code></pre> <p>If I run <code>python -m doctest testdocs.py</code> to run the doctest in my class and make sure that the warning is printed, I get:</p> <pre><code>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. </code></pre> <p>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 <code>sys.stderr</code> instead of <code>sys.stdout</code>. But this happens even when I say <code>sys.stderr = sys.stdout</code> at the end of my module.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload