pytest 自定义HOOK函数

除了系统提过的HOOK函数外,也可以通过自定义HOOK的方式实现想要的功能。

首先创建一个py文件,里面定义自己的HOOK函数,主要pytest里面的hook函数必须以pytest开头。

python 复制代码
#myhook.py


def pytest_myhook(user):
    """自定义HOOK函数"""


def pytest_myhook2():
    """自定义HOOK函数"""

其次创建自己的插件类,user类的重写__init__方法,注册钩子的时候带入pytest的config配置。在该方法中设置钩子入口:self

python 复制代码
.config.hook.pytest_myhook().

#插件类
class user:
    name = "herry"
    age = 18


    def __init__(self, config):
        self.config = config
        self.config.hook.pytest_myhook(user=self)
        self.config.hook.pytest_myhook2()




@pytest.mark.A
def test_B():
    print("BBB")




if __name__ == "__main__":
    pytest.main([("pytest模块分享之hook2.py"), ("-s"), ("-m=A")])

最后在conftest.py文件中注册钩子和引用实现它。其中注册方法要放在最前面。

先添加构造,在注册插件,

python 复制代码
def pytest_addhooks(pluginmanager):
    from . import myhook


    pluginmanager.add_hookspecs(myhook)




def pytest_configure(config):
    config.user_ = user(config)
    config.pluginmanager.register(config.user_)




def pytest_myhook(user):
    print("username------%s"%user.name)
    print("age------%s" % user.age)


def pytest_myhook2():
    print("myhook2")
执行结果:
相关推荐
明月_清风35 分钟前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽10 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805115 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon16 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly16 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程16 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly18 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法