5

Below is an example of test code that uses a user fixture to setup the test.

@pytest.fixture
def user():
    # Setup db connection
    yield User('test@example.com')
    # Close db connection

def test_change_email(user):
    new_email = 'new@example.com'
    change_email(user, new_email)
    assert user.email == new_email

Is there a way to generate multiple user objects in the same test using the same fixture, if I wanted to e.g. add functionality for changing user emails in bulk and needed 10 users setup before the test?

haeger
  • 623
  • 5
  • 14

1 Answers1

8

The pytest documentation had a "factories as fixtures"-section that solved my problem.

This example in particular (copy/pasted from the link):

@pytest.fixture
def make_customer_record():

    created_records = []

    def _make_customer_record(name):
        record = models.Customer(name=name, orders=[])
        created_records.append(record)
        return record

    yield _make_customer_record

    for record in created_records:
        record.destroy()


def test_customer_records(make_customer_record):
    customer_1 = make_customer_record("Lisa")
    customer_2 = make_customer_record("Mike")
    customer_3 = make_customer_record("Meredith")
haeger
  • 623
  • 5
  • 14
  • 5
    I did actually. Just before posting I decided to google one last time and I found my answer. This was added to the pytest docs in the last two weeks, so I thought I'd share my discovery. – haeger Jun 13 '18 at 06:18
  • This was driving me nuts, thank you so much for your answer. I linked to your question in the one that I posted so that way no one else has to go through this rabbit hole. – David Warshawsky Aug 18 '20 at 23:21