简体   繁体   中英

How can I specify a configuration for setting up pytest fixtures when I start the pytest test runner?

My tests rely on ids that are specific to a given environment (eg dev, qa, production)

In my tests I use fixtures to make a set of ids available over the session.

@pytest.fixture(scope="session", autouse=True)
def test_entities(request):
    test_entities = None
    path = os.path.join(base_path, "data/test_entities_dev.json")        ...
    ... 
    <Get from File>
    ...
    return test_entities

The test entities that I retrieve for a given test will depend on the environment. I would like to specify the file to open when I start my pytest session. eg "data/test_entities_qa.json" instead of "data/test_entities_dev.json". How can I do this with pytest?

If I understand you right, you can provide in each environment a different command line parameter. In that case, you should check out Okken's answer .

My complete solution borrowing from this SO post :

1) In conftest.py use pytest hooks

# conftest.py
def pytest_addoption(parser):
    parser.addoption("--env", action="store", default="dev")

2) in fixtures.py use this pattern:

@pytest.fixture(scope="session", autouse=True) 
def get_env(pytestconfig):
    return pytestconfig.getoption("env")

@pytest.fixture(scope="session", autouse=True)
def test_entities(request, get_env):
    filename = "data/dev_entities.json"
    if get_env == 'qa':
        filename = "data/qa_entities.json"
    elif get_env == 'prod':
         filename = "data/prod_entities.json"
    ...
    <Get entities from file>
    ...
    return entities

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM