[英]How to test a named CheckConstraint or ValidationError is raised in unittests?
我正在对我的 model 进行单元测试验证和检查约束:
class MyModel(models.Model):
title = models.CharField()
class Meta:
models.CheckConstraint(
check=~Q(title='Word'),
name='title_cannot_be_word'
),
def clean(self):
error_dict = {}
if self.title == 'Word':
error_dict['title'] = 'Title can not be Word'
if error_dict:
raise ValidationError(error_dict)
在我的tests.py中:
def test_validation(self):
with self.assertRaises(ValidationError):
m = MyModel(title='Word')
m.clean()
def test_constraint(self):
with self.assertRaises(Integrity):
m = MyModel.objects.create(title='Word')
这一切都很好,但是实际上我有多个CheckConstraints
和ValidationErrors
用于不同的字段,所以我希望能够测试是否出现了正确的错误。
如何测试像title_cannot_be_word
这样的命名CheckConstraint
,或者像error_dict['title']
这样的命名ValidationError
被提升?
您可以获得对异常的引用,然后继续验证:
def test_validation(self):
with self.assertRaises(ValidationError) as ex:
m = MyModel(title='Word')
m.clean()
exception = ex.exception
self.assertTrue(hasattr(exception, 'error_dict'))
self.assertIn('title', exception.error_dict)
至于IntegrityError
,它不包含任何字段,它只是带参数的Exception
。 您可能想检查异常的名称是否在字符串表示中:
def test_constraint(self):
with self.assertRaises(Integrity) as ex:
MyModel.objects.create(title='Word')
exception = ex.exception
self.assertIn('title_cannot_be_word', str(exception))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.