Hook¶
Pytest Hook 的类型:
1. Bootstrapping Hooks
2. Initialization Hooks
3. Collection Hooks
4. Test running (runtest) hooks
5. Reporting Hooks
6. Debugging/Interaction Hooks
Ordering of Pytest Hooks:
1. tryfirst=True: Execution as Early as Possible
2. trylast=True: Execution as Late as Possible
3. hookwrapper=True: Hook Wrappers
creates a hook that wraps around all others.
It can execute code both before and after the standard hooks.
示例:
@pytest.hookimpl(hookwrapper=True)
def pytest_collection_modifyitems(items):
# 在all non-wrapper hooks 运行前运行
outcome = yield
# 在all non-wrapper hooks 运行后运行
4. optionalhook=True: 这个参数表示这个钩子函数是可选的,它应该被调用,但可以忽略
pytest_collection_modifyitems()函数:
四个参数:
item:当前测试用例的对象
call:表示测试用例的调用状态,包括 setup, call, teardown 三个阶段
keyword:关键字参数,通常不需要手动传递
outcome:测试结果信息