基于设置变量py.测试(testinfra)检查输出

2024-06-01 05:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使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']值,因此我想将它存储在一个变量中。在

不管怎样要这么做?在


Tags: 文件namedevtestenvclient机器host
1条回答
网友
1楼 · 发布于 2024-06-01 05:18:25

有很多方法可以在测试之间共享状态。举几个例子:

使用会话范围的fixture

使用计算值的会话范围定义fixture。它将在第一个使用它的测试运行之前执行,然后将在整个测试运行期间缓存:

# conftest.py
@pytest.fixture(scope='session')
def grain():
    host = ...
    return host.salt("grains.item", "client_NAME")

只需将fixture用作测试中的输入参数即可访问该值:

^{pr2}$

使用pytest命名空间

定义一个带有会话作用域的autouse fixture,这样每个会话自动应用一次,并将值存储在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标志重新运行测试,以删除缓存并强制重新计算值。在

相关问题 更多 >