Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Tests pass against regex validator of models in Django

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.

like image 972
user3490695 Avatar asked Jul 26 '14 08:07

user3490695


1 Answers

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.

like image 104
falsetru Avatar answered Oct 31 '22 23:10

falsetru