8

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.

nigeu
  • 133
  • 2
  • 8
  • Look the [official documentation](https://docs.python.org/3.5/library/argparse.html) – Chiheb Nexus Apr 02 '17 at 19:16
  • This is a good question (and it is unrelated to argparse or sys.argv like the only other comments here seem to think), but I did find the answer at [this](https://stackoverflow.com/q/13275738/3100515) question (not the accepted answer, the other one). – Ajean Oct 24 '17 at 00:47

2 Answers2

4

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)
Guy Markman
  • 426
  • 1
  • 4
  • 14
4

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.

User
  • 4,023
  • 4
  • 37
  • 63