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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With