深入理解 pytest_runtest_makereport:如何在 pytest 中自定义测试报告

pytest_runtest_makereport 是 pytest 系统中的一个钩子函数,它允许我们在测试执行时获取测试的报告信息。通过这个钩子,我们可以在测试运行时(无论是成功、失败还是跳过)对测试结果进一步处理,比如记录日志、添加自定义信息、生成报告等。

1、pytest_runtest_makereport 的作用

pytest_runtest_makereport 会在每个测试执行完成后被调用,并生成一个 TestReport 对象。这个对象包含了测试的执行结果,通常包括:

测试名称:测试的名称

执行结果:测试是成功(passed)、失败(failed)、跳过(skipped)还是标记为 Xfail(预期失败)

异常信息:如果测试失败或有异常,这里会包含异常的相关信息

执行时长:测试执行的时间

模块和函数信息:测试的模块、类、函数等

该钩子可以在每次测试完成后生成自定义报告或执行其他自定义操作。

2、使用 pytest_runtest_makereport

要使用 pytest_runtest_makereport,需要将它放在 conftest.py 文件中。

例如:记录每个测试的执行结果并生成日志

conftest.py 中定义 pytest_runtest_makereport 钩子:

python 复制代码
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()

    if rep.when == 'call':
        if rep.failed:
            logger.error(f"Test {item.nodeid}: FAILED\n")

            if call.excinfo:
                error_message = str(call.excinfo.value)
                logger.error(f"Test {item.nodeid} failed with error: {error_message}\n")
                print('这是error_message:', error_message)

        elif rep.skipped:
            outcome_status = 'SKIPPED'
            logger.info(f"Test {item.nodeid}: {outcome_status}\n")
        else:
            outcome_status = 'PASSED'
            logger.info(f"Test {item.nodeid}: {outcome_status}\n")

3、钩子函数的参数

pytest_runtest_makereport 接收两个参数:

item:表示当前的测试项(pytest.Item 对象),它包含了测试的相关信息,如测试名称、模块、类、函数等。

call:表示测试执行的结果。它是一个包含执行过程信息的对象,通常具有以下属性:

call.excinfo:如果测试失败或出错,这里会包含异常信息。

call.result:测试的返回结果(仅在测试通过时有效)。

4、生成详细报告

可以利用 pytest_runtest_makereport 来生成更详细的测试报告。比如,将失败的测试详情写入到文件中,或者在每次测试后生成 HTML、JSON 等格式的报告。

例如:记录失败测试并输出到文件

python 复制代码
# conftest.py

import pytest

def pytest_runtest_makereport(item, call):
    # 生成测试报告
    report = pytest.TestReport(item)
    
    # 如果测试失败,将失败信息写入到文件
    if report.failed:
        with open('failed_tests.log', 'a') as f:
            f.write(f"Test {item.nodeid} failed with error: {call.excinfo}\n")

5、获取详细的 TestReport 对象

pytest_runtest_makereport 默认返回的是一个 TestReport 对象,这个对象包含了很多关于测试的信息。可以使用它来定制测试报告。

TestReport 对象的常用属性包括:

nodeid:测试的标识符(通常是文件路径 + 测试函数名称)。

outcome:测试结果,可以是 'passed', 'failed', 'skipped' 等。

longrepr:如果测试失败,这里包含了失败的详细信息(例如堆栈跟踪)。

duration:测试的执行时长。

when:指示测试在何时执行。值可以是 'setup', 'call', 'teardown' 等,通常 call 是我们关心的测试执行阶段。

例如:打印详细的测试结果

python 复制代码
# conftest.py

import pytest

def pytest_runtest_makereport(item, call):
    report = pytest.TestReport(item)
    
    print(f"Test {item.nodeid} executed.")
    print(f"Outcome: {report.outcome}")
    print(f"Duration: {report.duration}")
    
    if report.outcome == 'failed':
        print(f"Failure details: {report.longrepr}")

【总结】

pytest_runtest_makereport 是一个强大的钩子函数,可以定制和扩展 pytest 的测试报告系统。通过该钩子,可以访问每个测试的详细结果,并在测试完成后执行自定义操作。这对于生成报告、日志记录、失败处理等非常有用。如果在使用 pytest 时需要更详细的报告或日志记录,pytest_runtest_makereport 是一个非常实用的工具。

相关推荐
我命由我1234525 分钟前
Android 设备的日志缓冲区被写满,logcat: Unexpected EOF!
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
171320330计算机毕设编程36 分钟前
基于SpringBoot的在线拍卖系统
android·java·spring boot·小程序·课程设计
用户09340777351437 分钟前
HarmonyOS WPS Open SDK 实践:OpenFileRequest 打开链路与沙箱拷贝
android·typescript·harmonyos
0xBADCODE1 小时前
动态DEX加载+反射+DES硬编码密钥:安卓三层逆向实战
android·java·python·安全·网络安全·逆向·ctf
天远Date Lab1 小时前
分布式微服务实战:基于天远车辆估值构建自动化车价评估网关
人工智能·分布式·微服务·自动化
JoyCong19981 小时前
从iPhone Ultra到ToDesk:折叠大屏时代的效率革命,硬件只是开始
大数据·运维·ios·智能手机·iphone·远程工作·远程操作
2501_916007471 小时前
Flutter与游戏App加固避坑指南:如何为混合开发与高交互应用选对安全方案?
安全·flutter·游戏·ios·小程序·uni-app·iphone
Patrick在香港1 小时前
Python 拉取 C&SD 官方 API:香港 2022 年已跨过“超老龄线“,而抚养比正在爬回 1961
android·c语言·python·数据分析·时序数据库·数据可视化·香港
DeepVisionary1 小时前
8 月 20 款大模型同台:OpenAI 拆出三档家族,IBM 押注 512K 密集推理,Meta 回头开源 30B
python·自动化
mmsx2 小时前
osmdroid 地图实战 03|谷歌影像的 URL,为什么不能 setTileSource 了事?
android