Reputation: 793
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
Reputation: 66251
You have multiple ways of accessing the config object:
request.config
attribute of the request
fixture objectpytestconfig
fixturepytest.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.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