pytest插件探索——hook开发

1次阅读

共计 3826 个字符,预计需要花费 10 分钟才能阅读完成。

前言
参考官方的这篇文章,我尝试翻译其中一些重点部分,并且拓展了相关的 pluggy 部分的知识。由于 pytest 是在 pluggy 基础上构建的,强烈建议先阅读一下 pluggy 的官方文档,这样理解起来更加容易一点。
正文
conftest.py 可以作为最简单的本地 plugin 调用一些 hook 函数,以此来做些强化功能。
pytest 整个框架通过调用如下定义良好的 hooks 来实现配置,收集,执行和报告这些过程:

内置 plugins:从代码内部的_pytest 目录加载;

外部插件(第三方插件):通过 setuptools entry points 机制发现的第三方插件模块;

conftest.py 形式的本地插件:测试目录下的自动模块发现机制;

原则上,每个 hook 都是一个 1:N 的 python 函数调用,这里的 N 是对一个给定 hook 的所有注册调用数。所有的 hook 函数都使用 pytest_xxx 的命名规则,以便于查找并且同其他函数区分开来。
decorrator
pluggy 里提供了两个 decorator helper 类,分别是 HookspecMarker 和 HookimplMarker,通过使用相同的 project_name 参数初始化得到对应的装饰器,后续可以用这个装饰器将函数标记为 hookspec 和 hookimpl。
hookspec
hook specification (hookspec) 用来 validate 每个 hookimpl,保证 hookimpl 被正确的定义。
hookspec 通过 add_hookspecs() 方法加载,一般在注册 hookimpl 之前先加载;
hookimpl
hook implementation (hookimpl) 是一个被恰当标记过的回调函数。hookimpls 通过 register() 方法加载。
注:为了保证 hookspecs 在项目里可以不断演化, hookspec 里的参数对于 hookimpls 是可选的,即可以定义少于 spec 里定义数量的参数。
hookwrapper
hookimpl 里还有一个 hookwrapper 选项,用来表示这个函数是个 hookwrapper 函数。hookwrapper 函数可以在普通的非 wrapper 的 hookimpls 执行的前后执行一些其他代码,类似于 @contextlib.contextmanager,hookwrapper 必须在它的主体包含单一的 yield,用来实现生成器函数,例如:
import pytest

@pytest.hookimpl(hookwrapper=True)
def pytest_pyfunc_call(pyfuncitem):
do_something_before_next_hook_executes()

outcome = yield
# outcome.excinfo may be None or a (cls, val, tb) tuple

res = outcome.get_result() # will raise if outcome was exception

post_process_result(res)

outcome.force_result(new_res) # to override the return value to the plugin system
生成器发送一个 pluggy.callers._Result 对象,这个对象可以在 yield 表达式里指定并且通过 force_result() 或者 get_result() 方法重写或者拿到最终结果。
注:hookwrapper 不能返回结果 (跟所有的生成器函数一样);
hookimpl 的调用顺序
默认情况下,hook 的调用顺序遵循注册时的顺序 LIFO(后进先出),hookimpl 允许通过 tryfirst, trylast* 选项调整这一项顺序。
举个例子,对于如下的代码:
# Plugin 1
@pytest.hookimpl(tryfirst=True)
def pytest_collection_modifyitems(items):
# will execute as early as possible

# Plugin 2
@pytest.hookimpl(trylast=True)
def pytest_collection_modifyitems(items):
# will execute as late as possible

# Plugin 3
@pytest.hookimpl(hookwrapper=True)
def pytest_collection_modifyitems(items):
# will execute even before the tryfirst one above!
outcome = yield
# will execute after all non-hookwrappers executed
执行顺序如下:

Plugin3 的 pytest_collection_modifyitems 先调用,直到 yield 点,因为这是一个 hook warpper。
Plugin1 的 pytest_collection_modifyitems 被调用,因为有 tryfirst=True 参数。
Plugin2 的 pytest_collection_modifyitems 被调用,因为有 trylast=True 参数 (不过即使没有这个参数也会排在 tryfirst 标记的 plugin 后面)。
Plugin3 的 pytest_collection_modifyitems 调用 yield 后面的代码. yield 接收非 Wrapper 的 result 返回. Wrapper 函数不应该修改这个 result。

当然也可以同时将 tryfirst 和 trylast 与 hookwrapper=True 混用,这种情况下它将影响 hookwrapper 之间的调用顺序.
hook 执行结果处理和 firstresult 选项
默认情况下,调用一个 hook 会使底层的 hookimpl 函数在一个循环里按顺序执行,并且将其非空的执行结果添加到一个 list 里面。例外的是,hookspec 里有一个 firstresult 选项,如果指定这个选项为 true,那么得到第一个返回非空的结果的 hookimpl 执行后就直接返回,后续的 hookimpl 将不在被执行,参考后面的例子。
注:hookwrapper 还是正常的执行
hook 的调用
每一个 pluggy.PluginManager 都有一个 hook 属性, 可以通过调用这个属性的 call 函数来调用 hook,需要注意的是,调用时必须使用关键字参数语法来调用。
请看下面这个 firstresult 和 hook 调用例子:
from pluggy import PluginManager, HookimplMarker, HookspecMarker

hookspec = HookspecMarker(“myproject”)
hookimpl = HookimplMarker(“myproject”)

class MySpec1(object):
@hookspec
def myhook(self, arg1, arg2):
pass

class MySpec2(object):
# 这里将 firstresult 设置为 True
@hookspec(firstresult=True)
def myhook(self, arg1, arg2):
pass

class Plugin1(object):
@hookimpl
def myhook(self, arg1, arg2):
“””Default implementation.
“””
return 1

class Plugin2(object):
# hookimpl 可以定义少于 hookspec 里定义数量的参数,这里只定义 arg1
@hookimpl
def myhook(self, arg1):
“””Default implementation.
“””
return 2

class Plugin3(object):
# 同上,甚至可以不定义 hookspec 里的参数
@hookimpl
def myhook(self):
“””Default implementation.
“””
return 3

pm1 = PluginManager(“myproject”)
pm2 = PluginManager(“myproject”)
pm1.add_hookspecs(MySpec1)
pm2.add_hookspecs(MySpec2)
pm1.register(Plugin1())
pm1.register(Plugin2())
pm1.register(Plugin3())
pm2.register(Plugin1())
pm2.register(Plugin2())
pm2.register(Plugin3())
# hook 调用必须使用关键字参数的语法
print(pm1.hook.myhook(arg1=None, arg2=None))
print(pm2.hook.myhook(arg1=None, arg2=None))
得到结果如下:
[3, 2, 1]
3
可以看到,由于 pm2 里的 hookspec 里有 firstresult 参数,在得到 3 这个非空结果时就直接返回了。
自动注册插件
除了常规的 register() 方法注册插件,pluggy 同时提供了 load_setuptools_entrypoints() 方法,允许通过 setuptools entry points 自动注册插件。

正文完
 0