简体   繁体   中英

How to add command line parameter to pytest command

I cannot find how to add named command line parameter to pytest command, so I can execute tests with custom parameter available as a fixture.

pytest --my-parameter

def test_something(my_parameter):
    ...

In order to accomplish such behaviour the pytest_addoption shall be defined and new session level fixture in combination with pytestconfig fixture shall be used

# conftest.py
import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--my-parameter", action="store", default=None,
        help=("Parameter description")
    )


@pytest.fixture(scope='session')
def my_parameter(pytestconfig):
    """ Description of changes triggered by parameter. """
    param = pytestconfig.getoption("--my-parameter")
    if param is None:
        assert False, '--my-parameter parameter must be supplied in order to run test suite.'
    return param

# tests.py:
import pytest


def test_something(my_parameter):
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM