user3732361 user3732361 - 1 month ago 7
Python Question

How to run pytest.main("-v test_script2.py") when test_script2.py 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 'test_script2.py' and run all the tests. But there are some arguments that I need to pass down to test_script2.py before the test cases run.

One way I could think of was to write to a file and have test_script2.py 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

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

def pytest_addoption(parser):
    parser.addoption(
        '--arg1',
        dest="arg1",
        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"