pytest-dev / pytest-dev/pytest

Multiple use of fixture in a single test

Open
#2,703 21 comments 10 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: fixtures type: proposal
Dominant language
Python
Stars
14.5k
Forks
3.4k
Avg merge
2d 9h
Merged PRs (30d)
35

Description

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')).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files, tests, or entry points are named. Start by reviewing the proposed repeated-fixture syntax and the existing generator workaround, then inspect pytest's fixture resolution and cleanup behavior. Done would require an agreed API, defined scope and naming rules, preservation of existing fixtures, and tests for setup and finalization; the issue does not yet establish those decisions.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.