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

相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github