欢迎来到魔幻小生的博客

pytest Hook 钩子函数

什么是 Hook 函数

比如说你写了一个框架类的程序,你希望这个框架可以“被其他的代码注入”,即别人可以加入代码对你这个框架进行定制化,该如何做比较好?

一种很常见的方式就是约定一个规则,框架初始化时会收集满足这个规则的所有代码(文件),然后把这些代码加入到框架中来,在执行时一并执行。所有这一规则下可以被框架收集到的方法就是hook方法

pytest 的 Hook 函数

image

Hook 钩子函数是 pytest 框架预留的函数,通过这些钩子我们可以对 pytest 用例收集、用例执行、报告输出等各个阶段进行干预。

pytest 插件就是用1个或者多个 hook 函数,也就是钩子函数构成的。如果想要编写新的插件,或者是仅仅改进现有的插件,都必须通过这个 hook 函数进行。所以想掌握 pytest 插件二次开发,必须搞定 hook 函数。

pytest 中的钩子函数按功能一共分为6类:引导钩子,初始化钩子、用例收集钩子、用例执行钩子、报告钩子、调试钩子。

pytest内置hooks函数源码文件路径:\site-packages\_pytest\hookspec.py

通过在 conftest.py 中重写 hook 方法。

image

官方文档:https://doc.pytest.org/en/latest/_modules/_pytest/hookspec.html

常用方法

修改默认编码支持中文

# conftest.py 文件
def pytest_collection_modifyitems(session, config, items):
    for item in items:
        # item.name 用例名称
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        # item.nodeid 用例路径
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')
# test_hook.py 文件
@pytest.mark.parametrize("name", ["哈利", "赫敏", "罗恩"])
def test_demo(self, name):
	print(name)

image

改变编码后的执行结果:

image

改变用例执行顺序

pytest_collection_modifyitems(session, config, items)

可以通过此 hook 函数改变收集到用例的执行顺序

# conftest.py 文件
def pytest_collection_modifyitems(session, config, items):
    print(f"收集到的测试用例{items}")
    #items.reverse()  # 将收集到的用例反转
    random.shuffle(items)  # 将收集到的用例进行随机
    print(f"随机排序后的用例{items}")

命令行添加自定义参数

parser.addoption()

使用 python -m pytest --help 便可以看见添加的自定义参数

# conftest.py 文件
def pytest_addoption(parser, pluginmanager):
    mygroup = parser.getgroup("hogwarts")
    mygroup.addoption("--env",      #注册一个命令行选项
        default='test',             #参数默认值
        dest='env',                 #存储的变量
        help='set your run env'     #参数描述信息
    )

@pytest.fixture(scope='session')
def cmdoption(request):
    env = request.config.getoption("--env", default='test')
    if env == 'test':
        print("test 环境")
    elif env == 'dev':
        print("开发 环境")
    return env
# test_hook.py 文件
def test_env(self, cmdoption):
    print(cmdoption)
posted @ 2025-03-15 16:27  魔幻小生  阅读(103)  评论(0)    收藏  举报