简体   繁体   中英

Can pytest capture output from a doctest?

I'm running pytest with --doctest-modules and no other options.

I've got a doctest test that's failing, and I'm trying to debug the issue by adding print() statements to the underlying code.

Capturing output is working and displaying as expected for my regular (non- doctest ) tests, but the doctest tests aren't showing stdout in my pytest output, even though I've got print() statements happening in there.

I could re-write my doctest as a non- doctest test in order to get those print() statements to flow through, but that sounds like an awfully roundabout thing to do.

Is there any way to tell pytest that I want it to capture output for doctest s too?

$ python --version
Python 3.7.2
$ pytest --version
This is pytest version 3.10.1, imported from /home/gene/.pythonz/pythons/CPython-3.7.2/lib/python3.7/site-packages/pytest.py
setuptools registered plugins:
  pytest-xdist-1.26.1 at /home/gene/.pythonz/pythons/CPython-3.7.2/lib/python3.7/site-packages/xdist/plugin.py
  pytest-xdist-1.26.1 at /home/gene/.pythonz/pythons/CPython-3.7.2/lib/python3.7/site-packages/xdist/looponfail.py
  pytest-pythonpath-0.7.3 at /home/gene/.pythonz/pythons/CPython-3.7.2/lib/python3.7/site-packages/pytest_pythonpath.py
  pytest-mock-1.10.0 at /home/gene/.pythonz/pythons/CPython-3.7.2/lib/python3.7/site-packages/pytest_mock.py
  pytest-forked-1.0.1 at /home/gene/.pythonz/pythons/CPython-3.7.2/lib/python3.7/site-packages/pytest_forked/__init__.py
  hypothesis-4.4.1 at /home/gene/.pythonz/pythons/CPython-3.7.2/lib/python3.7/site-packages/hypothesis/extra/pytestplugin.py
  flaky-3.5.3 at /home/gene/.pythonz/pythons/CPython-3.7.2/lib/python3.7/site-packages/flaky/flaky_pytest_plugin.py

Turning my comment into an answer: the easiest way is to print to stderr as doctest only captures stdout for comparison. Example:

import sys


def greet(who):
    """Greet someone.

    >>> greet('world')
    'Hello world'

    >>> greet('fizz')
    'Hello fizz'

    >>> greet('buzz')
    'Hello buzz'
    """

    print('input:', who, file=sys.stderr)
    return f'Hello {who}'

Running the tests:

$ pytest --doctest-modules -sv
======================================= test session starts ========================================
...
collected 1 item                                                                                   

spam.py::spam.greet input: world
input: fizz
input: buzz
PASSED

===================================== 1 passed in 0.03 seconds =====================================

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM