Skip to content Skip to sidebar Skip to footer

Pytest - How To Parameterize Tests With Multiple Scenarios?

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_p

Solution 1:

One common practice is to set and read from environment variables to determine which platform you are running from.

For example, in the environment you can have a variable isProduction=1. Then in your code, you can check by os.environ['isProduction'] == 1.

You can even save the private ids in the environment for reasons such as safety. For example in the environment, you can have the following variables on nonproduction

id1="subnet-11f6xx0b65b5cxx38"
id2="subnet-116aaaf1ce207xx99"
id3"subnet-11xxfda8f811fxx77"

And another set on production machine

id1="subnet-08f6d70b65b5cxx38"
id2="subnet-0b6aaaf1ce207xx03"
id3="subnet-0e54fda8f811fxxd8"

in the code you do

import os
private_ids = [os.environ['id1'], os.environ['id2'], os.environ['id3']]

So you'll get the configs on each machine. Just make sure in your workflow/testflow the environment variables are correctly sourced.


Solution 2:

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

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


Post a Comment for "Pytest - How To Parameterize Tests With Multiple Scenarios?"