Various behaviors of doctest

Peter Otten __peter__ at web.de
Mon Feb 28 12:27:47 CET 2011


Gnarlodious wrote:

> Yeah, I just spent about 2 hours trying everything I could think of...
> without success. Including your suggestions. Guess I'll have to skip
> it. But thanks for the ideas.
> 
> -- Gnarlie

Are you using Python 2.x? Then you cannot redefine print. Instead you have 
to redirect stdout. The following example should run as a cgi script:

#!/usr/bin/env python
import cgi
import sys
from cStringIO import StringIO

def f():
    """
    >>> 1 + 1
    2
    >>> 2 + 2
    22
    >>> "<"
    '<'
    """

if __name__ == "__main__":
    print ("Content-type: text/html\r\n\r\n"
           "<html><body style='background-color:#f0f0f0'>"
           "<h1 style='color: navy;'>There goes:</h1>")

    outstream = StringIO()
    import doctest, sys

    from doctest import DocTestRunner
    class DTR(DocTestRunner):
        def run(self, test, compileflags=None, out=None, clear_globs=True):
            DocTestRunner.run(self, test, compileflags, outstream.write, 
clear_globs)
        def summarize(self):
            saved = sys.stdout
            sys.stdout = outstream
            DocTestRunner.summarize(self)
            sys.stdout = saved

    doctest.DocTestRunner = DTR
    doctest.testmod(verbose=True)
    text = outstream.getvalue()
    
    for line in text.splitlines():
        spaces = len(line) - len(line.lstrip())
        line = line.strip()
        if "*****" in line:
            print "<hr/>"
        else:
            print "<div style='color: %s; margin-left:%sem;'>%s</div>" % (
                "blue" if spaces else "black", spaces, cgi.escape(line))
    print "</body></html>"




More information about the Python-list mailing list