Python 2.6 - django TestCase - assertRaises ValidationError clean () method

Django 1.5 and Python 2.6.

The model has a method clean()that confirms that it job.company_idshould equaljob.location.company_id

I am trying to write a test for this, but instead of failing / failing the test, the test ends with a validation error message using the model method clean().

Here's the code (irrelevant bits omitted):

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

In the tests.py file:

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

When I run the 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']
+4
source share
1 answer

assertRaises. : http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises

job2.clean, job2.clean().

self.assertRaises(ValidationError, job2.clean)

.

+5

All Articles