我刚刚开始对我的网络应用程序进行测试。
首先,我不确定是否有必要对正则表达式模型字段(就像我代码中的那个)运行测试,其次,如果需要测试,我该怎么做?
我已经尝试过这个解决方案:Unit Tests pass against regex validator of models in Django 但它不起作用。
cf 字段需要 16 个字符的字符串,但我的函数 test_cf_max_length() 返回卖家对象,即使输入的 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)
最佳答案
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.
关于测试的必要性,这个案例清楚地告诉你编写它们是有意义的。
关于python - 如何在 Python 中对正则表达式进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924098/