用于在模型中返回绝对URL的Django单元测试

时间:2018-10-01 12:34:15

标签: django unit-testing django-models

下面是models.py

class Unit(models.Model):
    name = models.CharField(max_length=200)
    start = models.DateTimeField()
    end = models.DateTimeField()
    description = models.TextField()
    deleted = models.BooleanField(default=False)

    def clean(self):
        if self.end and self.start and self.end <= self.start:
            raise ValidationError({
                'end': _('End date should be after start date')
            })

    def get_absolute_url(self):
        return reverse('decentmark:unit_view', kwargs={'unit_id': self.pk})

我为日期验证等编写了一些测试。需要一些帮助来为get_aubsolute_url编写测试

1 个答案:

答案 0 :(得分:0)

您将需要创建一个新对象并尝试访问它,如果操作顺利,它将返回响应代码200,否则将返回404

class UnitTest(TestCase):
    def create_unit(self): # create_an_object_to_test_later
        name = 'just_test'
        start = '01-01-2018'
        end = '01-01-2019'
        description = 'demo_text'
        return Unit.objects.create(name=name, start =start , end =end,description =description)

    def test_url(self):
        w = self.create_unit()
        response = self.client.post(reverse('unit_view', args=[w.pk,])) #set unit_view to the url name in the urls.py
        self.assertEqual(response.status_code, 200)