前言
- 本篇来学习获取用例执行结果的Hooks函数–pytest_runtest_makereport
基本使用
import pytest
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
"""
这里item是测试用例,call是测试步骤,具体执行过程如下:
先执行when='setup' 返回setup 的执行结果
然后执行when='call' 返回call 的执行结果
最后执行when='teardown'返回teardown 的执行结果
"""
print('-' * 20)
out = yield
print('用例执行结果', out)
report = out.get_result()
print('测试报告:%s' % report)
print('步骤:%s' % report.when)
print('nodeid:%s' % report.nodeid)
print('description:%s' % str(item.function.__doc__))
print(('运行结果: %s' % report.outcome))
import os
def test_66():
"""这是测试用例描述-66"""
print('大家好,我是测试小白!')
if __name__ == '__main__':
os.system('pytest -s test_66.py')
- 查看运行结果

setup和teardown使用
@pytest.fixture(scope="session", autouse=True)
def fix_a():
print("setup 前置操作")
yield
print("teardown 后置操作")
- 运行test_66.py 查看结果

setup失败
@pytest.fixture(scope="session", autouse=True)
def fix_a():
print("setup 前置操作")
raise Exception('前置操作失败!')
yield
print("teardown 后置操作")
- 运行test_66.py ,查看结果为1error

call失败情况
- 恢复conftest.py代码,使setup 成功,修改test_66.py 文件代码,内容如下
import os
def test_66():
"""这是测试用例描述-66"""
print('大家好,我是测试小白!')
assert 1 != 1
if __name__ == '__main__':
os.system('pytest -s test_66.py')
- 运行test_66.py , 查看运行结果为1failed

teardown失败情况
@pytest.fixture(scope="session", autouse=True)
def fix_a():
print("setup 前置操作")
yield
print("teardown 后置操作")
raise Exception("teardown 失败了!")
- 恢复test_66.py代码并运行,查看结果为1passed,1error

只获取call的结果
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
print('-' * 20)
out = yield
print('用例执行结果', out)
report = out.get_result()
if report.when == 'call':
print('测试报告:%s' % report)
print('步骤:%s' % report.when)
print('nodeid:%s' % report.nodeid)
print('description:%s' % str(item.function.__doc__))
print(('运行结果: %s' % report.outcome))
- 运行test_66.py,查看结果如下
