Test if ValidationError was raised

django, python, unit-testing

Solution

`assertRaises` is used as a context manager:

def test_validate_percent(self):
    with self.assertRaises(ValidationError):
        validate_percent(1000)

or with a callable:

def test_validate_percent(self):
    self.assertRaises(ValidationError, validate_percent, 1000)

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

Problem

I want to test if an exception was raised how can I do that? in my models.py I have this function, the one I want to test: ``` def validate_percent(value): if not (value >= 0 and value <= 100): raise ValidationError('error') ``` in my tests.py I tried this: ``` def test_validate_percent(self): self.assertRaises(ValidationError, validate_percent(1000)) ``` the output of the test is: ``` ..E ====================================================================== ERROR: test_validate_percent (tm.tests.models.helpers.HelpersTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/...py", line 21, in test_validate_percent self.assertRaises(ValidationError, validate_percent(1000)) File "/....py", line 25, in validate_percent raise ValidationError(u'error' % value) ValidationError: ['error'] ```

Original source

Related problems