pytest capsys: checking output AND getting it reported?

前端 未结 3 2105
盖世英雄少女心
盖世英雄少女心 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.

提交回复
热议问题