Pytest-如何在多种情况下对测试进行参数化? [英] Pytest - How to Parameterize tests with multiple scenarios?

查看:89
本文介绍了Pytest-如何在多种情况下对测试进行参数化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pytest,boto3和aws,并希望通过参数化测试具有动态断言.如何改进此代码以仅在特定的一组子网内断言?

I'm using pytest ,boto3 and aws and want to have dynamic assertions with parameterized tests. How to improve this code to only assert on a specific group of subnetids?

production_private_ids = ["subnet-08f6d70b65b5cxx38", "subnet-0b6aaaf1ce207xx03", "subnet-0e54fda8f811fxxd8"]) ....
nonproduction_private_ids = ["subnet-11f6xx0b65b5cxx38", "subnet-116aaaf1ce207xx99", "subnet-11xxfda8f811fxx77"]) ....


@pytest.mark.parametrize("subnet", ["production_private_ids", "nonproduction_private_ids", "nonproduction_public_ids","production_public_ids ")

# if environment = production, then only check if production_private_ids exists in team_subnet

def test_sharing_subnets_exist(subnet,accountid):
    team_subnet =  get_team_subnets(accountid)
    assert subnet in team_subnet


# if environment = nonproduction, then only check if nonproduction_private_ids exists in team_subnet
def test_sharing_subnets_exist(subnet,accountid):
    team_subnet =  get_team_subnets(accountid)
    assert subnet in team_subnet

推荐答案

如果需要对参数化执行其他逻辑,则可以通过metafunc对测试进行参数化.示例:

You can parametrize the tests via metafunc if you need to execute additional logic on parametrization. Example:

import os
import pytest

production_private_ids = [...]
nonproduction_private_ids = [...]


def pytest_generate_tests(metafunc):
    # if the test has `subnet` in args, parametrize it now
    if 'subnet' in metafunc.fixturenames:
        # replace with your environment check
        if os.environ.get('NAME', None) == 'production':
            ids = production_private_ids
        else:
            ids = nonproduction_private_ids
        metafunc.parametrize('subnet', ids)


def test_sharing_subnets_exist(subnet, accountid):
    team_subnet =  get_team_subnets(accountid)
    assert subnet in team_subnet

现在运行 pytest ... 将仅检查非生产ID,而 NAME =生产"pytest ... 将仅检查生产ID.

Now running pytest ... will check only non-production IDs, while NAME="production" pytest ... will check only production IDs.

这篇关于Pytest-如何在多种情况下对测试进行参数化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆