首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pytest fixture相互干扰

Pytest fixture相互干扰
EN

Stack Overflow用户
提问于 2017-04-05 17:17:09
回答 1查看 451关注 0票数 2

我在Django中使用Pytest,结果出现了这种奇怪的行为。我有两个用户fixture,一个是另一个的超集。在我使用同一个测试用例中的两个fixture之前,一切都按预期进行。

灯具:

代码语言:javascript
复制
@pytest.fixture
def user_without_password():
    return User.objects.create_user(username=fake.name(), email=fake.email())

@pytest.fixture
def user_with_password(user_without_password):
    user = user_without_password
    user.set_password('topsecret')
    user.save()
    return user

测试

代码语言:javascript
复制
@pytest.mark.django_db()
def test_without_pass(user_without_password):
    assert not user_without_password.has_usable_password()


@pytest.mark.django_db()
def test_with_pass(user_with_password):
    assert user_with_password.has_usable_password()

# THIS FAILS!!
@pytest.mark.django_db()
def test_both(user_with_password, user_without_password):
    assert not user_without_password.has_usable_password()
    assert user_with_password.has_usable_password()

最后一个测试不起作用,因为显然user_with_passworduser_without_password最终是同一个对象。有没有办法确保它们每次都是新的对象?这种行为感觉有悖于直觉。

EN

回答 1

Stack Overflow用户

发布于 2017-11-14 05:42:18

pytest fixture被设计成高效的- i.e。如果一个fixture被多次请求,它只会被创建一次。这意味着您总是可以从另一个fixture请求fixture,并确保您使用的是与测试相同的对象。

此外,如果您像这样阅读您的user_with_password fixture:

给我没有密码的用户的装置没有密码的用户有一个password

  • Change

然后,返回它创建的没有密码的用户的fixture继续返回该用户是有意义的,但是现在它已经添加了密码。

如果您想解决这个问题,那么创建一个创建新对象的fixture,而不仅仅是单个对象,如下所示:

代码语言:javascript
复制
@pytest.fixture
def user_without_password_factory():
    def create_user_without_password(): 
        return User.objects.create_user(username=fake.name(), email=fake.email())
    return create_user_without_password

@pytest.fixture
def user_with_password_factory():
    def create_user_with_password(): 
        user = User.objects.create_user(username=fake.name(), email=fake.email())
        user.set_password('topsecret')
        user.save()
        return user
    return create_user_with_password

@pytest.mark.django_db()
def test_without_pass(user_without_password_factory):
    assert not user_without_password_factory().has_usable_password()


@pytest.mark.django_db()
def test_with_pass(user_with_password_factory):
    assert user_with_password_factory().has_usable_password()

# Succeeds!!
@pytest.mark.django_db()
def test_both(user_with_password_factory, user_without_password_factory):
    assert not user_without_password_factory().has_usable_password()
    assert user_with_password_factory().has_usable_password()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43226871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档