@pytest.hookimpl 何时执行

rev*_*van 4 pytest

我是 pytest 新手。@pytest.hookimpl 何时执行?而它的完整用法又是什么呢?我尝试过使用日志。对于(hookwrapper=true),它是打印,单个测试的3组前后产量。

cur*_*usY 8

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)
Run Code Online (Sandbox Code Playgroud)

这意味着 pytest 默认情况下会标记钩子方法@pytest.hookimpl(tryfirst=False, trylast=False, hookwrapper=False, optionalhook=False)Pytest在执行时会根据这个标签(装饰器)对这些钩子方法进行不同的处理。

hookwrapper参数为例。如果钩子方法标记为hookwrapper=True,则 pytest 将先执行前面的部分yield,然后再执行其他相同类型的钩子方法。yield这些方法执行完之后,就会执行后面的部分。(此功能就像 pytest 装置一样。)

的一种用途@pytest.hookimpl(hookwrapper=True)是可以计算某些钩子方法的总成本时间。(这里,示例代码将计算测试收集时间。)

@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.')
Run Code Online (Sandbox Code Playgroud)