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
Model:
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
Tests:
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')))
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.
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)
See Validating objects - Model instance reference | Django documentation | Django
BTW, you model does not have location
field. I slightly modified model instance creation part accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With