我正在使用 Pytest 编写测试。我有一个这样的装置:
@pytest.yield_fixture(autouse=True, scope='session')
def manage_tests():
print("Do stuff...")
do_stuff()
yield
我在那里放置了一条打印语句,以便在运行测试时可以在控制台中看到它,以便更好地了解程序正在做什么。但我在控制台中没有看到该文本,我猜 pytest 吞下了它。有没有办法从固定装置打印?
Pytest 不会吞掉输出,只是默认情况下不显示。要在控制台中查看输出,请尝试使用
-s
选项运行测试,例如:
pytest -s <path_to_file>
在 pytest 3 中使用此夹具:
@pytest.fixture()
def tprint(request, capsys):
"""Fixture for printing info after test, not supressed by pytest stdout/stderr capture"""
lines = []
yield lines.append
with capsys.disabled():
for line in lines:
sys.stdout.write('\n{}'.format(line))
我可以看到打印语句。但有一些重要的事情需要注意:
scope=session
,所以这只在第一次测试时执行。