python - 根据 py.test (testinfra) 检查输出设置变量

标签 python testing pytest salt-stack

我正在尝试使 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/

相关文章:

java - 如何对 Java 8 流进行单元测试?

testing - gradle build 不生成 jacoco 测试报告

testing - 如何从 figwheel repl 的测试目录运行 cljs.test cases?

python - py.test : Mocking a datetime object that is constantly changing

python - Pytest django 数据库访问不允许使用 django_db 标记

python - python Mechanize 缓存功能是否与普通浏览器缓存功能相同?

python - 我如何将数据保存/插入到表中以从表单中获取值?

Python NetworkX——根据属性选项的数量自动设置节点颜色

python - pytest 如何模拟 s3fs.S3FileSystem 打开文件

python - 比较并计算python列表中的稀疏数组