Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to test a not-null field

I'm trying to make an unit test fail when a not-null field is not set in my model:

class Foo(models.Model):
    email = models.EmailField(
        unique=True,
        null=False,
        blank=False)

def testFoo(self):
    try:
        Foo.objects.create().save()
    except:
        self.fail("error!")

But it never fails.

The email format and not-null validations work perfectly when the application is running but I can't write the test.

Of course I can do the validations programmatically but I don't want to repeat myself. Any ideas?

like image 233
carrizo Avatar asked Nov 01 '22 00:11

carrizo


1 Answers

Okay, you have a few issues, let me enumerate:

  1. The save is superfluous. create already does the save.
  2. Creating objects does not trigger validation of things like "is this email a valid email". If you tried to pass in email=None it would fail because of your null=False parameter to the field, but the default for email is '', so it's not failing at that level. If you want to validate whether the email is valid or not, do this:

    def testFoo(self):
        try:
            a = Foo.objects.create()
            a.clean_fields()
        except:
            self.fail("error!")
    
like image 89
CrazyCasta Avatar answered Nov 15 '22 03:11

CrazyCasta