我正在尝试使 testinfra 测试文件更便携,我想使用单个文件来处理 prod/dev 或测试环境的测试。 为此,我需要从远程测试的机器获取一个值,我通过以下方式获取:
def test_ACD_GRAIN(host):
grain = host.salt("grains.item", "client_NAME")
assert grain['client_NAME'] == "test"
我需要在测试文件的不同部分使用此 grain['client_NAME']
值,因此我想将其存储在变量中。
无论如何都要这样做吗?
最佳答案
有很多方法可以在测试之间共享状态。仅举几例:
使用 session 范围的固定装置
定义一个具有计算值的 session 范围的装置。它将在使用它的第一个测试运行之前执行,然后将在整个测试运行中进行缓存:
# 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
命名空间
定义一个具有 session 范围的自动使用装置,因此每个 session 会自动应用一次并将值存储在 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
标志重新运行测试以删除缓存并强制重新计算值。
关于python - 根据 py.test (testinfra) 检查输出设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004671/