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.
Command-line arguments are given after the name of the program in command-line shell of Operating Systems. 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.
It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.
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)
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.
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