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")

执行结果:

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

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

相关推荐
CHANG_THE_WORLD3 分钟前
Python容器转换与共有函数详解
网络·python·rpc
高洁015 分钟前
循环神经网络讲解
人工智能·python·神经网络·机器学习·transformer
子午12 分钟前
【中草药识别系统】Python+TensorFlow+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
Sunsets_Red21 分钟前
二项式定理
java·c++·python·算法·数学建模·c#
R-G-B43 分钟前
OpenCV Python——窗口滑动条,TrackBar控件,createTrackbar(),getTrackbarPos(),
python·callback·trackbar·窗口滑动条·trackbar控件·createtrackbar·gettrackbarpos
ranchor6661 小时前
pandas 模拟题
开发语言·python·pandas
布茹 ei ai1 小时前
地表沉降监测分析系统(vue3前端+python后端+fastapi+网页部署)(开源分享)
前端·python·fastapi
闲人编程1 小时前
API限流、鉴权与监控
分布式·python·wpf·限流·集群·令牌·codecapsule
封奚泽优1 小时前
Deep-Live-Cam(调试和求助)
git·python·ffmpeg·pip·cuda
萤火虫的夏天2511 小时前
虚拟环境安装tensorflow使用GPU加速,显卡:1650ti
人工智能·python·tensorflow