Master Bee
Master Bee

Reputation: 1099

Test if ValidationError was raised

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']

Upvotes: 17

Views: 17147

Answers (2)

waitingkuo
waitingkuo

Reputation: 93754

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

Upvotes: 3

Pavel Anossov
Pavel Anossov

Reputation: 62868

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)

Upvotes: 28

Related Questions