我在Django中使用Pytest,结果出现了这种奇怪的行为。我有两个用户fixture,一个是另一个的超集。在我使用同一个测试用例中的两个fixture之前,一切都按预期进行。
灯具:
@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测试
@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_password和user_without_password最终是同一个对象。有没有办法确保它们每次都是新的对象?这种行为感觉有悖于直觉。
发布于 2017-11-14 05:42:18
pytest fixture被设计成高效的- i.e。如果一个fixture被多次请求,它只会被创建一次。这意味着您总是可以从另一个fixture请求fixture,并确保您使用的是与测试相同的对象。
此外,如果您像这样阅读您的user_with_password fixture:
给我没有密码的用户的装置没有密码的用户有一个password
然后,返回它创建的没有密码的用户的fixture继续返回该用户是有意义的,但是现在它已经添加了密码。
如果您想解决这个问题,那么创建一个创建新对象的fixture,而不仅仅是单个对象,如下所示:
@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()https://stackoverflow.com/questions/43226871
复制相似问题