Andrea
Andrea

Reputation: 805

How to specify more than one option in pytest config [pytest_addoption]

Is it possible to add more than one option in the command line for pytest? I see that I can add the pytest_addoption hook to the conftest.py file, but I'm wondering how to go about adding more than one option(s).

Upvotes: 17

Views: 37855

Answers (3)

Abdul Batin
Abdul Batin

Reputation: 1

def pytest_addoption(parser):
    print('conftest method')
    parser.addoption("--hostip", action = "store",default = "127.0.0.1",help ="host ip address")
    parser.addoption("--port", action="store", default="5000", help="port")

 @pytest.fixture
 def get_param(request):
    config_param = {}
     config_param["host"] = request.config.getoption("--hostip")
    config_param["port"] = request.config.getoption("--port")
    return config_param

After this how do we use the get_param function? I want that to load data elsewhere

Upvotes: -1

hardik gosai
hardik gosai

Reputation: 398

you can add option by this way as shown below :

def pytest_addoption(parser):
    print('conftest method')
    parser.addoption("--hostip", action = "store", default = "127.0.0.1", help ="host ip address")
    parser.addoption("--port", action="store", default="5000", help="port")

@pytest.fixture
def get_param(request):
    config_param = {}
    config_param["host"] = request.config.getoption("--hostip")
    config_param["port"] = request.config.getoption("--port")
    return config_param

Upvotes: 7

Frank T
Frank T

Reputation: 9066

You can specify arbitrarily many command-line options using the pytest_addoption hook.

Per the pytest hook documentation:

Parameters: parser – To add command line options, call parser.addoption(...). To add ini-file values call parser.addini(...).

The pytest_addoption hook is passed a parser object. You can add as many command-line options as you want by calling parser.addoption(...) as many times as you want.

So an example of adding two parameters is as simple as:

def pytest_addoption(parser):
    parser.addoption('--foo', action='store_true', help='Do foo')
    parser.addoption('--bar', action='store_false', help='Do not do bar')

And like any other py.test hook this needs to go into a conftest.py file.

Upvotes: 19

Related Questions