Search code examples
pythondependency-injectionpytestfixtures

Pytest use same fixture twice in one function


For my web server, I have a login fixture that create a user and returns the headers needed to send requests. For a certain test, I need two users. How can I use the same fixture twice in one function?

from test.fixtures import login


class TestGroups(object):

    def test_get_own_only(self, login, login):
         pass

Solution

  • 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.param
    
    second = first
    
    def test_double_fixture(first, second):
        assert False, '{} {}'.format(first, second)