pytest capsys: checking output AND getting it reported?

前端 未结 3 2107
盖世英雄少女心
盖世英雄少女心 2021-02-13 03:04

Python 3.4.1, pytest 2.6.2.

When a test fails, pytest will routinely report what was printed to stdout by the test. For instance this code:

         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 03:42

    You're seeing the correct behaviour, when using capsys.readouterr() you're consuming the captured output. Hence any output to stdout and stderr will no longer show up in the test report. But any new output which you create after this and do not consume will still be reported, so you can get the full output back in the report by simply writing it to the output streams once more:

    def test_result_and_stdout(capsys):
        result = method_under_test()
        out, err = capsys.readouterr()
        sys.stdout.write(out)
        sys.stderr.write(err)
        assert out.startswith("Hello")
        assert result == 42
    

提交回复
热议问题