有很多方法可以在测试之间共享状态。仅举几例:
使用会话范围的固定装置
使用计算值的会话范围定义夹具。它将在使用它的第一个测试运行之前执行,然后将被缓存以供整个测试运行:
# conftest.py
@pytest.fixture(scope='session')
def grain():
host = ...
return host.salt("grains.item", "client_NAME")
只需在测试中使用夹具作为输入参数即可访问该值:
def test_ACD_GRAIN(grain):
assert grain['client_NAME'] == "test"
使用pytest命名空间
定义一个具有会话范围的 autouse 固定装置,以便每个会话自动应用一次,并将值存储在 pytest 命名空间中。
# conftest.py
import pytest
def pytest_namespace():
return {'grain': None}
@pytest.fixture(scope='session', autouse=True)
def grain():
host = ...
pytest.grain = host.salt("grains.item", "client_NAME")
它将在第一次测试运行之前执行。在测试中,只需调用pytest.grain 即可获取值:
import pytest
def test_ACD_GRAIN():
grain = pytest.grain
assert grain['client_NAME'] == "test"
pytest 缓存:在测试运行之间重用值
如果值在两次测试运行之间没有变化,你甚至可以在磁盘上持久化:
@pytest.fixture
def grain(request):
grain = request.config.cache.get('grain', None)
if not grain:
host = ...
grain = host.salt("grains.item", "client_NAME")
request.config.cache.set('grain', grain)
return grain
现在测试不需要在不同的测试运行中重新计算值,除非您清除磁盘上的缓存:
$ pytest
...
$ pytest --cache-show
...
grain contains:
'spam'
使用--cache-clear 标志重新运行测试以删除缓存并强制重新计算值。