Skip to content

Multiple use of fixture in a single test #2703

Open
@dysfungi

Description

@dysfungi

Feature request to add the ability to use a fixture more than once in the test function arguments. Off the top of my head, appending a number to the fixture name could be a decent API. Obviously don't override existing fixtures and perhaps require the appended numbers to be ascending.

@pytest.fixture
def rand_int():
    yield random.randint(0, 100)

def test_rand_ints(rand_int0, rand_int1, rand_int2):
    # do something with 3 random integers

I can get around this by creating a fixture that generates values.

@python.fixture
def randints():
    def gen(count):
        for x in range(count):
            yield random.randint(0, 100)
    yield gen

def test_randint_gen(randints):
    r1, r2, r3 = randints(3)
    # do something with 3 random integers

I realize these examples could just be utility functions, but consider the following examples that require cleanup.

@python.fixture
def user():
    u = models.User()
    u.commit()
    yield u
    u.delete()

@python.fixture
def usergen(request):
    def gen(count):
        for x in range(count):
            u = models.User()
            u.commit()
            request.addfinalizer(lambda u=u: u.delete())
            yield u

    yield gen

def test_user(user0, user1, user2):
    # do something with 3 users

def test_usergen(usergen):
    user1, user2, user3 = usergen(3)
    # do something with 3 users

I think this deserves debate as my suggestion requires less code and I believe to be more intuitive.

It should be noted that adding scope to either solution will be confusing and probably not recommended (e.g., @fixture(scope='module')).

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: fixturesanything involving fixtures directly or indirectlytype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions