深入理解 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 是一个非常实用的工具。

相关推荐
北京耐用通信9 分钟前
破解AGV多协议互联难题:耐达讯自动化Profinet转Devicenet网关如何实现高效协同
人工智能·科技·物联网·网络协议·自动化·信息与通信
游戏开发爱好者81 小时前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
王码码20351 小时前
Flutter for OpenHarmony 实战之基础组件:第三十一篇 Chip 系列组件 — 灵活的标签化交互
android·flutter·交互·harmonyos
梦帮科技2 小时前
OpenClaw 桥接调用 Windows MCP:打造你的 AI 桌面自动化助手
人工智能·windows·自动化
黑码哥2 小时前
ViewHolder设计模式深度剖析:iOS开发者掌握Android列表性能优化的实战指南
android·ios·性能优化·跨平台开发·viewholder
亓才孓2 小时前
[JDBC]元数据
android
feasibility.2 小时前
AI 编程助手进阶指南:从 Claude Code 到 OpenCode 的工程化经验总结
人工智能·经验分享·设计模式·自动化·agi·skills·opencode
独行soc2 小时前
2026年渗透测试面试题总结-17(题目+回答)
android·网络·安全·web安全·渗透测试·安全狮
金融RPA机器人丨实在智能2 小时前
Android Studio开发App项目进入AI深水区:实在智能Agent引领无代码交互革命
android·人工智能·ai·android studio
科技块儿2 小时前
利用IP查询在智慧城市交通信号系统中的应用探索
android·tcp/ip·智慧城市