在同一测试中重用 pytest 夹具

hae*_*ger 5 python pytest

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
Run Code Online (Sandbox Code Playgroud)

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

hae*_*ger 8

pytest 文档中有一个“工厂作为固定装置”部分解决了我的问题。

特别是这个示例(从链接复制/粘贴):

@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")
Run Code Online (Sandbox Code Playgroud)

  • 我确实这么做了。就在发帖之前,我决定最后一次谷歌搜索,我找到了答案。这是在过去两周内添加到 pytest 文档中的,所以我想我应该分享我的发现。 (5认同)