【问题标题】:PyTest Case 1: Convert following UnitTest Code into PyTest:PyTest 案例 1:将以下 UnitTest 代码转换为 PyTest:
【发布时间】:2021-01-06 21:23:41
【问题描述】:

如何将以下 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")

【问题讨论】:

    标签: django pytest pytest-django


    【解决方案1】:

    对我来说看起来很可靠!你可能不需要 pytest.raises 中的as e 除非你想断言一些关于异常的东西

    顺便说一下,有一些 pip 包可以帮助您自动执行此操作。

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2022-06-13
      • 2018-11-08
      • 2021-03-26
      • 1970-01-01
      相关资源
      最近更新 更多