pytest钩子函数

pytest 给我们开放了大量的 hook 函数,可以编写插件

pytest 可以识别到三种插件:

内置插件:从 pytest 内部 _pytest 目录加载的插件

外部插件:通过 pip 安装的插件(比如: pip install pytest-ordering )。

conftest.py 插件:测试目录中的 conftest.py 加载

钩子函数:

pytest hook 链接: https://docs.pytest.org/en/stable/reference.html?#hooks

pytest hook 函数也叫钩子函数,是pytest 框架开发者为用户预留的一些函,pytest 提供了大量的钩子函数,可以在用例的不同生命周期自动调用

使用:

执行完测试用例后,需要对结果进行汇总,用例总数,失败用例数,成功用例数等。

pytest有自带的一个钩子函数:pytest_terminal_summary

python 复制代码
# conftest.py

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    :param terminalreporter: 报告汇总
    :param exitstatus: 退出状态
    :param config: 全局 Config 对象, 等同于 request.config
    :return:
    exitstatus:
        0 -- 用例全部通过
        1 -- 有用例失败
        2 -- 收集用i就失败了,还没执行
        3 -- 其他报错
        4 -- 其他报错
        5 -- 收集到0条用例
    """
    print(f'退出状态:{exitstatus}')

    # 获取环境地址
    base_url = config.option.base_url
    print(f'获取到的base_url: {base_url}')

    total = terminalreporter._numcollected
    if exitstatus in [0, 1]:
        passed = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
        failed = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
        skipped = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
        error = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
        successful = len(terminalreporter.stats.get('passed', [])) / terminalreporter._numcollected * 100
        duration = time.time() - terminalreporter._sessionstarttime
        markdown_text = f"""### 执行结果:  
        - 运行环境: 测试环境  
        - 运行base_url: {base_url}
        - 持续时间: {duration: .2f} 秒  

        ### 本次运行结果:  
        - 总用例数: {total}  
        - 通过用例:{passed}  
        - 跳过用例:{skipped}
        - 失败用例: {failed}  
        - 异常用例: {error}  
        - 通过率: {successful:.2f} % \n  
        """
        print(f'用例执行结果:{markdown_text}')
        with open("summary.json", 'w', encoding='utf-8') as fp:
            summary = {
                "total": total,
                "passed": passed,
                "failed": failed,
                "skipped": skipped,
                "error": error,
                "successful": f'{successful:.2f} %',
                "duration": duration
            }
            import json
            fp.write(json.dumps(summary, indent=4))
            
            """后面这里可以写发送邮件或者其他形式的通知"""
    else:
        print('未收集到测试用例')
python 复制代码
# test_allure_3.py

import allure
import requests
import json

class TestDemo:

    def test_x1(self):
        """输入正确的用户名和密码"""
        with allure.step('步骤1:登录前'):
            print('步骤1:登录前')
        allure.dynamic.feature('动态添加功能点1')
        print('x11111')
        allure.dynamic.title('动态添加title11')
        with allure.step('步骤2:登录后'):
            print('登录结束')


    def test_x2(self):
        """输入错误的用户名和密码"""
        with allure.step('步骤1:登录前'):
            print('步骤1:登录前')
        allure.dynamic.feature('动态添加功能点2')
        print('x222222')
        allure.dynamic.title('动态添加title22')
        with allure.step('步骤2:登录后'):
            print('登录结束')

参考:
https://blog.51cto.com/u_14844/6385694

相关推荐
listhi5202 小时前
基于空时阵列最佳旋转角度的卫星导航抗干扰信号处理的完整MATLAB仿真
开发语言·matlab·信号处理
岁岁岁平安2 小时前
本机 MongoDB 注册系统服务、启用security认证
数据库·python·mongodb
lly2024063 小时前
Kotlin 类和对象
开发语言
是苏浙3 小时前
零基础入门C语言之C语言内存函数
c语言·开发语言
zhmhbest3 小时前
Qt 全球峰会 2025:中国站速递 —— 技术中立,拥抱更大生态
开发语言·qt·系统架构
程序员大雄学编程3 小时前
用Python来学微积分30-微分方程初步
开发语言·python·线性代数·数学·微积分
关于不上作者榜就原神启动那件事3 小时前
模拟算法乒乓球
开发语言·c++·算法
我爱学习_zwj3 小时前
App通信:HTTP与JSON全解析
python
机器学习ing.3 小时前
U-Net保姆级教程:从原理到医学细胞分割实战(PyTorch版)!
人工智能·pytorch·python·深度学习·机器学习
88号技师3 小时前
2025年7月一区SCI优化算法-Logistic-Gauss Circle optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法