【问题标题】:Python pytest: capturing stdout always failsPython pytest:捕获标准输出总是失败
【发布时间】:2017-09-13 15:50:46
【问题描述】:

我正在尝试在 pytest 中捕获 stdout / print 语句的输出(Python 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 的结果:

========================================================= 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 =======================================================

为什么没有捕获?

【问题讨论】:

    标签: python unit-testing tdd pytest


    【解决方案1】:

    您需要在打印后致电readouterr

    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
    

    【讨论】:

    • 天哪。我用头敲了三个小时。 >,
    • 非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多