有时我想在我的代码中插入一些打印语句,看看当我执行它时会打印出什么。我通常使用现有的pytest测试来“锻炼”它。但是当我运行这些时,我似乎无法看到任何标准输出(至少在我的IDE PyCharm中)。
是否有一种简单的方法可以在pytest运行期间查看标准输出?
有时我想在我的代码中插入一些打印语句,看看当我执行它时会打印出什么。我通常使用现有的pytest测试来“锻炼”它。但是当我运行这些时,我似乎无法看到任何标准输出(至少在我的IDE PyCharm中)。
是否有一种简单的方法可以在pytest运行期间查看标准输出?
当前回答
我建议使用-h命令。可以使用一些非常有趣的命令。 但是,对于这个特殊的情况:-s快捷方式——capture=no。就足够了
pytest <test_file.py> -s
其他回答
根据pytest文档,版本3的pytest可以在测试中临时禁用捕获:
def test_disabling_capturing(capsys):
print('this output is captured')
with capsys.disabled():
print('output not captured, going directly to sys.stdout')
print('this output is also captured')
-s开关禁用每个测试捕获(仅当测试失败时)。
-s等价于——capture=no。
capsys、capsysbinary、capfd和capfbinary fixture允许访问创建的stdout/stderr输出 在测试执行期间。下面是一个测试函数的例子,它执行一些与输出相关的检查:
def test_print_something_even_if_the_test_pass(self, capsys):
text_to_be_printed = "Print me when the test pass."
print(text_to_be_printed)
p_t = capsys.readouterr()
sys.stdout.write(p_t.out)
# the two rows above will print the text even if the test pass.
结果如下:
test_print_something_even_if_the_test_pass PASSED[100%]测试通过时打印我
pytest test_name.py -v -s
简单!
如果有人想从输出代码中运行测试:
if __name__ == '__main__':
pytest.main(['--capture=no'])