调试器输出未显示

时间:2016-02-25 15:44:47

标签: python ipython pytest

我在包含the capfd 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 ==========================

有没有办法让pytest在涉及ipdb时停止捕获stdout / stderr?

1 个答案:

答案 0 :(得分:0)

作为一种解决方法,我可以使用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"