17

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']
Master Bee
  • 1,089
  • 1
  • 12
  • 18

2 Answers2

28

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)
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
3
def test_validate_percent(self):
    self.assertRaises(ValidationError, validate_percent, 1000)
waitingkuo
  • 89,478
  • 28
  • 112
  • 118