测试是否引发了ValidationError

时间:2013-04-25 12:31:01

标签: python django unit-testing

我想测试是否有异常,我该怎么办?

在我的models.py中我有这个函数,我要测试的那个:

  def validate_percent(value):
    if not (value >= 0 and value <= 100):
      raise ValidationError('error')

在我的tests.py中我试过这个:

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

测试的输出是:

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

2 个答案:

答案 0 :(得分:21)

assertRaises用作上下文管理器:

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

或使用callable:

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

答案 1 :(得分:2)

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