简体   繁体   English

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

[英]PyTest Case 1: Convert following UnitTest Code into PyTest:

How to convert following unitest code into a pytest code如何将以下 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")

Query:询问:

  • I have written following tests into a pytest but has issue with test_new_user_invalid_email, how to correct it?我已将以下测试写入 pytest 但 test_new_user_invalid_email 有问题,如何纠正?

  • As I am new in wrting pytest, so is the test_create_user_with_email_successful and test_new_user_email_normalized written correctly?由于我是编写 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")

looks pretty solid to me!对我来说看起来很坚固! you probably don't need the as e in the pytest.raises unless you'd like to assert something about the exception您可能不需要 pytest.raises 中的as e ,除非您想对异常进行断言

By the way, there are a few pip packages that can help you do this automatically.顺便说一句,有一些 pip 包可以帮助您自动执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM