Pytest: Passing on multiple parameters to a fixture

Viewed 1897

I would like to use a flexible fixture for a data call that can be reused across the test suite. For this purpose I like to ideally pass on more than on parameter. However the code fragment below generally works only for one parameter:

@pytest.fixture
def getData(request):
    """Variable data query"""
    data_detail = request.param

In the pytest documentation there is no hint that more than one parameter may work, e.g. such as:

@pytest.fixture
def getData(request):
    """Variable data query"""
    data_detail = request.param[0]
    time_detail = request.param[1]

Does anyone have a hint how to build a pytest fixture to which several parameters / arguments may be passed on?

1 Answers

You can use a tuple or a dict as the fixture parameter:

@pytest.fixture
def tuple_params(request):
    yield sum(request.param)


@pytest.mark.parametrize("tuple_params", [(1, 2, 3)], indirect=True)
def test_tuple_params(tuple_params):
    print(tuple_params)  # 6


@pytest.fixture
def dict_params(request):
    yield f"{request.param['a']}_{request.param['b']}"


@pytest.mark.parametrize("dict_params", [{"a": "foo", "b": "bar"}],
                         indirect=True)
def test_dict_params(dict_params):
    print(dict_params)  # foo_bar

Generally, the parameter can be any object, so you can always put your fixture parameters in a suitable object.

With a tuple or a list parameter, you can also access the values per index as in your example.

Related