这适用于最新的pytest:
您只需使用--capture=sys选项运行pytest,并依赖于raises()上下文之外的断言(由于某些原因,此位非常重要!)
示例:#!/usr/bin/env python
from __future__ import print_function
import pytest
def f(code=0):
print("Foo")
raise SystemExit(code)
def test_f(capsys):
with pytest.raises(SystemExit):
f()
out, err = capsys.readouterr()
assert out == "Foo\n"
print(out, err)
演示:$ py.test -v --capture=sys test_foo.py
======================================= test session starts ===============================&