Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest: How to access command line arguments outside of a test

Tags:

python

pytest

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.

like image 214
nigeu Avatar asked Apr 02 '17 19:04

nigeu


People also ask

How do I get command line arguments?

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.

Can you pass 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.


2 Answers

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)
like image 83
Guy Markman Avatar answered Oct 23 '22 05:10

Guy Markman


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.

like image 20
Khan Avatar answered Oct 23 '22 05:10

Khan