[英]Can pytest capture output from a doctest?
I'm running pytest
with --doctest-modules
and no other options.我正在使用
--doctest-modules
运行pytest
而没有其他选项。
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.我有一个失败的
doctest
测试,我正在尝试通过向底层代码添加print()
语句来调试问题。
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.对于我的常规(非
doctest
)测试,捕获输出正在工作并按预期显示,但是doctest
测试没有在我的pytest
输出中显示 stdout,即使我在那里发生了print()
语句。
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.我可以将我的
doctest
重写为非doctest
测试,以便让那些print()
语句流过,但这听起来非常迂回。
Is there any way to tell pytest
that I want it to capture output for doctest
s too?有什么方法可以告诉
pytest
我也希望它捕获doctest
的输出?
$ 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.将我的评论变成答案:最简单的方法是打印到 stderr,因为
doctest
只捕获 stdout 进行比较。 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 =====================================
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.