Skip to content Skip to sidebar Skip to footer

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-fr

Solution 1:

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

defpytest_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 7defpytest_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")])deftest_sync_with_migration_list(migration_id):
    print(migration_id)

Output :
57

Hope it would help !!

Solution 2:

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.hookimpldefpytest_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])


deftest_sync_with_migration_list(migration_id):
    migration_instance = migration.parallel(migration_id=migration_id)
    migration_instance.perform_sync_only()

Post a Comment for "Pytest - How Can I Pass Pytest Addoption Value To Pytest Parameterize?"