我有一个函数可以读取 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'}]
我需要能够将此集合传递给 pytest.mark.parametrize
为列表中的每个迭代/每一行生成一个测试。在调用函数
lib_iterations
之前我不知道字典键生成此字典列表。关于如何做到这一点的任何想法?
最佳答案
如果您的问题是如何将迭代列表传递给 pytest 参数化装饰器,那么您可以这样做:
@pytest.mark.parametrize('testdata', [i for i in Iterations])
如果测试模块中迭代的内容未知,则可以使用 pytest_generate_tests
钩。在该 Hook 函数中,您可以加载 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])
使用此 fixture 的测试功能:def test_it(testdata):
print testdata
关于pytest - 使用 pytest.mark.parametrize 从列表中读取动态生成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30632841/