Reputation: 317
In pytest, the standard convention for passing cmdline args to tests is to add an option using parser.addoption
and define a fixture with the same name using @pytest.fixture()
.
Example:
# In conftest.py:
import pytest
def pytest_addoption(parser):
parser.addoption("--input1", action="store", default="default input1")
@pytest.fixture
def input1(request):
return request.config.getoption("--input1")
For this reason, our conftest.py
has become pretty huge (think AWS CLI). I was wondering if, instead of defining each option explicitly in conftest.py
, there is a way to parameterize and pass all command line arguments to the tests? Kind of like *kwargs
As per documents, pytest uses argparse
which provides parse_known_args function which outputs both known and unknown options. So technically this should be possible right?
Upvotes: 2
Views: 3637
Reputation: 16805
As far as I know, you still have to register each option in pytest_addoption
, but you can access all options by using a single fixture:
@pytest.fixture
def options(request):
yield request.config.option
This will provide the options namespace, and you can access each option using the dot notation:
def test_something(options):
print(options.input1)
(provided you have added the option input1
as shown in your question)
The name of the option is either the name you provided using the dest
argument in addoption
, or derived from option name itself if dest
is not given (by stripping the starting hyphens, and converting other characters not allowed in a variable name into underscores).
This behaves very similar to argparse.parse_known_args
, as it also returns a namespace with all options. Note that the namespace will additionally contain a number of other options from pytest
and pytest
plugins.
Upvotes: 1