py.test 中夹具设置时间的细分
Breakdown of fixture setup time in py.test
我有一些 py.test 测试有多个依赖和参数化的夹具,我想测量每个夹具所花费的时间。但是,在带有 --durations
的日志中,它只显示 setup
的实际测试时间,但没有给我详细说明每个固定装置花费了多长时间。
没有任何内置的东西,但您可以通过在 conftest.py
文件中使用新的 pytest_fixture_setup hook 轻松实现自己。
下面是如何执行此操作的具体示例:
import logging
import time
import pytest
logger = logging.getLogger(__name__)
@pytest.hookimpl(hookwrapper=True)
def pytest_fixture_setup(fixturedef, request):
start = time.time()
yield
end = time.time()
logger.info(
'pytest_fixture_setup'
f', request={request}'
f', time={end - start}'
)
输出类似于:
2018-10-29 20:43:18,783 - INFO pytest_fixture_setup, request=<SubRequest 'some_data_source' for <Function 'test_ruleset_customer_to_campaign'>>, time=3.4723987579345703
魔法是hookwrapper:
pytest plugins can implement hook wrappers which wrap the execution of other hook implementations. A hook wrapper is a generator function which yields exactly once. When pytest invokes hooks it first executes hook wrappers and passes the same arguments as to the regular hooks.
我 运行 遇到的一个相当重要的陷阱是 conftest.py
必须位于项目的根文件夹中才能获取 pytest_fixture_setup
挂钩。
我有一些 py.test 测试有多个依赖和参数化的夹具,我想测量每个夹具所花费的时间。但是,在带有 --durations
的日志中,它只显示 setup
的实际测试时间,但没有给我详细说明每个固定装置花费了多长时间。
没有任何内置的东西,但您可以通过在 conftest.py
文件中使用新的 pytest_fixture_setup hook 轻松实现自己。
下面是如何执行此操作的具体示例:
import logging
import time
import pytest
logger = logging.getLogger(__name__)
@pytest.hookimpl(hookwrapper=True)
def pytest_fixture_setup(fixturedef, request):
start = time.time()
yield
end = time.time()
logger.info(
'pytest_fixture_setup'
f', request={request}'
f', time={end - start}'
)
输出类似于:
2018-10-29 20:43:18,783 - INFO pytest_fixture_setup, request=<SubRequest 'some_data_source' for <Function 'test_ruleset_customer_to_campaign'>>, time=3.4723987579345703
魔法是hookwrapper:
pytest plugins can implement hook wrappers which wrap the execution of other hook implementations. A hook wrapper is a generator function which yields exactly once. When pytest invokes hooks it first executes hook wrappers and passes the same arguments as to the regular hooks.
我 运行 遇到的一个相当重要的陷阱是 conftest.py
必须位于项目的根文件夹中才能获取 pytest_fixture_setup
挂钩。