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?
It is possible to pass custom command line arguments to the test module.
To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.
You don't need to pass command line parameters to your JUnit execution. Instead your test methods should build/prepare everything and call your new myClass(...) constructor with the parameters your original program would do when using command line parameters.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With