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")
当你使用py.test进行测试时。可以使用“capsys”或“capfd”测试函数参数对STDOUT和STDIN运行断言
可以找到更多详细信息in the py.test docs
我看到两种方式:
在unittest期间重定向stdout:
使用记录器记录输出,并在测试中收听。
Python自己的测试套件可以做到这一点,我们使用两种主要技术:
重定向stdout(正如其他人建议的那样)。我们使用上下文管理器:
使用
subprocess
模块。当我们特别想测试对命令行参数的处理时,就使用这个。请参见http://hg.python.org/cpython/file/default/Lib/test/test_cmd_line_script.py以获取几个示例。相关问题 更多 >
编程相关推荐