Pytest use same fixture twice in one function Pytest use same fixture twice in one function python python

Pytest use same fixture twice in one function


An alternative is just to copy the fixture function. This is both simple and correctly handles parameterized fixtures, calling the test function with all combinations of parameters for both fixtures. This example code below raises 9 assertions:

import pytest@pytest.fixture(params=[0, 1, 2])def first(request):    return request.paramsecond = firstdef test_double_fixture(first, second):    assert False, '{} {}'.format(first, second)


I do it with Dummy class which will implement fixture functionality. Then just call it from your test. Provide clarify method name to better understand what is your test doing.

import pytest@pytest.fixturedef login():    class Dummy:        def make_user(self):            return 'New user name'    return Dummy()def test_something(login):    a = login.make_user()    b = login.make_user()    assert a == b


The trick is to use mark.parametrize with the "indirect" switch, thus:

@pytest.fixturedef data_repeated(request):    return [deepcopy({'a': 1, 'b': 2}) for _ in range(request.param)]@pytest.mark.parametrize('data_repeated', [3], indirect=['data_repeated'])def test(data_repeated):    assert data_repeated == [        {'a': 1, 'b': 2},        {'a': 1, 'b': 2},        {'a': 1, 'b': 2}]