我正在尝试使testinfra测试文件更具可移植性,我想使用单个文件来处理prod / dev或test env的测试。为此,我需要从远程测试的机器获取一个值,我通过以下方式获得:
def test_ACD_GRAIN(host):
grain = host.salt("grains.item", "client_NAME")
assert grain['client_NAME'] == "test"我需要在测试文件的不同部分使用这个grain['client_NAME']值,因此我想将它存储在一个变量中。
不管怎么说,要这么做?
发布于 2018-02-28 06:04:35
有很多方法可以在测试之间共享状态。举几个例子:
使用会话范围的fixture
定义一个具有会话作用域的fixture,在该作用域中计算值。它将在第一个使用它的测试运行之前执行,然后在整个测试运行中被缓存:
# conftest.py
@pytest.fixture(scope='session')
def grain():
host = ...
return host.salt("grains.item", "client_NAME")只需在测试中使用fixture作为输入参数即可访问该值:
def test_ACD_GRAIN(grain):
assert grain['client_NAME'] == "test"使用pytest命名空间
定义一个具有会话作用域的自动使用装置,以便它在每个会话中自动应用一次,并将该值存储在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标志重新运行测试,以删除缓存并强制重新计算值。
https://stackoverflow.com/questions/49004671
复制相似问题