python – 测试是否提出ValidationError
发布时间:2020-12-16 23:37:36 所属栏目:Python 来源:网络整理
导读:我想测试一个异常是否被提出如何做到这一点? 在我的models.py我有这个功能,我想测试的一个: def validate_percent(value): if not (value = 0 and value = 100): raise ValidationError('error') 在我的tests.py中我尝试过: def test_validate_percent(se
我想测试一个异常是否被提出如何做到这一点?
在我的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'] 解决方法
assertRaises用作上下文管理器:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |