Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 905
Master Bee Avatar asked Apr 25 '13 12:04

Master Bee


2 Answers

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
like image 82
Pavel Anossov Avatar answered Nov 18 '22 20:11

Pavel Anossov


def test_validate_percent(self):
    self.assertRaises(ValidationError, validate_percent, 1000)
like image 3
waitingkuo Avatar answered Nov 18 '22 20:11

waitingkuo