测试Python脚本

2024-04-19 05:52:29 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

当你使用py.test进行测试时。可以使用“capsys”或“capfd”测试函数参数对STDOUT和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"

可以找到更多详细信息in the py.test docs

我看到两种方式:

  1. 在unittest期间重定向stdout:

    class YourTest(TestCase):
        def setUp(self):
            self.output = StringIO()
            self.saved_stdout = sys.stdout
            sys.stdout = self.output
    
        def tearDown(self):
            self.output.close()
            sys.stdout = self.saved_stdout
    
        def testYourScript(self):
            yourscriptmodule.main()
            assert self.output.getvalue() == "My expected ouput"
    
  2. 使用记录器记录输出,并在测试中收听。

Python自己的测试套件可以做到这一点,我们使用两种主要技术:

  1. 重定向stdout(正如其他人建议的那样)。我们使用上下文管理器:

    import io
    import sys
    import contextlib
    
    @contextlib.contextmanager
    def captured_output(stream_name):
        """Run the 'with' statement body using a StringIO object in place of a
           specific attribute on the sys module.
           Example use (with 'stream_name=stdout'):
    
           with captured_stdout() as s:
               print("hello")
               assert s.getvalue() == "hello"
        """
        orig_stdout = getattr(sys, stream_name)
        setattr(sys, stream_name, io.StringIO())
        try:
            yield getattr(sys, stream_name)
        finally:
            setattr(sys, stream_name, orig_stdout)
    
    def captured_stdout():
        return captured_output("stdout")
    
    def captured_stderr():
        return captured_output("stderr")
    
    def captured_stdin():
        return captured_output("stdin")
    
  2. 使用subprocess模块。当我们特别想测试对命令行参数的处理时,就使用这个。请参见http://hg.python.org/cpython/file/default/Lib/test/test_cmd_line_script.py以获取几个示例。

相关问题 更多 >