前言
pytest这个框架提供了非常多的钩子。通过这些钩子我们可以对pytest 用例收集、用例执行、报告输出等各个阶段进行干预,根据需求去开发对应的插件,以满足自己的使用场景。
01 什么是钩子函数?
钩子函数在pytest称之为Hook函数,它pytest框架的开发者,为了让用户更好的去扩展开发预留的一些函数。而预留的这些函数,在整个测试执行的生命周期中特定的阶段会自动去调用执行。如下图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rwGtcb6r-1689820478252)(/api/attachments/426316)]
pytest中的钩子函数按功能一共分为6类:引导钩子,初始化钩子、用例收集钩子、用例执行钩子、报告钩子、调试钩子。
详细文档可以查看pytest官方文档https://docs.pytest.org/en/latest/reference/reference.html?highlight=hook#hooks
02 用例执行钩子
2.1 pytest_runtestloop
收集完成后执行主运行测试循环的钩子函数。
默认钩子实现对会话 ( ) 中收集的所有项目执行 runtest 协议session.items,除非收集失败或collectonly设置了 pytest 选项。如果在任何时候pytest.exit()调用,循环将立即终止。如果在任何点session.shouldfail或session.shouldstop设置,循环在当前项目的运行测试协议完成后终止。
参数:
- session:pytest 会话对象。
触发时机:
- 用例收集完后执行。
2.2 pytest_runtest_protocol
这个钩子函数是用来执行单个用例的,对单个测试项执行 runtest 协议。
参数:
- Item:执行的用例。
- nextitem: 指定的下一条执行的测试用例。
pytest默认的runtest协议为如下三个阶段:
-
设置阶段:这个阶段主要执行用例:前置夹具。
- call = pytest_runtest_setup(item)
- report = pytest_runtest_makereport(item, call)
- pytest_runtest_logreport(report)
- pytest_exception_interact(call, report)
-
调用阶段:这个阶段负责执行测试用例。
- call = pytest_runtest_call(item)
- report = pytest_runtest_makereport(item, call)
- pytest_runtest_logreport(report)
- pytest_exception_interact(call, report)
-
拆解阶段: 这个阶段主要执行用例:后置夹具。
- call = pytest_runtest_teardown(item, nextitem)
- report = pytest_runtest_makereport(item, call)
- pytest_runtest_logreport(report)
- pytest_exception_interact(call, report)
2.3 pytest_runtest_logstart
单个项目运行 runtest 协议开始时调用。
参数:
- nodeid : 完整的节点ID。
- location :包含如下三个值的元组(filename, lineno, testname) ,分别为文件名、行号、用例名称。
2.4 pytest_runtest_logfinish
在单个项目运行 runtest 协议结束时调用。
参数:
- nodeid : 完整的节点ID。
- location :包含如下三个值的元组(filename, lineno, testname) ,分别为文件名、行号、用例名称。
2.5 pytest_runtest_setup
在运行runTest协议时,设置阶段执行的钩子函数。该钩子函数默认实现的行为是负责执行前置的测试夹具,以及获取前置夹具中yeild返回的数据。
参数:
Item:执行的用例。
2.6 pytest_runtest_call
在运行runTest协议时,调用阶段执行的钩子函数,该钩子函数的默认实现的行为是执行:item.runtest()。
参数:
Item:执行的用例。
2.7 pytest_runtest_teardown
在运行runTest协议时, 拆卸阶段 执行的钩子函数。该钩子函数默认实现的行为是负责执行后置的测试夹具。
参数:
- Item:执行的用例。
- nextitem: 执行的下一条用例。
2.8 pytest_runtest_makereport
该钩子函数,在用例执行runTest协议的过程中,每个阶段都会调用一次。期作用是为了创建测试执行记录器,记录每个阶段执行的结果。
参数:
-
Item:执行的用例
-
call: 用例执行的阶段。
为了更深入地理解,您可以查看这些钩子的默认实现,也可以查看_pytest.runner其中_pytest.pdb的交互_pytest.capture 及其输入/输出捕获,以便在发生测试失败时立即进入交互式调试。
2.9 pytest_pyfunc_call
该钩子函数的作用是为了调用底层的测试执行函数。
参数:
- pyfuncitem: 最终执行的用例函数。