Reputation: 145
I would like to access command line arguments passed to pytest from within a non-test class.
I have added the following to my conftest.py file
def pytest_addoption(parser): # pragma: no cover
"""Pytest hook to add custom command line option(s)."""
group = parser.getgroup("Test", "My test option")
group.addoption(
"--stack",
help="stack", metavar="stack", dest='stack', default=None)
But I can not work out how to access the value passed on the command line. I have found code on how to access it from a fixture, but I would like to access it from a method or class that is not part of the test case.
Upvotes: 8
Views: 5370
Reputation: 4211
Yes you could add one more pytest hook pytest_configure
to your conftest.py as follows:
stack = None
def pytest_configure(config):
global stack
stack = config.getoption('--stack')
Now your argument stack is available at global level.
Upvotes: 5
Reputation: 446
You can access the parameters with sys.argv
.
It will return a list of all the arguemnts you sent wrote when you called using the command line.
For example
def pytest_addoption(parser): # pragma: no cover
"""Pytest hook to add custom command line option(s)."""
params = sys.argv[1:]
group = parser.getgroup("Test", "My test option")
group.addoption(
"--stack",
help="stack", metavar="stack", dest='stack', default=None)
Upvotes: 4