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")
执行结果:
相关推荐
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L3 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅3 天前
海天线算法的前世今生
python·计算机视觉
韩师傅3 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L3 天前
LangGraph的MessageState and HumanMessage
python