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.

2
  • Look the official documentation Commented Apr 2, 2017 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 question (not the accepted answer, the other one). Commented Oct 24, 2017 at 0:47

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.