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

.config.hook.pytest_myhook().

python 复制代码
#插件类
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")

执行结果:

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

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

相关推荐
Cloud_Shy6181 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 30 - 32)
开发语言·人工智能·笔记·python·学习方法
天佑木枫27 分钟前
15天Python入门系列 · 序
开发语言·python
happylifetree28 分钟前
Python017-第二章15.数据容器-dict常用操作
python
装不满的克莱因瓶42 分钟前
了解 LangChain 中的 LLM 与 ChatModel 的差异
人工智能·python·ai·langchain·llm·agent·chatmodel
IT知识分享2 小时前
从零开发在线简繁转换工具:OpenCC 实战、避坑经验与方案选型
javascript·python
lunzi_08262 小时前
【学习笔记】《Python编程 从入门到实践》第8章:函数定义、参数传递与模块导入
笔记·python·学习
杨运交2 小时前
[030][Web模块]Spring Boot 验证与 OpenAPI 集成实战:从校验规则到文档生成
前端·spring boot·python
培培说证2 小时前
2026财务岗位如何快速提升自身能力
python
努力攻坚操作系统2 小时前
编程语言编译运行机制对比:C / Java / Python
java·c语言·python
godspeed_lucip2 小时前
LLM和Agent——专题6:Multi Agent 入门(5)
人工智能·python