【问题标题】:Django how to test model functions with validatorDjango如何使用验证器测试模型函数
【发布时间】:2021-07-23 16:15:09
【问题描述】:

我的models.py 是这样的:

def validate_yearofbirth(value):
    text = str(value)
    if len(text) < 4 or len(text) > 4 or value < 1900:
        raise ValidationError('Please insert your year of birth!')

class Personal(models.Model):
    firstname = models.CharField(max_length = 100)
    lastname = models.CharField(max_length = 100)
    yearofbirth = models.PositiveIntegerField(validators = [validate_yearofbirth], null = True)

    @property
    def fullname(self):
        return '{}, {}'.format(self.lastname, self.firstname)
    
    def __str__(self):
        return self.fullname

    @property
    def age(self):
        year = datetime.now().year
        age = year - self.yearofbirth
        return age

有人知道如何为def validate_yearofbirthdef age 编写测试吗?我只设法为def fullname 编写了一个测试,但我还没有弄清楚如何为不是def __str__(self) 的函数编写测试。

我的test_models.py 文件如下所示:

class TestModel(TestCase):

    def test_personal_str(self):
        fullname = Personal.objects.create(nachname = 'Last Name', vorname = 'First Name')

        self.assertEqual(str(fullname), 'Last Name, First Name')

您也可以忽略return age 并不总是返回“真实”年龄这一事实 - 这对我的班级并不重要。

【问题讨论】:

    标签: python django testing django-models django-testing


    【解决方案1】:

    我会这样做:

    from django.test import TestCase
    from myapp.models import Personal
    
    class TestPersonalModel(TestCase):
    
        def setUp(self):
            Personal.objects.create(lastname = 'Schuhmacher', firstname = 'Michael', yearofbirth=1969)
    
        def test_fullname(self):
            person = Personal.objects.get(lastname="Schuhmacher")
            self.assertEqual(person.fullname, 'Schuhmacher, Michael')
        
        def test_age(self):
            person = Personal.objects.get(lastname="Schuhmacher")
            self.assertEqual(person.age, 52)
    
        def test_year_of_birth_validator(self):
            with self.assertRaises(ValidationError):
                Personal.objects.create(lastname = 'Einstein', firstname = 'Albert', yearofbirth=1879)
    
    

    【讨论】:

    • 如果yearofbirth
    猜你喜欢
    • 2022-10-30
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多