pytest_runtest_makereport钩子函数获取测试用例执行结果

前言

pytest测试框架提供的很多钩子函数方便我们对测试框架进行二次开发,可以根据自己的需求进行改造。

例如:钩子方法:pytest_runtest_makereport ,可以更清晰的了解测试用例的执行过程,并获取到每个测试用例的执行结果。

pytest_runtest_makereport方法简介

先看下相关的源码,在 _pytest/runner.py 文件下,可以导入之后查看:

源码:

from _pytest import runner

# 对应源码
def pytest_runtest_makereport(item, call):
    """ return a :py:class:`_pytest.runner.TestReport` object
    for the given :py:class:`pytest.Item` and
    :py:class:`_pytest.runner.CallInfo`.
    """

装饰器 pytest.hookimpl(hookwrapper=True, tryfirst=True) 解释:

@pytest.hookimpl(hookwrapper=True)装饰的钩子函数,有以下两个作用:

1、可以获取到测试用例不同执行阶段的结果(setup,call,teardown)

2、可以获取钩子方法 pytest_runtest_makereport(item, call) 的调用结果(yield返回一个测试用例执行后的result对象)和调用结果result对象中的测试报告(返回一个report对象)

pytest_runtest_makereport(item, call) 钩子函数参数解释:

1、 item 是测试用例对象;

2、 call 是测试用例的测试步骤;具体执行过程如下:

①先执行 when="setup" ,返回setup用例前置操作函数的执行结果。

②然后执行 when="call" ,返回call测试用例的执行结果。

③最后执行 when="teardown" ,返回teardown用例后置操作函数的执行结果。

第一个案例

conftest.py 文件编写pytest_runtest_makereport 钩子方法,打印运行过程和运行结果。

# conftest.py 

import pytest

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    print('------------------------------------')

    # 获取钩子方法的调用结果,返回一个result对象
    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))

test_a.py 写一个简单的用例

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值