您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 测试是否提出ValidationError

5b51 2022/1/14 8:23:17 python 字数 1635 阅读 569 来源 www.jb51.cc/python

我想测试一个异常是否被提出如何做到这一点? 在我的models.py我有这个功能,我想测试的一个: def validate_percent(value): if not (value >= 0 and value <= 100): raise ValidationError('error') 在我的tests.py中我尝试过: def test_validate_percen

概述

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

或与可呼叫:

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

> http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶