自动化测试用例的调试信息非常有用,可以让我们知道现在的运行情况到,执行到哪步以及相应的出错信息等,可以在pytest里面,有时并不会输出所有信息,比如默认情况下pass的测试用例是没有print输出的。本文将介绍如何在pytest里面实时显示所有的log信息。
1. 用print输出log信息
slowTest_print.py
import time
def test_1():
print 'test_1'
time.sleep(1)
print 'after 1 sec'
time.sleep(1)
print 'after 2 sec'
time.sleep(1)
print 'after 3 sec'
assert 1, 'should pass'
def test_2():
print 'in test_2'
time.sleep(1)
print 'after 1 sec'
time.sleep(1)
print 'after 2 sec'
time.sleep(1)
print 'after 3 sec'
assert 0, 'failing for demo purposes'
运行上述程序,pytest会capture所有的输出,保存直到所有的测试用例都执行结束,并且只输出那些失败的测试用例的信息,对于成功的测试用例,没有print的信息显示。
从下面的运行结果,如果需要查看test_1()的运行情况,没有log信息可看,print没有显示。
C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v slowTest_print.py
============================= test session starts =============================
platform win32 -- Python 2.7.13, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- C:\Python27\python.exe
cachedir: .cache
metadata: {'Python': '2.7.13', 'Platform': 'Windows-7-6.1.7601-SP1', 'Packages': {'py': '1.4.32', 'pytest': '3.0.6', 'pluggy': '0.4.0'}, 'JAVA_HOME': 'C:\\Program Files (x86)\\Java\\jd
k1.7.0_01', 'Plugins': {'html': '1.14.2', 'metadata': '1.3.0'}}
rootdir: C:\Users\yatyang\PycharmProjects\pytest_example, inifile:
plugins: metadata-1.3.0, html-1.14.2
collected 2 items
slowTest_print.py::test_1 PASSED
slowTest_print.py::test_2 FAILED
================================== FAILURES ===================================
___________________________________ test_2 ____________________________________
def test_2():
print 'in test_2'
time.sleep(1)
print 'after 1 sec'
time.sleep(1)
print 'after 2 sec'
time.sleep(1)
print 'after 3 sec'
> assert 0, 'failing for demo purposes'
E AssertionError: failing for demo purposes
E assert 0
slowTest_print.py:22: AssertionError