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']
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)
def test_validate_percent(self):
self.assertRaises(ValidationError, validate_percent, 1000)
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