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?
Okay, you have a few issues, let me enumerate:
save
is superfluous. create
already does the save.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!")
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