B
B
Boldy2014-11-14 10:32:44
Django
Boldy, 2014-11-14 10:32:44

How to write tests in django?

Just started writing tests. The project uses django-mptt. How to write tests for it? SQLite.
In this test, user2 becomes a child of user1 and user1.invite_period_expire_date is set to user2.contract_date+timedelta(days=30). Only the user2.get_ancestors() call returns an empty array. The attributes only list the fields that django complained about. Now the tests just don't pass.

from django.test import TestCase
from models import TreeNode
from datetime import date, timedelta


class TreeTest(TestCase):
    def test_invite_period_works_correctly(self):
        user1 = TreeNode.objects.create(id=4,
                         date_of_birth=date.today(),
                         passport_address_id=1,
                         identity_expire_date=date.today(),
                         contract_date=date(2014, 1, 1),
                         itn=1, account_id=1, level=1, lft=1, rght=4, tree_id=1).save()
        user2 = TreeNode.objects.create(id=15,
                         date_of_birth=date.today(),
                         passport_address_id=1,
                         identity_expire_date=date.today(),
                         contract_date=date(2014, 1, 2),
                         itn=2, account_id=2, level=2, lft=1, rght=3, tree_id=1)\
            .insert_at(TreeNode.objects.get(id=4),, save=True)
        self.assertEqual(user2.get_parent_of_level(1).invite_period_expire_date, user2.contract_date + timedelta(days=30))

tested model
class TreeNode(MPTTModel):

    id = models.CharField(verbose_name='Клиентский ID', max_length=10, primary_key=True)
    parent = TreeForeignKey('self', verbose_name='ID пригласившего', null=True, blank=True, related_name='child')

    contract_date = models.DateField(null=False, blank=False)
    invite_period_expire_date = models.DateField(null=True, blank=True)

    def save(self, *args, **kwargs):
        super(TreeNode, self).save(*args, **kwargs)
        if self.get_parent_of_level(1):
            if not self.get_parent_of_level(1).invite_period_expire_date:
                self.get_parent_of_level(1).start_invite_period(self.contract_date)
    
    def start_invite_period(self, start_date):
        self.invite_period_expire_date = start_date + invite_period
        self.save()

    def get_parent_of_level(self, level):
        if self.get_level() - level >= 0:
            return self.get_ancestors().get(level=self.get_level() - level)
        return None

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question