简体   繁体   English

如何使用 pytest 和 python 测试控制台打印?

[英]How to test a console print with pytest and python?

I would like to test the print of a function with unitest on python 2.7:我想在 python 2.7 上用 unitest 测试 function 的打印:

Example:例子:

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"

In the example I want to test that we have "Parsing..." in the console在示例中,我想测试我们在控制台中有“Parsing...”

here is my test:这是我的测试:

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

But then I don't know how to test what is written "Parsing..." in the console.但是后来我不知道如何测试控制台中写的“Parsing ...”。 I am blocked我被封锁了

I just want to test if we have the same message in the console as "Parsing..."我只是想测试一下我们在控制台中是否有与“Parsing...”相同的消息

You can use capsys from pytest.您可以使用capsys中的 capsys。

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

You could do something like this:你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM