Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for a ValidationError in Django

If I have a model called Enquiry with an attribute of email how might I check that creating an Enquiry with an invalid email raises an error?

I have tried this

def test_email_is_valid(self):
    self.assertRaises(ValidationError, Enquiry.objects.create(email="testtest.com"))

However I get the Error

TypeError: 'Enquiry' object is not callable

I'm not quite getting something, does anybody know the correct method to test for email validation?

like image 297
Reiss Johnson Avatar asked Jul 02 '26 09:07

Reiss Johnson


1 Answers

Django does not automatically validate objects when you call save() or create(). You can trigger validation by calling the full_clean method.

def test_email_is_valid(self):
    enquiry = Enquiry(email="testtest.com")
    self.assertRaises(ValidationError, enquiry.full_clean)

Note that you don't call full_clean() in the above code. You might prefer the context manager approach instead:

def test_email_is_valid(self):
    with self.assertRaises(ValidationError):
        enquiry = Enquiry(email="testtest.com")
        enquiry.full_clean()
like image 156
Alasdair Avatar answered Jul 04 '26 01:07

Alasdair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!