未显示调试器输出

2024-07-03 06:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在包含the ^{} fixture的测试中运行ipdb时遇到问题。测试代码的简化版本如下:

import pytest
import sys

def test_foo(capfd):
    def foo():
        print("Hello World!")
    foo()
    out, err = capfd.readouterr()
    import ipdb
    ipdb.set_trace()
    assert out == "Hello World!\n"

当我运行py.test -s test/test_capfb.py时,调试器的所有输出都被捕获,我什么也看不到。我仍然可以向调试器发出命令(例如下面输出中的c),但在整个进程完成运行之前,不会得到任何输出。输出示例如下:

; py.test -s tests/test_capfb.py
============================= test session starts ==============================
platform linux2 -- Python 2.7.5, pytest-2.8.7, py-1.4.31, pluggy-0.3.1
rootdir: /home/usr/repos/junk, inifile: setup.cfg
plugins: bdd-2.16.0, colordots-0.1, cov-2.2.1, html-1.7, pep8-1.0.6, xdist-1.14, catchlog-1.2.2
collected 1 items
tests/test_capfb.py 
c  <---- I typed this!
--Return--
None
> /home/usr/repos/junk/tests/test_capfb.py(12)test_foo()
     11     import ipdb
---> 12     ipdb.set_trace()
     13
ipdb> .
========================== 1 passed in 228.90 seconds ==========================

当涉及到ipdb时,有没有办法告诉pytest停止捕获stdout/stderr?你知道吗


Tags: pytestimporthelloworldfoopytestdef
1条回答
网友
1楼 · 发布于 2024-07-03 06:41:26

作为解决方法,我可以使用iocapture来捕获输出,如下所示:

import pytest
import sys
import iocapture

def test_foo():
    def foo():
        print("Hello World!")
    out = None
    with iocapture.capture() as captured:
        foo()
        out = captured.stdout
    import ipdb
    ipdb.set_trace()
    assert out == "Hello World!\n"

相关问题 更多 >