emonigma
emonigma

Reputation: 4406

Show result of print function calls in doc-tests

I am debugging the failure of a doc-test. I debug with print() statements instead of emulators and breakpoints. Doc-tests seem to suppress the stdout of the functions under test.

Is there way to only perform the doctests, ignoring print function calls? mentions the opposite, how to suppress print function calls. The behavior seems to have changed in Python3.

One clumsy solution is to copy the body of the doc-test to main(), remove the leading angled brackets, debug, copy back, and iterate. It'd be easier to keep the function in the doc-test.

This command prints extended output from the doctest but not from the functions under test:

python3 -m doctest -v module.py 

How can I include the output of print function calls of the functions under test?

Update

Here is a minimal example of a doc-test.

import doctest

def sum(a, b):
    """
    >>> 2 == sum(1, 1)
    True
    >>> n = sum(1, 1)
    >>> 2 == n
    True
    """

    print("Hello world")
    return False  # anything to break the test


doctest.testmod(optionflags=doctest.ELLIPSIS)

The result is:

**********************************************************************
Failed example:
    2 == sum(1, 1)
Expected:
    True
Got:
    Hello world
    False
**********************************************************************
Failed example:
    n = sum(1, 1)
Expected nothing
Got:
    Hello world
**********************************************************************
Failed example:
    2 == n
Expected:
    True
Got:
    False
**********************************************************************

So the code works as expected, and the problem lies in writing the tests to fit the doctest framework of matching expected and actual print output. I usually assign the function call to a variable and test that variable, so the prints come not in the test failure but in the function call (which I normally catch with an ellipsis, even though I don't do it here). One solution is to hide print output for doc-tests and to turn it back on when I need to debug.

Upvotes: 3

Views: 1693

Answers (1)

Holloway
Holloway

Reputation: 7367

You can write debugging output to stderr instead of stdout.

import sys
# for debug statements
print('debugging stuff', file=sys.stderr)

Upvotes: 6

Related Questions