SuperGeo
SuperGeo

Reputation: 793

Pass command line arguments to test modules

When running python scripts, we can use sys.argv to get command line arguments and use it anywhere in our python code.

When running pytest, we can use pytest_addoption to add command line arguments, but it seems to me that we can only use them inside either tests or fixtures, where we can access the option through anything that exposes the config object.

In my case, however I would like to be able to access command line options from the test module body itself.

Is it possible to somehow access pytest's config without requiring any fixture?

Upvotes: 7

Views: 3857

Answers (1)

hoefling
hoefling

Reputation: 66251

You have multiple ways of accessing the config object:

  1. Via request.config attribute of the request fixture object
  2. Via pytestconfig fixture
  3. Via pytest.config (the config object becomes a module attribute in the pytest_configure hook invocation - use with caution in early init phase, but you can fully rely on it in tests). This is presumably what you are looking for.
  4. Via node.config attribute of any object that subclasses _pytest.nodes.Node, for example Session object, test item nodes etc.

Example usage:

# conftest.py
def pytest_addoption(parser):
    parser.addoption('--spam', action='store_true', default=False, help='some flag')
# test_spam.py

import pytest


print('accessing option on module level', pytest.config.getoption('--spam'))

def util():
    print('accessing option from non-test function', pytest.config.getoption('--spam'))


@pytest.fixture
def myfixture(request, pytestconfig):
    print('accessing option in fixture via request', request.config.getoption('--spam'))
    print('accessing option in fixture via session', request.session.config.getoption('--spam'))
    print('accessing option in fixture via pytestconfig', pytestconfig.getoption('--spam'))


def test_spam(request, pytestconfig):
    print('accessing option in fixture via request', request.config.getoption('--spam'))
    print('accessing option in fixture via session', request.session.config.getoption('--spam'))
    print('accessing option in fixture via pytestconfig', pytestconfig.getoption('--spam'))

etc.

Upvotes: 12

Related Questions