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

相关推荐
7***374511 分钟前
Java设计模式之工厂
java·开发语言·设计模式
上不如老下不如小26 分钟前
2025年第七届全国高校计算机能力挑战赛初赛 Python组 编程题汇总
开发语言·python·算法
Q_Q51100828533 分钟前
python+django/flask的结合人脸识别和实名认证的校园论坛系统
spring boot·python·django·flask·node.js·php
Q_Q51100828534 分钟前
python+django/flask的选课系统与课程评价整合系统
spring boot·python·django·flask·node.js·php
程序员小白条36 分钟前
你面试时吹过最大的牛是什么?
java·开发语言·数据库·阿里云·面试·职场和发展·毕设
charlie11451419139 分钟前
勇闯前后端Week2:后端基础——Flask API速览
笔记·后端·python·学习·flask·教程
小年糕是糕手1 小时前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode
豐儀麟阁贵1 小时前
8.2异常的抛出与捕捉
java·开发语言·python
权泽谦1 小时前
PHP 版羊了个羊完整开发实战:逻辑解析 + 三消算法 + 全套接口(附源码)
开发语言·php
程序员西西1 小时前
SpringBoot无感刷新Token实战指南
java·开发语言·前端·后端·计算机·程序员