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

相关推荐
我命由我123451 分钟前
Photoshop - Photoshop 创建文档
学习·ui·课程设计·设计·photoshop·ps·美工
fatiaozhang95276 分钟前
中国移动中兴云电脑W132D-RK3528-2+32G-刷机固件包(非原机制作)
android·xml·电脑·电视盒子·刷机固件·机顶盒刷机
六月的可乐1 小时前
【干货推荐】AI助理前端UI组件-悬浮球组件
前端·人工智能·ui
Android出海2 小时前
Google Play账户与App突遭封禁?紧急应对与快速重构上架策略
android·网络·重构·新媒体运营·产品运营·内容运营
恋猫de小郭2 小时前
Flutter 官方 LLM 动态 UI 库 flutter_genui 发布,让 App UI 自己生成 UI
android·前端·flutter
锅拌饭3 小时前
saveEnabled导致的Fragment大量泄露
android
叽哥3 小时前
Kotlin学习第 3 课:Kotlin 流程控制:掌握逻辑分支与循环的艺术
android·java·kotlin
CYRUS_STUDIO3 小时前
别让 so 裸奔!移植 OLLVM 到 NDK 并集成到 Android Studio
android·android studio·llvm
尚久龙3 小时前
安卓学习 之 图片控件和图片按钮
android·java·学习·手机·android studio·安卓
东风西巷3 小时前
Don‘t Sleep:保持电脑唤醒,确保任务不间断
android·电脑·软件需求