pytest 自定义HOOK函数

除了系统提过的HOOK函数外,也可以通过自定义HOOK的方式实现想要的功能。

首先创建一个py文件,里面定义自己的HOOK函数,主要pytest里面的hook函数必须以pytest开头。

#myhook.py


def pytest_myhook(user):
    """自定义HOOK函数"""


def pytest_myhook2():
    """自定义HOOK函数"""

其次创建自己的插件类,user类的重写__init__方法,注册钩子的时候带入pytest的config配置。在该方法中设置钩子入口:self

.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文件中注册钩子和引用实现它。其中注册方法要放在最前面。

先添加构造,在注册插件,

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

 

猜你喜欢

转载自blog.csdn.net/nhb687095/article/details/131738735