问题描述
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
"""Test creating a new user with an email is successful"""
email = "test@londonappdev.com"
password = "Password123"
user = get_user_model().objects.create_user(email=email,password=password)
self.assertEqual(user.email,email)
self.assertTrue(user.check_password(password))
def test_new_user_email_normalized(self):
"""normalize Email"""
email = "teast@AIOwoev.com"
password = "Password123"
user = get_user_model().objects.create_user(email=email,password=password)
self.assertEqual(user.email,email.lower())
def test_new_user_invalid_email(self):
"""Creating user with no email fails"""
with self.assertRaises(ValueError):
get_user_model().objects.create_user(None,"test123")
查询:
-
我已将以下测试写入 pytest 但有问题 test_new_user_invalid_email,如何改正?
-
由于我是编写 pytest 的新手,所以我也是 test_create_user_with_email_successful 和 test_new_user_email_normalized 写对了吗?
def test_create_user_with_email_successful(client) -> None:
email = "test@londonappdev.com"
password = "Password123"
user = get_user_model().objects.create_user(email=email,password=password)
assert user.email == email
assert user.check_password(password)
def test_new_user_email_normalized(self):
"""normalize Email"""
email = "teast@AIOwoev.com"
password = "Password123"
user = get_user_model().objects.create_user(email=email,password=password)
assert user.email == email.lower()
def test_new_user_invalid_email(self):
"""Creating user with no email fails"""
with pytest.raises(ValueError) as e:
get_user_model().objects.create_user(None,"test123")
解决方法
对我来说看起来很结实!您可能不需要 pytest.raises 中的 as e
除非您想对异常进行断言
顺便说一下,有一些 pip 包可以帮助您自动执行此操作。