pytest系列——pytest_runtest_makereport钩子函数获取测试用例执行结果

前言

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

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

pytest_runtest_makereport方法简介

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

image

源码:

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 写一个简单的用例:

def test_a():


'''用例描述:test_a'''


print("123")
运行结果:

image

image

结果分析:

从结果可以看到,测试用例的执行过程会经历3个阶段:

setup -> call -> teardown

每个阶段会返回 Result 对象和 TestReport 对象,以及对象属性。(setupteardown上面的用例默认没有,结果都是passed。)

第二个案例

给用例写个 fixture() 函数增加测试用例的前置和后置操作; conftest.py 如下:


import pytest


@pytest.hookimpl(hookwrapper=True, tryfirst=True)

def pytest_runtest_makereport(item, call):

print('------------------------------------')


# 获取钩子方法的调用结果

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))



@pytest.fixture(scope="session", autouse=True)

def fix_a():

print("setup 前置操作")

yield

print("teardown 后置操作")

运行结果:

image

image

第三个案例

fixture() 函数的 setup 前置函数在执行时异常,即 setup 执行结果为 failed ,则后面的 call 测试用例与 teardown 后置操作函数都不会执行。

此时的状态是 error ,也就是代表测试用例还没开始执行就已经异常了。(在执行前置操作函数的时候就已经发生异常)


import pytest



@pytest.hookimpl(hookwrapper=True, tryfirst=True)

def pytest_runtest_makereport(item, call):

print('------------------------------------')


# 获取钩子方法的调用结果

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))



@pytest.fixture(scope="session", autouse=True)

def fix_a():

print("setup 前置操作")

assert 1 == 2

yield

print("teardown 后置操作")

运行结果:

image

image

第四个案例

setup 前置操作函数正常执行,测试用例 call 执行发生异常。

此时的测试用例执行结果为 failed


# 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))



@pytest.fixture(scope="session", autouse=True)

def fix_a():

print("setup 前置操作")

yield

print("teardown 后置操作")


# test_a.py


def test_a():

"""用例描述:test_a"""


print("123")

assert 1 == 0
运行结果:

image

image

第五个案例

setup 前置操作函数正常执行,测试用例 call 正常执行, teardown 后置操作函数执行时发生异常。

测试用例正常执行,但是测试结果中会有 error ,因为 teardown 后置操作函数在执行时发生异常


# conftest.py


import pytest



@pytest.hookimpl(hookwrapper=True, tryfirst=True)

def pytest_runtest_makereport(item, call):

print('------------------------------------')


# 获取钩子方法的调用结果

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))



@pytest.fixture(scope="session", autouse=True)

def fix_a():

print("setup 前置操作")

yield

print("teardown 后置操作")

raise Exception("teardown 失败了")


# test_a.py


def test_a():

'''用例描述:test_a'''

print("123")
运行结果:

image

image

image

第六个案例:只获取call结果

场景:编写测试用例时,在保证 setup 前置操作函数和 teardown 后置操作函数不报错的前提下,我们一般只需要关注测试用例的执行结果,即只需要获取测试用例执行call的结果。

解决办法:因为前面的 pytest_runtest_makereport 钩子方法执行了三次。所以在打印测试报告的相关数据之气可以加个判断: if report.when == "call" 


import pytest

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)

def pytest_runtest_makereport(item, call):

print('------------------------------------')


# 获取钩子方法的调用结果

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))



@pytest.fixture(scope="session", autouse=True)

def fix_a():

print("setup 前置操作")

yield

print("teardown 后置操作")

运行结果:

image

image

conftest.py 去除pytest_runtest_makereport 钩子方法,正常执行测试用例

# conftest.py


import pytest


@pytest.fixture(scope="session", autouse=True)

def fix_a():

print("setup 前置操作")

yield

print("teardown 后置操作")

# test_a.py


def test_a():

"""用例描述:test_a"""


print("123")
运行结果:

image

image

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

<think>好的,用户想了解如何使用pytest钩子函数获取测试用例(subtest)的参数。首先,我需要回忆一下pytest中subtest的机制。子测试通常是通过`TestCase.subTest`在unittest中使用的,但在纯pytest中,可能是指参数化测试中的多个用,或者pytest自带的subtest功能? 不过,pytest本身并没有直接等同于unittest的subTest,但可能用户指的是参数化测试中的每个子用。或者,用户可能使用了某种插件,比如pytest-subtest,这时候需要特定的钩子来捕获。需要先确定用户的具体使用场景。 假设用户是指参数化测试中的每个子用,也就是通过@pytest.mark.parametrize生成的多个测试用例。这时候,每个参数化的实都是一个独立的测试用例pytest在处理时会为每个参数生成单独的测试项。此时,钩子函数pytest_collection_modifyitems可以在收集阶段处理这些用获取它们的参数。 但用户提到的是子测试用例(subtest),可能更类似于在单个测试函数中生成多个子测试,比如使用生成器或者在测试内部循环,这时候每个循环迭代可能被视为一个子测试。不过,在pytest中,这种情况通常会被处理为多个独立的测试函数或参数化用,而不是子测试。 或者,可能用户是指pytest的subtest插件,如pytest-subtest,该插件允许在测试函数内部创建子测试,这样在测试报告中,主测试下会有多个子测试。这时候,如何通过钩子获取这些子测试的参数? 需要明确的是,pytest的内置钩子可能无法直接捕获到subtest的参数,因为子测试可能是在运行时动态生成的,而不是在测试收集阶段。这时候可能需要查看是否有特定的钩子或事件来处理这种情况。 首先,我应该查阅pytest关于钩子的文档,尤其是与测试用例相关的钩子pytest_runtest_protocol、pytest_runtest_makereport等,这些可能在测试执行过程中获取到子测试的信息。 假设用户使用的是pytest-subtest插件,该插件允许在测试中使用上下文管理器创建子测试。如: def test_example(): for i in range(3): with pytest.subtest(i=i): assert i % 2 == 0 在这种情况下,每个subtest会生成一个子测试项。这时候,pytest-subtest插件可能有自己的机制来生成子测试报告,并可能通过钩子来暴露这些子测试的参数。 要获取子测试的参数,可能需要监听相关的报告钩子,比如pytest_runtest_makereport,该钩子在每个测试项执行完成后被调用,可以在这里检查是否有子测试的报告。 当子测试执行时,主测试的报告中可能会有一些属性,比如user_properties,或者通过特定的插件添加的字段来存储子测试的信息。如,pytest-subtest可能会将子测试的参数存储在测试报告的某个位置。 如,在pytest_runtest_makereport钩子中,可以检查报告中是否有来自子测试的信息。当子测试执行时,可能会生成一个子报告,其when为"call",并且可能包含像context这样的属性,其中包含子测试的参数。 具体步骤可能是: 1. 编写一个pytest_runtest_makereport钩子函数,在conftest.py中实现。 2. 在这个钩子中,检查报告对象是否属于子测试。 3. 如果是子测试,获取其参数,比如通过report.user_properties或者report.context等属性。 需要实际测试一下,如,在conftest.py中添加钩子实现,打印出报告的相关属性,看看子测试的参数存储在哪里。 另外,可能需要查看pytest-subtest插件的文档或源码,了解它是如何处理子测试的报告和参数的。如,子测试的参数可能存储在测试报告的某个属性中,比如user_properties或者自定义的字段。 假设在子测试的报告中,参数是通过user_properties添加的,那么在钩子中可以这样获取: def pytest_runtest_makereport(item, call, report): if report.when == "call": for prop in report.user_properties: if prop[0] == "subtest": subtest_params = prop[1] print(f"Subtest parameters: {subtest_params}") 或者,可能需要检查item对象的属性,比如item._subtest,如果插件将其存储在那里。 另外,可能子测试的参数可以通过item.funcargs获取,但需要具体分析。 如果用户没有使用特定的插件,而是自己实现的子测试机制,可能需要自定义钩子来传递参数,但这种情况比较复杂。 总结来说,步骤应该是: 1. 确认用户使用的subtest机制是哪种(如pytest-subtest插件)。 2. 查阅相关插件的文档,确定如何访问子测试参数。 3. 使用适当的钩子函数(如pytest_runtest_makereport)在测试报告生成时提取参数。 4. 在钩子函数中处理报告对象,提取子测试的参数信息。 在实现时,可能需要在conftest.py中编写钩子函数,检查报告对象中的子测试信息,并打印或存储参数。 如,使用pytest-subtest时,子测试的参数可能保存在报告的某个属性中,可以通过遍历报告的用户属性或其他属性来获取。 可能需要编写示代码进行测试,确保能够正确获取参数。</think>在pytest获取子测试(subtest)参数可通过`pytest_subtest`插件配合钩子函数实现,以下是分步说明: $$注意:需先安装插件$$ ```bash pip install pytest-subtest ``` ### 步骤1:创建`conftest.py`文件 在项目根目录或测试目录中创建该文件,用于存放钩子函数 ### 步骤2:实现报告处理钩子 使用`pytest_runtest_makereport`钩子捕获子测试参数: ```python def pytest_runtest_makereport(item, call, report): # 仅处理测试执行阶段 if report.when == "call": # 检查是否存在子测试上下文 if hasattr(report, 'context'): # 提取子测试参数和断言结果 subtest_data = { "params": report.context['params'], "result": "PASSED" if report.passed else "FAILED", "msg": report.longreprtext } print(f"\n捕获子测试参数:{subtest_data}") ``` ### 步骤3:编写含子测试的用 ```python def test_example(): for i in [1, 2, 3]: # 通过上下文管理器创建子测试 with pytest.subtest(num=i): assert i % 2 == 0 # 故意让奇数失败 ``` ### 执行结果 ```text test_demo.py::test_example 捕获子测试参数:{'params': {'num': 1}, 'result': 'FAILED', 'msg': 'AssertionError: assert 1 % 2 == 0'} 捕获子测试参数:{'params': {'num': 2}, 'result': 'PASSED', 'msg': ''} 捕获子测试参数:{'params': {'num': 3}, 'result': 'FAILED', 'msg': 'AssertionError: assert 3 % 2 == 0'} ``` ### 关键点解析 1. **参数存储位置**:子测试参数通过`report.context['params']`访问 2. **结果判断**: - `report.passed`判断子测试是否通过 - `report.longreprtext`获取失败详情 3. **扩展应用**:可将参数写入文件/数据库,用于生成定制化报告 ### 注意事项 1. 主测试始终显示为`PASSED`,实际结果需通过子测试报告判断 2. 多个子测试共享同一个测试项ID,需通过参数区分不同实 3. 建议结合`pytest-html`等报告插件实现可视化展示 这种方法常用于: - 参数化测试结果分析 - 失败用参数追溯 - 测试数据覆盖率统计 - 动态生成测试报告
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值