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

标签 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'}]
我需要能够将此集合传递给 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/

相关文章:

python - 模拟父类(super class) __init__ 方法或父类(super class)作为一个整体进行测试

python - 如何安装py.test?

python - 使用 Jenkins 中的管道执行 pytest

python - 整个 session 的 pytest 超时

python-3.x - 如何将命令行参数从pytest传递给代码

python - PyCharm + cProfile + py.test --> pstat 快照 View +调用图为空

python - pytest - 从运行测试的 CLI 命令指定日志级别

python - 如果另一个失败,pytest 可以运行测试吗?

python - Moto 警告 : Use ec2_backend. describe_images() 为您的测试找到合适的图像

python - 确保 py.test 在 sys.path 中包含应用程序目录