在同一个测试中重用 pytest fixture

Reusing pytest fixture in the same test

下面是使用 user 夹具设置测试的测试代码示例。

@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

有没有办法在同一个测试中使用同一个夹具生成多个用户对象,如果我想,例如添加批量更改用户电子邮件的功能并且需要在测试前设置 10 个用户?

pytest 文档中有一个“factories as fixtures”部分解决了我的问题。

这个例子特别(copy/pasted 来自 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")