pytest中钩子函数的使用

收集测试结果:

2. pytest_terminal_summary(terminalreporter, exitstatus,config)

在测试执行完毕后,用于生成并显示最终的测试摘要信息到终端,你可以实现自定义的测试报告汇总和显示。

例如:你可以在此钩子函数中计算测试用例覆盖率、输出额外的统计信息

在conftest.py文件中使用,所有的测试用例执行完成后,自动收集测试结果

python 复制代码
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    函数:pytest钩子函数,固定写法,每次pytest测试完成后,会自动收集测试结果
    :param terminalreporter:内部终端报告对象,对象的status属性
    :param exitstatus:返回给操作系统的返回码
    :param config:pytest配置的config对象
    :return:
    """
    # 打印执行结果
    result = terminalreporter.stats
    # 获取测试用例总数
    case_all_num = terminalreporter._numcollected
    if case_all_num > 0:
        # 获取成功的用例数
        case_pass_num = len(terminalreporter.stats.get('passed', []))
        # 获取失败的用例数
        case_failed_num = len(terminalreporter.stats.get('failed', []))
        # 获取错误的用例数
        case_error_num = len(terminalreporter.stats.get('error', []))
        # 获取跳过的用例数
        case_skipped_num = len(terminalreporter.stats.get('skipped', []))
        # 获取执行时长
        # round: 四设五入保留小数位数
        run_time = round(time.time() - terminalreporter._sessionstarttime, 2)
        formt_run_time = format_datatime(run_time)
        # 统计测试用例-通过率
        tgl_str = None
        if case_all_num > 0:
            tgl = int(case_pass_num) / int(case_all_num)
            tgl_str = "{:.2%}".format(tgl)

        # 测试结果写入txt文档
        result = os.path.join("./report", "result.txt")

        # 写入测试结果到reports下的result.txt文件
        with open(result, "w") as f:
            f.write(f"本次接口自动化测试结果如下(请注意失败及错误的接口):\n")
            f.write(f"用例总数:{case_all_num}个\n")
            f.write(f"通过数:{case_pass_num}个\n")
            f.write(f"失败数:{case_failed_num}个\n")
            f.write(f"跳过数:{case_skipped_num}个\n")
            f.write(f"错误数:{case_error_num}个\n")
            f.write(f"成功率:{tgl_str}个\n")
            f.write(f"用例执行时长:{run_time}秒 ({formt_run_time})")

        summary = str()
        with open(result, 'r') as f:
            for i in f.readlines():
                summary = f'{summary}' + i
        mylog.info(summary)

参考博文:

pytest合集(9)--- Hook钩子函数_pytest钩子函数-CSDN博客

相关推荐
努力搬砖的咸鱼1 天前
从零开始搭建 Pytest 测试框架(Python 3.8 + PyCharm 版)
python·pycharm·pytest
FINE!(正在努力!)3 天前
PyTest框架学习
学习·pytest
程序员杰哥4 天前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
测试老哥4 天前
Pytest+Selenium UI自动化测试实战实例
自动化测试·软件测试·python·selenium·测试工具·ui·pytest
水银嘻嘻4 天前
07 APP 自动化- appium+pytest+allure框架封装
python·appium·自动化·pytest
天才测试猿5 天前
接口自动化测试之pytest接口关联框架封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
not coder6 天前
Pytest Fixture 详解
数据库·pytest
not coder6 天前
pytest 常见问题解答 (FAQ)
开发语言·python·pytest
程序员的世界你不懂6 天前
(1)pytest简介和环境准备
pytest
not coder6 天前
Pytest Fixture 是什么?
数据库·oracle·pytest