【问题标题】:Reusing pytest fixture in the same test在同一个测试中重用 pytest 夹具
【发布时间】:2018-11-22 09:30:33
【问题描述】:

以下是使用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 个用户?

【问题讨论】:

    标签: python pytest


    【解决方案1】:

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

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

    @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")
    

    【讨论】:

    • 虽然看起来很奇怪,但您创建了一个问题,同时您也回答了这个问题。 :X
    • 我确实做到了。就在发布之前,我决定最后一次谷歌,我找到了答案。这是在过去两周内添加到 pytest 文档中的,所以我想我会分享我的发现。
    • 这让我发疯了,非常感谢您的回答。我在我发布的问题中链接了你的问题,这样其他人就不必穿过这个兔子洞了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多