我想运行文档测试并获取失败次数,但不打印任何输出。例如,我尝试过这个:
with open(os.devnull, 'w') as sys.stdout:
tests_failed, tests_run = doctest.testmod(some_module,
optionflags=doctest.ELLIPSIS)
但这对于测试运行器套件来说效果不佳,它需要
sys.stdout
写入 JSON 文件。
如何运行文档测试而不打印任何输出?
为了捕捉(从而保持沉默)
stdout
,我使用contextlib.redirect_stdout
:
import io
import contextlib
[...]
# in function running tests:
f = io.StringIO()
with contextlib.redirect_stdout(f):
# run code that outputs stuff to stdout
# stdout contents are now in f.get_value(),
# which you can use for further assertions