pytest教程-45-钩子函数-pytest_report_testitemFinished

领取资料,咨询答疑,请➕wei:  June__Go

上一小节我们学习了pytest_report_collectionfinish钩子函数的使用方法,本小节我们讲解一下pytest_report_testitemFinished钩子函数的使用方法。

pytest_report_testitemFinished 钩子函数在每个测试项(测试函数或测试方法)执行完成后被调用。这个钩子可以用来获取测试结果、执行自定义的报告逻辑,或者在测试结束后进行一些清理工作。以下是一个具体的代码示例,展示了如何在 conftest.py 文件中使用这个钩子函数:

# conftest.py

import pytest

# 全局变量用于存储测试结果
test_results = {}

def pytest_report_testitemFinished(item, report):
    # 获取测试项的名称和结果
    test_name = item.name
    test_result = report.outcome

    # 将测试结果存储在全局字典中
    test_results[test_name] = test_result

    # 根据测试结果执行不同的操作
    if test_result == "passed":
        print(f"{test_name} passed.")
    elif test_result == "failed":
        print(f"{test_name} failed.")
        print(f"Failure details: {report.longrepr}")
    elif test_result == "skipped":
        print(f"{test_name} skipped.")
    else:
        print(f"{test_name} had an unknown outcome: {test_result}")

    # 如果需要,可以在这里执行一些清理工作,例如关闭资源
    # ...

# 在测试运行结束时,可以输出所有测试结果
def pytest_sessionfinish(session, exitstatus):
    # 输出所有测试项的结果
    for test_name, result in test_results.items():
        print(f"{test_name}: {result}")

    # 清空测试结果字典,为下一次测试会话做准备
    test_results.clear()

在这个示例中,我们首先定义了一个全局字典 test_results 来存储每个测试项的名称和结果。在 pytest_report_testitemFinished 钩子函数中,我们根据测试结果的 outcome 属性(可以是 "passed"、"failed"、"skipped" 或其他值)来执行不同的操作。例如,我们可以打印出失败的测试项的详细信息。

我们还定义了一个 pytest_sessionfinish 钩子函数,在测试会话结束时输出所有测试项的结果,并清空 test_results 字典,以便为下一次测试会话做准备。

请注意,这个示例中的代码仅用于演示如何使用 pytest_report_testitemFinished 钩子函数来处理测试结果。在实际应用中,你可能需要根据具体的测试需求来调整这些操作,例如生成更详细的测试报告或者执行更复杂的后处理逻辑。

在这个复杂的示例中,我们将使用 pytest_report_testitemFinished 钩子函数来实现一个更高级的测试结果处理流程。我们将在测试用例完成后收集详细的结果信息,包括执行时间、断言结果、异常信息等,并在测试会话结束时生成一个详细的测试报告。此外,我们还将展示如何使用 pytest_sessionfinish 钩子函数来执行测试后的清理工作。

首先,确保你的项目中有一个 conftest.py 文件。然后,在 conftest.py 文件中定义 pytest_report_testitemFinishedpytest_sessionfinish 钩子函数:

# conftest.py

import pytest
import json
from datetime import datetime

# 全局变量用于存储测试结果
test_results = {}

def pytest_report_testitemFinished(item, report):
    # 获取测试项的名称和结果
    test_name = item.name
    test_result = report.outcome

    # 获取测试执行时间
    execution_time = report.duration

    # 获取断言结果和异常信息
    assert_count = len(report.assertion_list)
    exception_info = report.longrepr if report.failed else None

    # 创建测试结果字典
    test_result_data = {
        'name': test_name,
        'outcome': test_result,
        'duration': execution_time,
        'assert_count': assert_count,
        'exception_info': exception_info
    }

    # 将测试结果存储在全局字典中
    test_results[test_name] = test_result_data

    # 根据测试结果执行不同的操作
    if test_result == "passed":
        print(f"{test_name} passed in {execution_time:.2f} seconds.")
    elif test_result == "failed":
        print(f"{test_name} failed in {execution_time:.2f} seconds.")
        if exception_info:
            print(f"Exception: {exception_info}")
    elif test_result == "skipped":
        print(f"{test_name} skipped.")

def pytest_sessionfinish(session, exitstatus):
    # 获取当前时间戳
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 创建测试报告文件
    report_file = f"pytest_test_report_{timestamp}.json"

    # 将测试结果写入 JSON 文件
    with open(report_file, 'w') as json_report:
        json.dump(test_results, json_report, indent=4)

    # 打印报告文件的路径
    print(f"\nTest report saved to: {os.path.abspath(report_file)}")

    # 执行清理工作,例如关闭数据库连接或网络资源
    # ...

    # 清空测试结果字典,为下一次测试会话做准备
    test_results.clear()

在这个示例中,我们在 pytest_report_testitemFinished 钩子函数中收集了每个测试用例的详细信息,包括名称、结果、执行时间、断言数量和异常信息。我们将这些信息存储在全局字典 test_results 中,并根据测试结果打印相应的信息。

pytest_sessionfinish 钩子函数中,我们创建了一个 JSON 文件来保存所有测试用例的结果。这个文件包含了所有测试用例的详细信息,可以用于后续的分析或报告生成。我们还打印了报告文件的路径,以便用户可以轻松地找到它。

请注意,这个示例中的代码仅用于演示如何使用 pytest_report_testitemFinishedpytest_sessionfinish 钩子函数来处理测试结果和生成报告。在实际应用中,你可能需要根据具体的测试需求来调整这些操作,例如生成不同格式的报告或者执行更复杂的后处理逻辑。

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走,希望可以帮助到大家!领取资料,咨询答疑,请➕wei:  June__Go

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值