pytest capsys: checking output AND getting it reported?

前端 未结 3 2123
盖世英雄少女心
盖世英雄少女心 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条回答
  • 2021-02-13 03:37

    Asides using "startswith".You can also use the "in" keyword, for example:

        assert "Hello" in output
    

    This is great if you have a huge amount of data being passed to stdout, you can use "in" to check for different lines in your stdout.

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

    You can also assert what's passed into stderr instead of stdout by using:

        assert "What you are expecting" in err
    

    Also note that line:

        out, err = capsys.readouterr()
    

    creates a snapshot of the output to both stdout and stderr so far so you can assert what you are expecting for that test.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-13 03:53

    From the documentation the behavior seems correct: only after the test function (test_result_and_stdout) finishes the output streams will be restored, not after each readouterr call. I don't think that currently capsys supports also redirecting to the original streams besides capturing them, which seems to be what you want.

    I would suggest to create an issue in the official repository and see what people have to say.

    0 讨论(0)
提交回复
热议问题