有时我想在我的代码中插入一些打印语句,看看当我执行它时会打印出什么。我通常使用现有的pytest测试来“锻炼”它。但是当我运行这些时,我似乎无法看到任何标准输出(至少在我的IDE PyCharm中)。

是否有一种简单的方法可以在pytest运行期间查看标准输出?


当前回答

根据pytest文档,版本3的pytest可以在测试中临时禁用捕获:

def test_disabling_capturing(capsys):
    print('this output is captured')
    with capsys.disabled():
        print('output not captured, going directly to sys.stdout')
    print('this output is also captured')

其他回答

pytest test_name.py -v -s

简单!

根据pytest文档,版本3的pytest可以在测试中临时禁用捕获:

def test_disabling_capturing(capsys):
    print('this output is captured')
    with capsys.disabled():
        print('output not captured, going directly to sys.stdout')
    print('this output is also captured')

capsys、capsysbinary、capfd和capfbinary fixture允许访问创建的stdout/stderr输出 在测试执行期间。下面是一个测试函数的例子,它执行一些与输出相关的检查:

def test_print_something_even_if_the_test_pass(self, capsys):
    text_to_be_printed = "Print me when the test pass."
    print(text_to_be_printed)
    p_t = capsys.readouterr()
    sys.stdout.write(p_t.out)
    # the two rows above will print the text even if the test pass.

结果如下:

test_print_something_even_if_the_test_pass PASSED[100%]测试通过时打印我

如果使用日志记录,除了通用标准输出的-s外,还需要指定打开日志记录输出。基于pytest测试中的日志记录,我使用:

pytest——log-cli-level=DEBUG -s my_directory/

如果有人想从输出代码中运行测试:

if __name__ == '__main__':
    pytest.main(['--capture=no'])