【问题标题】:Can pytest capture output from a doctest?pytest 可以从 doctest 捕获输出吗?
【发布时间】:2019-07-09 16:54:23
【问题描述】:

我正在运行 pytest 和 --doctest-modules 并且没有其他选项。

我有一个失败的doctest 测试,我正在尝试通过将print() 语句添加到底层代码来调试问题。

对于我的常规(非doctest)测试,捕获输出正常工作和显示,但doctest 测试没有在我的pytest 输出中显示标准输出,即使我有print()那里发生的陈述。

我可以将我的doctest 重写为非doctest 测试,以使那些print() 语句能够通过,但这听起来像是一个非常迂回的事情。

有什么方法可以告诉pytest 我也希望它捕获doctests 的输出?

$ 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

【问题讨论】:

  • 最简单的方法是打印到标准错误,因为doctest 只捕获标准输出进行比较。 print('debug stuff', file=sys.stderr) 等。当然,您仍然应该运行 pytest -s 来捕获输出。

标签: python pytest doctest


【解决方案1】:

将我的评论变成答案:最简单的方法是打印到 stderr,因为 doctest 仅捕获标准输出以进行比较。示例:

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}'

运行测试:

$ 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 =====================================

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多