【问题标题】:Set a variable based on a py.test (testinfra) check output根据 py.test (testinfra) 检查输出设置变量
【发布时间】:2018-08-06 20:43:50
【问题描述】:

我正在尝试使 testinfra 测试文件更便携,我想使用单个文件来处理产品/开发或测试环境的测试。 为此,我需要从远程测试的机器上获取一个值,我可以通过:

def test_ACD_GRAIN(host):
    grain = host.salt("grains.item", "client_NAME")
    assert grain['client_NAME'] == "test"

我需要在测试文件的不同部分使用这个 grain['client_NAME'] 值,因此我想将它存储在一个变量中。

无论如何要这样做?

【问题讨论】:

    标签: python testing pytest salt


    【解决方案1】:

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

    使用会话范围的固定装置

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

    # 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 标志重新运行测试以删除缓存并强制重新计算值。

    【讨论】:

    • 非常感谢,我刚刚发现了 python,它看起来确实很棒!
    • 很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2016-04-16
    • 2019-12-16
    • 1970-01-01
    • 2021-02-11
    • 2021-01-17
    • 2022-06-29
    相关资源
    最近更新 更多