mehmetg mehmetg - 7 months ago 92
Python Question

Passing a command line argument to a py.test fixture as a parameter

Admittedly it is not the best way to do it to start with and more importantly the fixture parameters are resolved i.e. Options.get_option() is called before everything else.
Recommendations and suggestions would be appreciated.


class Options(object):
option = None

def get_option(cls):
return cls.option


@pytest.yield_fixture(scope='session', autouse=True)
def session_setup():
Options.option = pytest.config.getoption('--remote')

def pytest_addoption(parser):
parser.addoption("--remote", action="store_true", default=False, help="Runs tests on a remote service.")

@pytest.yield_fixture(scope='function', params=Options.get_option())
def setup(request):
if request.param is None:
raise Exception("option is none")


Don't use custom Options class but directly ask for option from config.

pytest_generate_tests may be used for parametrizing fixture-like argument for tests.

def pytest_addoption(parser):
    parser.addoption("--pg_tag", action="append", default=[],
                     help=("Postgres server versions. "
                           "May be used several times. "
                           "Available values: 9.3, 9.4, 9.5, all"))

def pytest_generate_tests(metafunc):
    if 'pg_tag' in metafunc.fixturenames:
        tags = set(metafunc.config.option.pg_tag)
        if not tags:
            tags = ['9.5']
        elif 'all' in tags:
            tags = ['9.3', '9.4', '9.5']
            tags = list(tags)
        metafunc.parametrize("pg_tag", tags, scope='session')

def pg_server(pg_tag):
    # pg_tag is parametrized parameter
    # the fixture is called 1-3 times depending on --pg_tag cmdline

Edit: Replaced old example with metafunc.parametrize usage.