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

最佳答案

问题是您对assertRaises的用法。它应该包含异常和可调用对象以进行检查:http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises

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

self.assertRaises(ValidationError, job2.clean)

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

关于python 2.6-Django TestCase-assertRaises ValidationError clean()方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20354385/

10-13 01:09