【问题标题】:How to test a console print with pytest and python?如何使用 pytest 和 python 测试控制台打印?
【发布时间】:2025-12-29 22:25:12
【问题描述】:

我想在 python 2.7 上使用 unitest 测试函数的打印:

例子:

def load_parse_xml(data_file):
if os.path.isfile(data_file):
    print "Parsing..."
    data_parse = ET.ElementTree(file=data_file)
    return data_parse.getroot()
else:
    print data_file + " --> File not exist"

在示例中,我想测试我们在控制台中有“Parsing ...”

这是我的测试:

    def test_load_parse_xml(self):
    data_file = os.getcwd() + "/xml_tests/xmltest.xml"
    load_parse_xml(data_file)
    .......

但是我不知道如何测试控制台中写的“Parsing ...”。我被屏蔽了!

我只是想测试一下控制台中是否有与“Parsing ...”相同的消息

我是 python 的初学者和 unitest。

比你。

【问题讨论】:

标签: python-2.7 unit-testing pytest


【解决方案1】:

您可以使用 pytest 中的capsys

另请参阅:https://docs.pytest.org/en/6.2.x/capture.html#accessing-captured-output-from-a-test-function

你可以这样做:

    def test_test(capsys):
        print("Your print out from load_parse_xml")
        captured = capsys.readouterr()
        assert "Your print out from load_parse_xml" in captured.out

【讨论】:

    最近更新 更多