如何在Python中对regex进行测试?

2024-03-29 11:10:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始对我的web应用程序进行测试。你知道吗

首先,我不确定是否有必要在regex模型字段上运行测试(比如我代码中的那个),其次,如果有必要,我该怎么做?你知道吗

我已经尝试过这个解决方案:Unit Tests pass against regex validator of models in Django但它不起作用。你知道吗

cf字段需要16个字符的字符串,但是我的函数test\u cf\u max\u length()返回seller对象,即使输入的cf错误(<;16个字符)

你知道吗型号.py你知道吗

class Seller(User):
    cf = models.CharField(validators=[RegexValidator(regex='^.{16}$', message='Social Security Number', code='nomatch')], max_length=16)
    iban = models.CharField(validators=[RegexValidator(regex='^.{27}$', message='IBAN', code='nomatch')], max_length=27)
    is_seller = models.BooleanField(default=False)

你知道吗测试.py你知道吗

def setUpTestData(cls):
    Seller.objects.create(username='clara', cf='12345690123456', iban='123456789012345678901234567')


def test_cf_max_length(self):
    seller = Seller.objects.get(id=1)
    with self.assertRaises(ValidationError):
        if seller.full_clean():
            seller.save()
    self.assertEqual(Seller.objects.filter(id=1).count(), 0)

Tags: pytestselfobjectsmodelslengthmaxregex
1条回答
网友
1楼 · 发布于 2024-03-29 11:10:25

https://docs.djangoproject.com/en/2.2/ref/validators/#how-validators-are-run

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

关于测试的必要性,这个案例清楚地告诉你写它们是有意义的。你知道吗

相关问题 更多 >