SaurabhD
SaurabhD

Reputation: 23

pytest - How can I pass pytest addoption value to pytest parameterize?

I have to to pass an argument in my pytest command which I am storing in pytest addoption. I want to use these values in the pytest parametrize function.

Command:

pytest --range-from 3 --range-to 5 test.py

conftest.py:

def pytest_addoption(parser):
    parser.addoption("--range-from", action="store", default="default name")
    parser.addoption("--range-to", action="store", default="default name")

test.py:

@pytest.mark.parametrize('migration_id', migration_list[range-from:range-to])
def test_sync_with_migration_list(migration_id):
    migration_instance = migration.parallel(migration_id=migration_id)
    migration_instance.perform_sync_only()

I want to use the value of range-from and range-to inside parametrize.

I am not able to use these values. Please suggest how can this can be done.

Upvotes: 2

Views: 3629

Answers (2)

Chanda Korat
Chanda Korat

Reputation: 2561

One simple way is assign your command line argument to environment variable and use wherever you want. I am not sure in which manner you want to use the variables then so here i am putting simple print statement inside test.

conftest.py

def pytest_addoption(parser):
    parser.addoption("--range-from", action="store", default="default name") #Let's say value is :5
    parser.addoption("--range-to", action="store", default="default name") #Lets's say value is 7

def pytest_configure(config):
    os.environ["range_from"]=config.getoption("range-from") 
    os.environ["range_to"]=config.getoption("range-to")

test.py:

@pytest.mark.parametrize('migration_id', [os.getenv("range_from"),os.getenv("range_to")])
def test_sync_with_migration_list(migration_id):
    print(migration_id)

Output :
5
7

Hope it would help !!

Upvotes: 4

MrBean Bremen
MrBean Bremen

Reputation: 16815

You cannot directly access the options from parametrize, because they not available at load time. You can instead configure the parametrization at run time in pytest_generate_tests, where you have acces to the config from the metafunc argument:

test.py

@pytest.hookimpl
def pytest_generate_tests(metafunc):
    if "migration_id" in metafunc.fixturenames:
        # any error handling omitted
        range_from = int(metafunc.config.getoption("--range-from"))
        range_to = int(metafunc.config.getoption("--range-to"))
        metafunc.parametrize("migration_id",
                             migration_list[range_from:range_to])


def test_sync_with_migration_list(migration_id):
    migration_instance = migration.parallel(migration_id=migration_id)
    migration_instance.perform_sync_only()

Upvotes: 2

Related Questions