@pytest.hookimpl 什么时候执行
When is @pytest.hookimpl executes
我是pytest的新手。 @pytest.hookimpl 什么时候执行?它的完整用法是什么?我试过日志。对于(hookwrapper=true),就是打印,单次测试yield前后3组。
pytest 使用 @pytest.hookimpl
只是标记钩子方法。 (所以@pytest.hookimpl
是在pytest收集hook方法的时候执行的。)
如果你阅读了pytest的源代码,你可以找到这些代码:
def normalize_hookimpl_opts(opts):
opts.setdefault("tryfirst", False)
opts.setdefault("trylast", False)
opts.setdefault("hookwrapper", False)
opts.setdefault("optionalhook", False)
表示pytest默认会用@pytest.hookimpl(tryfirst=False, trylast=False, hookwrapper=False, optionalhook=False)
标记hook方法。 Pytest在执行时会根据这个标签(装饰器)对这些hook方法进行不同的处理。
以hookwrapper
参数为例。如果钩子方法被标记为hookwrapper=True
,pytest会先执行yield
之前的部分,然后再执行其他同类型的钩子方法。这些方法执行完后,yield
之后的部分就会被执行。 (此功能就像 pytest fixtures。)
@pytest.hookimpl(hookwrapper=True)
的一个用法是可以计算一些hook方法的总耗时。
(此处,示例代码将计算测试收集时间。)
@pytest.hookimpl(hookwrapper=True)
def pytest_collection(session):
collect_timeout = 5
collect_begin_time = time.time()
yield
collect_end_time = time.time()
c_time = collect_end_time - collect_begin_time
if c_time > collect_timeout:
raise Exception('Collection timeout.')
我是pytest的新手。 @pytest.hookimpl 什么时候执行?它的完整用法是什么?我试过日志。对于(hookwrapper=true),就是打印,单次测试yield前后3组。
pytest 使用 @pytest.hookimpl
只是标记钩子方法。 (所以@pytest.hookimpl
是在pytest收集hook方法的时候执行的。)
如果你阅读了pytest的源代码,你可以找到这些代码:
def normalize_hookimpl_opts(opts):
opts.setdefault("tryfirst", False)
opts.setdefault("trylast", False)
opts.setdefault("hookwrapper", False)
opts.setdefault("optionalhook", False)
表示pytest默认会用@pytest.hookimpl(tryfirst=False, trylast=False, hookwrapper=False, optionalhook=False)
标记hook方法。 Pytest在执行时会根据这个标签(装饰器)对这些hook方法进行不同的处理。
以hookwrapper
参数为例。如果钩子方法被标记为hookwrapper=True
,pytest会先执行yield
之前的部分,然后再执行其他同类型的钩子方法。这些方法执行完后,yield
之后的部分就会被执行。 (此功能就像 pytest fixtures。)
@pytest.hookimpl(hookwrapper=True)
的一个用法是可以计算一些hook方法的总耗时。
(此处,示例代码将计算测试收集时间。)
@pytest.hookimpl(hookwrapper=True)
def pytest_collection(session):
collect_timeout = 5
collect_begin_time = time.time()
yield
collect_end_time = time.time()
c_time = collect_end_time - collect_begin_time
if c_time > collect_timeout:
raise Exception('Collection timeout.')