从0到1精通自动化测试,pytest自动化测试框架,Hooks函数获取用例执行结果(二十三)

本文介绍了如何使用pytest的pytest_runtest_makereport钩子来获取测试用例的执行过程和结果。通过示例详细讲解了setup、call和teardown的不同状态,包括正常执行、失败情况及其对测试结果的影响。
摘要由CSDN通过智能技术生成

一、前言

pytest提供的很多钩子(Hooks)方法方便我们对测试用例框架进行二次开发,可以根据自己的需求进行改造

先学习下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`.
    """

这里item是测试用例,call是测试步骤,具体执行过程如下:

1.先执行when=’setup’ 返回setup 的执行结果

2.然后执行when=’call’ 返回call 的执行结果

3.最后执行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('------------------------------------')

    # 获取钩子方法的调用结果
    out = yield
    print('用例执行结果', out)

    # 3. 从钩子方法的调用结果中获取测试报告
    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写一个简单的用例

def test_a():
    '''用例描述:test_a'''
    print("行行行行")

运行结果如下

D:\soft\code\pytest_jenkins_demo\demo>pytest -s
============================= test session starts ====
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值