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 天前
结合unittest和pytest进行虚拟数据库测试
数据库·windows·pytest
江梦寻3 天前
如何使用 Python+Flask+win32print 实现简易网络打印服务
开发语言·后端·python·flask·pytest·web3.py·win32
qq_白羊座3 天前
pytest框架 核心知识的系统复习
pytest
@TangXin3 天前
单元测试-pytest框架实践
自动化测试·单元测试·pytest
evelol74 天前
【pytest框架源码分析四】pluggy源码分析之hook执行
自动化·pytest
云泽野6 天前
Pytest之parametrize参数化
android·python·pytest
evelol76 天前
【pytest框架源码分析三】pluggy源码分析之hook注册调用流程
自动化·pytest
云泽野7 天前
【Pytest】setup和teardown的四个级别
pytest
XuMeng_first8 天前
pytest的bug
bug·pytest