单元测试通过Django中模型的正则表达式验证器传递 [英] Unit Tests pass against regex validator of models in Django
问题描述
我为model.py中的几个字段定义了我的模型以及正则表达式验证器.在tests.py中,我编写了测试以验证那些验证器,但它们通过了它们.尽管当我尝试通过视图输入错误的值并且我的form.py中没有任何干净"功能时,验证程序会提高警惕
I have my models defined along with regex validators for a few fields in models.py. In tests.py, I have written tests to verify those validators but they pass against them. Although the validators are raising alert when I am trying to enter wrong values through views and I don't have any "clean" function in my forms.py for that form
型号:
class Organization(models.Model):
name = models.CharField(
max_length=128,
unique=True,
validators=[
RegexValidator(
r'^[(A-Z)|(a-z)|(\s)]+$',
)
]
)
def __unicode__(self):
return self.name
测试:
class TestOrganization(TestCase):
def setUp(self):
Organization.objects.create(
name='XYZ123',
location='ABC'
)
def test_insertion(self):
self.assertEqual(1,len(Organization.objects.filter(name='XYZ123')))
此测试实际上针对验证者规则创建了一个组织对象,并且test_insertion实际上通过了,事实并非如此,应该在setUp本身中引发异常.
This test actually creates an organization object against validators rule and test_insertion actually passes, which should not be the case and exception should be raised in setUp itself.
推荐答案
保存对象无效.您需要使用 Model.full_clean
方法.
Saving object does not validate. You need to do it manually using Model.full_clean
method.
from django.core.exceptions import ValidationError
class TestOrganization(TestCase):
def test_validation(self):
org = Organization(name='XYZ123')
with self.assertRaises(ValidationError):
# `full_clean` will raise a ValidationError
# if any fields fail validation
if org.full_clean():
org.save()
self.assertEqual(Organization.objects.filter(name='XYZ123').count(), 0)
请参见验证对象-模型实例参考|Django文档|Django
顺便说一句,您的模型没有 location
字段.我对模型实例创建部分做了相应的修改.
BTW, you model does not have location
field. I slightly modified model instance creation part accordingly.
这篇关于单元测试通过Django中模型的正则表达式验证器传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!