Python pytest:捕获标准输出总是失败 [英] Python pytest: capturing stdout always fails

查看:65
本文介绍了Python pytest:捕获标准输出总是失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 pytest 中的 stdout/print 语句捕获输出(Python 3.6 版).

I'm trying to capture output from stdout / print statements in pytest (Python version 3.6).

这总是失败:

message = 'The meaning of life is not actually 42\n'

def print_greeting():
    """print 42 to stdout"""

    # write to stdout
    sys.stdout.write(message)           # this fails

    # print to stdout
    print('Message again: ', message)   # this fails too


def test_printgreeting(capsys):
    """assert '42' was printed to stdout"""

    # capture stdout / stderr
    out, err = capsys.readouterr()
    print_greeting()

    # 42 should be in stdout from sys.stdout.write
    assert '42' in out

pytest 的结果:

Results from pytest:

========================================================= test session starts ==========================================================

collected 1 item

test.py
The meaning of life is not actually 42
F

=============================================================== FAILURES ===============================================================
__________________________________________________________ test_printgreeting __________________________________________________________
test.py:42: in test_printgreeting
    assert '42' in out
E   AssertionError: assert '42' in ''
======================================================= 1 failed in 0.03 seconds =======================================================

为什么没有捕获?

推荐答案

您需要在打印后调用 readouterr :

You need to call readouterr after you print:

def test_printgreeting(capsys):
    """assert '42' was printed to stdout"""

    # capture stdout / stderr
    print_greeting()
    out, err = capsys.readouterr()

    # 42 should be in stdout from sys.stdout.write
    assert '42' in out

这篇关于Python pytest:捕获标准输出总是失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆