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

相关推荐
0wioiw02 分钟前
安卓基础(Okhttp3)
android
海鸥-w1 小时前
Untiy3d 铰链、弹簧,特殊的物理关节
android·3d
知识倒进我脑里2 小时前
pytest生成报告no tests ran in 0.01s
pytest
神仙别闹2 小时前
基于IOS开发五子棋游戏
游戏·ios
FL16238631294 小时前
[C#].net顶级语句省略main方法内容
ui·.net·xhtml
gp1036 小时前
iOS主要知识点梳理回顾-5-运行时方法交换
ios·方法交换
布谷歌6 小时前
【注意】sql语句where条件中的数据类型不一致,不仅存在性能问题,还会有数据准确性方面的bug......
android·数据库·sql·bug
初见_Dream6 小时前
Android 消息总站 设计思路
android
浩说安卓6 小时前
Android Studio集成讯飞SDK过程中在配置Project的时候有感
android·ide·android studio
叶落方知秋6 小时前
OkHttp 3.10.0版本源码之缓存拦截器CacheInterceptor原理分析
android·前端框架