我的
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_yearofbirth
和 def 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
并不总是返回“真实”年龄——这对我的班级来说并不重要。
我会这样做:
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)
添加迈克尔的答案:为了测试验证,您需要调用对象的 full_clean 方法。保存对象时,Django 不会验证模型。
from django.core.exceptions import ValidationError
def test_year_of_birth(self):
obj = Personal.objects.create(lastname = 'Einstein', firstname = 'Albert', yearofbirth = 1879)
self.assertRaises(ValidationError, obj.full_clean)
请参阅此答案了解更多信息。
我确实喜欢这个希望它对你有用
from django.core.exceptions import ValidationError
def test_year_of_birth(self):
person = Personal.objects.create(lastname = 'Einstein', firstname = 'Albert', yearofbirth = 1879)
self.assertRaises(ValidationError, person.full_clean)