pytest测试框架之插件(hook函数)开发
参考文档:
https://docs.pytest.org/en/7.1.x/how-to/writing_hook_functions.html
https://juejin.cn/post/7281080420379131958
https://zhuanlan.zhihu.com/p/610804545
pytest 三种插件
pytest 给我们开放了大量的 hook 函数,可以编写插件。pytest 三种插件类型:
- 内置插件:从 pytest 内部 _pytest 目录加载的插件
- 外部插件:通过 pip 安装的插件(比如: pip install pytest-ordering )
- conftest.py 插件:测试目录中的 conftest.py 加载
pytest hook 函数
pytest hook 链接: https://docs.pytest.org/en/stable/reference.html?#hooks
pytest hook 函数也叫钩子函数,pytest 提供了大量的钩子函数,可以在用例的不同生命周期自动调用。 比如,在测试用例收集阶段,可利用 hook 函数修改测试用例名称的编码。
通常我们会把 hook 函数编写在项目的 conftest.py 文件中:
def pytest_collection_modifyitems(
session: "Session", config: "Config", items: List["Item"]
) -> None:
for item in items:
item.name = item.name.encode('utf-8').decode('unicode-escape')
item._nodeid = item.nodeid.encode