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")
执行结果:

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

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

相关推荐
用户8356290780513 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng85 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi5 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee6 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay6 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤6 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean7 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽8 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188969 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听9 小时前
RAG深入学习之Chunk
前端·人工智能·python