pytest文档78 - 钩子函数pytest_runtest_makereport获取用例执行报错内容和print内容
2023-03-20 15:00:03 时间
前言
pytest在执行用例的时候,当用例报错的时候,如何获取到报错的完整内容呢? 当用例有print()打印的时候,如何获取到打印的内容?
钩子函数pytest_runtest_makereport
测试用例如下,参数化第一个用例成功,第二个失败
import pytest
import time
@pytest.fixture()
def login():
print("login first----------")
@pytest.mark.parametrize(
"user, password",
[
["test1", "123456"],
["test2", "123456"],
]
)
def test_a(login, user, password):
"""用例描述:aaaaaa"""
time.sleep(2)
print("---------打印的内容-------")
print('传入参数 user->{}, password->{}'.format(user, password))
assert user == "test1"
使用钩子函数pytest_runtest_makereport 可以获取用例执行过程中生成的报告
import pytest
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
out = yield # 钩子函数的调用结果
res = out.get_result() # 获取用例执行结果
if res.when == "call": # 只获取call用例失败时的信息
print("item(我们说的用例case):{}".format(item))
print("description 用例描述:{}".format(item.function.__doc__))
print("exception异常:{}".format(call.excinfo))
print("exception详细日志:{}".format(res.longrepr))
print("outcome测试结果:{}".format(res.outcome))
print("duration用例耗时:{}".format(res.duration))
print(res.__dict__)
用例运行成功的日志
test_b.py item(我们说的用例case):<Function test_a[test1-123456]>
description 用例描述:用例描述:aaaaaa
exception异常:None
exception详细日志:None
outcome测试结果:passed
duration用例耗时:2.0006444454193115
{'nodeid': 'test_b.py::test_a[test1-123456]',
'location': ('test_b.py', 8, 'test_a[test1-123456]'),
'keywords': {'test1-123456': 1, 'parametrize': 1, 'test_b.py': 1, 'test_a[test1-123456]': 1, 'myweb': 1, 'pytestmark': 1},
'outcome': 'passed',
'longrepr': None,
'when': 'call',
'user_properties': [],
'sections': [('Captured stdout setup', 'login first----------
'), ('Captured stdout call', '---------打印的内容-------
传入参数 user->test1, password->123456
')],
'duration': 2.0006444454193115,
'extra': []}
用例运行失败的日志
item(我们说的用例case):<Function test_a[test2-123456]>
description 用例描述:用例描述:aaaaaa
exception异常:<ExceptionInfo AssertionError("assert 'test2' == 'test1'
- test1
? ^
+ test2
? ^",) tblen=1>
exception详细日志:login = None, user = 'test2', password = '123456'
@pytest.mark.parametrize(
"user, password",
[
["test1", "123456"],
["test2", "123456"],
]
)
def test_a(login, user, password):
"""用例描述:aaaaaa"""
time.sleep(2)
print("---------打印的内容-------")
print('传入参数 user->{}, password->{}'.format(user, password))
> assert user == "test1"
E AssertionError: assert 'test2' == 'test1'
E - test1
E ? ^
E + test2
E ? ^
test_b.py:21: AssertionError
outcome测试结果:failed
duration用例耗时:2.003612995147705
{'nodeid': 'test_b.py::test_a[test2-123456]',
'location': ('test_b.py', 8, 'test_a[test2-123456]'),
'keywords': {'parametrize': 1, 'test2-123456': 1, 'test_a[test2-123456]': 1, 'test_b.py': 1, 'myweb': 1, 'pytestmark': 1},
'outcome': 'failed',
'longrepr': ExceptionChainRepr(chain=[(ReprTraceback(reprentries=[ReprEntry(lines=[' @pytest.mark.parametrize(', ' "user, password",', ' [', ' ["test1", "123456"],', ' ["test2", "123456"],', ' ]', ' )', ' def test_a(login, user, password):', ' """用例描述:aaaaaa"""', ' time.sleep(2)', ' print("---------打印的内容-------")', " print('传入参数 user->{}, password->{}'.format(user, password))", '> assert user == "test1"', "E AssertionError: assert 'test2' == 'test1'", 'E - test1', 'E ? ^', 'E + test2', 'E ? ^'], reprfuncargs=ReprFuncArgs(args=[('login', 'None'), ('user', "'test2'"), ('password', "'123456'")]), reprlocals=None, reprfileloc=ReprFileLocation(path='test_b.py', lineno=21, message='AssertionError'), style='long')], extraline=None, style='long'), ReprFileLocation(path='D:\demo\myweb\test_b.py', lineno=21, message="AssertionError: assert 'test2' == 'test1'
- test1
? ^
+ test2
? ^"), None)]),
'when': 'call',
'user_properties': [],
'sections': [('Captured stdout setup', 'login first----------
'), ('Captured stdout call', '---------打印的内容-------
传入参数 user->test2, password->123456
')],
'duration': 2.003612995147705,
'extra': []}
out.get_result() 用例执行结果
out.get_result() 返回用例执行的结果,主要有以下属性
- ‘nodeid’: ‘test_b.py::test_a[test1-123456]’,
- ‘location’: (‘test_b.py’, 8, ‘test_a[test1-123456]’),
- ‘keywords’: {‘test1-123456’: 1, ‘parametrize’: 1, ‘test_b.py’: 1, ‘test_a[test1-123456]’: 1, ‘myweb’: 1, ‘pytestmark’: 1},
- ‘outcome’: ‘passed’,
- ‘longrepr’: None,
- ‘when’: ‘call’,
- ‘user_properties’: [],
- ‘sections’: [(‘Captured stdout setup’, ‘login first————— ’), (‘Captured stdout call’, ‘————-打印的内容———- 传入参数 user->test1, password->123456 ’)],
- ‘duration’: 2.0006444454193115,
- ‘extra’: []
其中sections 就是用例里面print打印的内容了
import pytest
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
out = yield # 钩子函数的调用结果
res = out.get_result() # 获取用例执行结果
if res.when == "call": # 只获取call用例失败时的信息
print("获取用例里面打印的内容:{}".format(res.sections))
执行结果:
test_b.py 获取用例里面打印的内容:[('Captured stdout setup', 'login first----------
'), ('Captured stdout call', '---------打印的内容-------
传入参数 user->test1, password->123456
')]
.获取用例里面打印的内容:[('Captured stdout setup', 'login first----------
'), ('Captured stdout call', '---------打印 的内容-------
传入参数 user->test2, password->123456
')]
可以优化下输出
import pytest
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
out = yield # 钩子函数的调用结果
res = out.get_result() # 获取用例执行结果
if res.when == "call": # 只获取call用例失败时的信息
for i in res.sections:
print("{}: {}".format(*i))
运行结果
collected 2 items
test_b.py Captured stdout setup: login first----------
Captured stdout call: ---------打印的内容-------
传入参数 user->test1, password->123456
.Captured stdout setup: login first----------
Captured stdout call: ---------打印的内容-------
传入参数 user->test2, password->123456
相关文章
- 金融服务领域的大数据:即时分析
- 影响大数据、机器学习和人工智能未来发展的8个因素
- 从0开始构建一个属于你自己的PHP框架
- 如何将Hadoop集成到工作流程中?这6个优秀实践必看
- SEO公司使用大数据优化其模型的5种方法
- 关于Web Workers你需要了解的七件事
- 深入理解HTTPS原理、过程与实践
- 增强分析:数据和分析的未来
- PHP协程实现过程详解
- AI专家:大数据知识图谱——实战经验总结
- 关于PHP的错误机制总结
- 利用数据分析量化协同过滤算法的两大常见难题
- 怎么做大数据工作流调度系统?大厂架构师一语点破!
- 2019大数据处理必备的十大工具,从Linux到架构师必修
- OpenCV中的KMeans算法介绍与应用
- 教大家如果搭建一套phpstorm+wamp+xdebug调试PHP的环境
- CentOS下三种PHP拓展安装方法
- Go语言HTTP Server源码分析
- Go语言HTTP Server源码分析
- 2017年4月编程语言排行榜:Hack首次进入前五十