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

相关推荐
Swift社区1 小时前
iOS 基于 Foundation Model 构建媒体流
ios·iphone·swift·媒体
研究司马懿2 小时前
【ETCD】ETCD常用命令
网络·数据库·云原生·oracle·自动化·运维开发·etcd
-指短琴长-2 小时前
MySQL快速入门——基本查询(下)
android·mysql·adb
库奇噜啦呼3 小时前
【iOS】音频与视频播放
ios·音视频·cocoa
stevenzqzq4 小时前
android lambda回调
android
林北北的霸霸6 小时前
django初识与安装
android·mysql·adb
覆东流6 小时前
Photoshop合成的核心知识
ui·photoshop
Java 码农8 小时前
MySQL EXPLAIN 详解与优化指南
android·mysql·adb
我的xiaodoujiao8 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 24--数据驱动--参数化处理 Excel 文件 1
python·学习·测试工具·pytest