pytest 自定义HOOK函数

2024软件测试面试刷题,这个小程序(永久刷题),靠它快速找到工作了!(刷题APP的天花板)【持续更新最新版】-CSDN博客

除了系统提过的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")
执行结果:

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

相关推荐
金銀銅鐵9 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1114 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0016 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵18 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf18 小时前
Agent 流程编排
后端·python·agent
copyer_xyf19 小时前
Agent RAG
后端·python·agent
copyer_xyf19 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf19 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python