前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pytest(二十三)钩子函数pytest_runtest_makereport获取用例执行报错内容和print内容

Pytest(二十三)钩子函数pytest_runtest_makereport获取用例执行报错内容和print内容

作者头像
雷子
发布2022-05-21 11:07:49
2K0
发布2022-05-21 11:07:49
举报
文章被收录于专栏:雷子说测试开发

Pytest系列分享

Pytest系列(一)初次了解

Pytest(二)执行规则以及编写执行多条用例

Pytest(三)Pytest执行命令

Pytest(四)Pytest断言

Pytest(五)标记函数

Pytest(六)跳过测试

Pytest(七) pytest之参数化

Pytest(八) pytest Fixture(一)

Pytest(九) pytest Fixture(二)

Pytest(十) pytest Fixture(三)

Pytest(十一) pytest ini文件

Pytest(十二) Pytest产生测试报告

Pytest(十三)durations统计用例运行时间

Pytest(十四)用例执行顺序

Pytest(十五)重试机制

Pytest(十六)多进程并发执行

Pytest(十七)pytest增加log日志

Pytest(十八)setup和teardown

Pytest(十九)利用内置的cache 写入和读取缓存数据解决简单的数据依赖

Pytest(二十)揭秘如何利用allure标记case的重要性

Pytest(二十一)利用allure增加一些文本、截图等

Pytest(二十二)利用allure增加对用例步骤等描述

pytest在执行用例的时候,当用例报错的时候,如何获取到报错的完整内容呢?

当用例有print()打印的时候,如何获取到打印的内容?

那么应该如何做?

答案是 使用钩子函数:pytest_runtest_makereport

代码语言:javascript
复制
那么pytest_runtest_makereport作用:
对于给定的测试用例(item)和调用步骤(call),
返回一个测试报告对象(_pytest.runner.TestReport);
具体表现为:这个钩子方法会被每个测试用例调用 3 次,分别是:
用例的 setup 执行完毕后,调用 1 次,返回 setup 的执行结果;
用例执行完毕之后,调用 1 次,返回测试用例的执行结果;
用例的 teardown 执行完毕后,调用1 次,返回 teardown 的执行结果;

那么应该如何使用呢,我们去看一个简单的例子

在conftest.py配置

代码语言:javascript
复制
import pytest
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    out = yield  # 钩子函数
    res = out.get_result()   # 获取用例执行结果
    print(res)
    if res.when == "call":   # 只获取call用例失败时的信息
        print("item:{}".format(item))
        print("用例描述:{}".format(item.function.__doc__))
        print("异常:{}".format(call.excinfo))
        print("详细日志:{}".format(res.longrepr))
        print("测试结果:{}".format(res.outcome))
        print("用例耗时:{}".format(res.duration))
        print(res.__dict__)

去执行下对应的用例,看下执行的结果:

代码语言:javascript
复制
test_11.py::test_1 <TestReport 'test_11.py::test_1' when='setup' outcome='passed'>
获取到的id: leisi说测试
fixture 中返回: leisi说测试
<TestReport 'test_11.py::test_1' when='call' outcome='passed'>
item:<Function test_1>
用例描述:None
异常:None
详细日志:None
测试结果:passed
用例耗时:0.0007911720000000066
{'nodeid': 'test_11.py::test_1', 'location': ('test_11.py', 162, 'test_1'), 'keywords': {'test_1': 1, 'test_11.py': 1, 'pyteststuday': 1}, 'outcome': 'passed', 'longrepr': None, 'when': 'call', 'user_properties': [], 'sections': [], 'duration': 0.0007911720000000066}
PASSED<TestReport 'test_11.py::test_1' when='teardown' outcome='passed'>

当然在前面的使用的时候说的setup和teardown也是可以满足的。

代码语言:javascript
复制
class Test(object):
    def setup(self):
        print('11')
    def teardown(self):
        print('2222')
    def test_1(self):
        print("test")
        assert  1,2

我们看下执行结果

可以正常输出内容信息。而且我们看到一共调用了三次。和我们前面说的是一致的。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-04-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 雷子说测试开发 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档