Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to test model functions with validator

My models.py is looking like this:

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

Anyone know how to write a test for def validate_yearofbirth and for def age? I only managed to write a test for def fullname, but I haven't figured out how to write a test for a function which is not def __str__(self).

My test_models.py file for this class is looking like this:

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')

Also you can ignore the fact that return age doesn't always return the "real" age - this isn't important for my class.

like image 795
schuhesindbequemer Avatar asked Sep 07 '25 00:09

schuhesindbequemer


1 Answers

I'd do it like this:

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)

like image 111
Michael Haar Avatar answered Sep 08 '25 13:09

Michael Haar