【问题标题】:Unit Tests pass against regex validator of models in Django单元测试通过 Django 中模型的正则表达式验证器
【发布时间】:2014-09-18 02:03:08
【问题描述】:

我为 models.py 中的一些字段定义了我的模型以及正则表达式验证器。在 tests.py 中,我编写了测试来验证这些验证器,但它们通过了验证器。尽管当我尝试通过视图输入错误值时验证器会发出警报,并且我的 forms.py 中没有针对该表单的任何“干净”功能

型号:

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 本身中引发异常。

【问题讨论】:

    标签: python regex django unit-testing validation


    【解决方案1】:

    保存对象不生效。您需要使用Model.full_clean 方法手动完成。

    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)
    

    Validating objects - Model instance reference | Django documentation | Django

    顺便说一句,您的模型没有location 字段。我相应地稍微修改了模型实例创建部分。

    【讨论】:

    • 谢谢 :),我没有在此处复制完整的模型结构,但您的解决方案有所帮助
    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多