Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Django 1.5 and Python 2.6.

The model has a clean() method that validates that job.company_id must equal job.location.company_id

I'm trying to write a test for this, but instead of passing/failing the test, the test is ending with the validation error message from the model's clean() method.

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

When I run 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']
like image 455
billrichards Avatar asked Dec 03 '13 14:12

billrichards


1 Answers

The problem is your usage of assertRaises. It should take the exception and the callable to check: http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises

However, you aren't passing the callable job2.clean you are passing the return value of the callable job2.clean(). Changing the call to

self.assertRaises(ValidationError, job2.clean)

should fix the exception and your test case.

like image 112
Mark Lavin Avatar answered Oct 01 '22 22:10

Mark Lavin