参考资料
https://docs.pytest.org/en/latest/plugins.html(Installing and Using plugins)
https://docs.pytest.org/en/latest/writing_plugins.html#writing-plugins(Writing plugins)
https://docs.pytest.org/en/latest/_modules/_pytest/hookspec.html(Source code for _pytest.hookspec)
pytest插件加载方式
内置plugins:从代码内部的_pytest目录加载
外部插件(第三方插件):通过setuptools entry points机制发现的第三方插件模块
conftest.py形式的本地插件:测试目录下的自动模块发现机制
hook函数定制和扩展插件
pytest源码中的钩子函数:site-packages -> _pytest -> hookspec.py
pytest_collection_modifyitems:源码中的钩子函数,我们可以通过这个函数对收集上来的测试用例实现定制化功能
conftest.py
def pytest_collection_modifyitems(
session: "Session", config: "Config", items: List["Item"]
) -> None:
"""
Called after collection has been performed. May filter or re-order the items in-place.
:param pytest.Session session: The pytest session object.
:param _pytest.config.Config config: The pytest config object.
:param List[pytest.Item] items: List of item objects.
"""
#items是收集的测试用例列表,item代表每个测试用例对象
#自定义用例的执行顺序(倒序执行收集的用例)
items.reverse()
for item in items