Testing Python Scripts

后端 未结 5 1550
小蘑菇
小蘑菇 2021-02-14 01:23

How do I test the STDOUT output of a Python script with a testing framework like doctest, unittest, nose, etc? For example, say running my script "todo.py --list" shou

5条回答
  •  不要未来只要你来
    2021-02-14 02:09

    when you use py.test for your testing. You can use the "capsys" or the "capfd" test function arguments to run asserts against STDOUT and STDIN

    def test_myoutput(capsys): # or use "capfd" for fd-level
        print ("hello")
        sys.stderr.write("world\n")
        out, err = capsys.readouterr()
        assert out == "hello\n"
        assert err == "world\n"
        print "next"
        out, err = capsys.readouterr()
        assert out == "next\n"
    

    More details can be found in the py.test docs

提交回复
热议问题