微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PyTest 案例 1:将以下 UnitTest 代码转换为 PyTest:

如何解决PyTest 案例 1:将以下 UnitTest 代码转换为 PyTest:

如何将以下 unitest 代码转换为 pytest 代码

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 包可以帮助您自动执行此操作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。