python 2.6 - django TestCase - assertRaises ValidationError clean()方法

时间:2013-12-03 14:52:47

标签: python django python-2.6 testcase

Django 1.5和Python 2.6。

该模型使用clean()方法验证job.company_id必须等于job.location.company_id

我正在尝试为此编写测试,但测试不是通过/未通过测试,而是以模型的clean()方法中的验证错误消息结束。

这是代码(省略了无关的位):

在models.py中:

class Job(models.Model):
    title = models.CharField(max_length=200, verbose_name="Job title")
    company = models.ForeignKey(Company)    
    location = models.ForeignKey(Location, blank=True, null=True)

    def clean(self):
        from django.core.exceptions import ValidationError
        '''
        Location.company_id must equal Job.company_id
        '''
        if (self.company_id != Location.objects.get(pk=self.location_id).company_id):
            raise ValidationError('Location is not valid for company')

在tests.py中:

class job_cannot_have_invalid_location_and_can_have_valid_location(TestCase):
    def test_jobs_and_locations(self):
        job2 = Job.objects.create(company_id=company2.id)
        location1 = Location.objects.create(company_id=company1.id)
        job2.location_id = location1.id
        self.assertRaises(ValidationError, job2.clean())

当我运行python manage.py test:

.E.
======================================================================
ERROR: test_jobs_and_locations     (companies.tests.job_cannot_have_invalid_location_and_can_have_valid_location)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/djangobox/jobboard/companies/tests.py", line 60, in test_jobs_and_locations
    self.assertRaises(ValidationError, job2.clean())
  File "/home/djangobox/jobboard/companies/models.py", line 151, in clean
    raise ValidationError('Location is not valid for company')
ValidationError: [u'Location is not valid for company']

1 个答案:

答案 0 :(得分:5)

问题在于您使用assertRaises。应该检查异常和callable:http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises

但是,您没有传递可调用job2.clean,而您传递的是可调用job2.clean()的返回值。将呼叫更改为

self.assertRaises(ValidationError, job2.clean)

应该修复异常和你的测试用例。