默认情况下,py.test
会捕获标准输出的结果,以便控制打印输出的方式。如果不这样做,它将输出大量文本,但没有上下文说明是哪个测试打印了这些文本。
然而,如果一个测试失败,它将在生成的报告中包括一个部分,显示在该特定测试中打印到标准输出的内容。
例如:
def test_good():
for i in range(1000):
print(i)
def test_bad():
print('this should fail!')
assert False
以下输出结果:
>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items
tmp.py .F
=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________
def test_bad():
print('this should fail!')
> assert False
E assert False
tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================
注意 Captured stdout
部分。
如果您想要在执行时查看print
语句,可以向py.test
传递-s
标志。但是,请注意有时这可能很难解析。
>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items
tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F
=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________
def test_bad():
print('this should fail!')
> assert False
E assert False
tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================
sys.stdout.write("Test")
会发生什么?sys.__stdout__.write("Test")
呢?后者应该总是写入系统定义的stdout,也就是控制台。如果这两个命令执行不同的操作,则stdout已经被更改;如果它们执行相同的操作,则问题在于其他方面。 - TheSoundDefense