pytest.mark.parametrize从列表中读取以动态生成测试

use*_*189 3 pytest

我有一个读取yaml文件并生成测试迭代的函数,该字典如下面的字典列表所示:

   Iterations = lib_iterations()

   print Iterations

   Iterations = [{'mode':1,'format':5,'ip':'192.16.1.103'},
              {'mode':2,'format':6,'ip':'192.16.1.104'},
              {'mode':2,'format':8,'ip':'192.16.1.110'},
              {'mode':6,'format':2,'ip':'192.16.1.105'},
              {'mode':5,'format':7,'ip':'192.16.1.102'},
              {'mode':4,'format':2,'ip':'192.16.1.101'}]
Run Code Online (Sandbox Code Playgroud)

我需要能够将此设置传递给pytest.mark.parametrize才能为列表中的每个迭代/每行生成一个测试。

在调用函数lib_iterations之前,我不知道字典键,该函数生成此字典列表。

有关如何执行此操作的任何想法?

谢谢AB

小智 7

如果您的问题是如何将迭代列表传递给pytest参数装饰器,则可以执行以下操作:

@pytest.mark.parametrize('testdata', [i for i in Iterations])
Run Code Online (Sandbox Code Playgroud)

如果测试模块中的迭代内容未知,则可以使用pytest_generate_tests钩子。在该钩子函数中,您可以加载yaml文件并将其内容传递给metafunc.parametrize

import yaml

def pytest_generate_tests(metafunc):
    if 'testdata' in metafunc.fixturenames:
        with open("testdata.yml", 'r') as f:
            Iterations = yaml.load(f)
            metafunc.parametrize('testdata', [i for i in Iterations])
Run Code Online (Sandbox Code Playgroud)

使用此治具的测试功能:

def test_it(testdata):
    print testdata
Run Code Online (Sandbox Code Playgroud)