user3732361 user3732361 - 1 year ago 120
Python Question

How to run pytest.main("-v") when needs some command line arguments in order for the test functions to run?

I have two scripts. One script parses all the arguments and decides the control flow of the script. Another script has all the test functions defined and I wanted to use pytest module to invoke the '' and run all the tests. But there are some arguments that I need to pass down to before the test cases run.

One way I could think of was to write to a file and have read all the arguments from that file when it first runs. Please let me know if you have any other ideas. Your help is appreciated. Thank you!

Answer Source

If I understand your question correctly, you can create a file and add options to pytest using pytest_addoption hook:

def pytest_addoption(parser):
        help="first argument")

Now py.test understands this option, so if you execute:

py.test --arg1 hey

then tests in the same directory and below can access the option like this:

def test_foo(request):
    arg1 = request.config.getoption('arg1')
    assert arg1 == "hey"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download