Django unittest fails to check empty values

105 views
Skip to first unread message

marco sedda

unread,
Jan 26, 2009, 6:25:37 AM1/26/09
to Django users
Hi, I've a problem with unittest in django:

I've described a models.py:

class Season(models.Model):
name = models.CharField(max_length=30, unique=True)
startDate = models.DateField("From")
endDate = models.DateField("To")

and the test.py:

def testSeasonCreateEmpty(self):
self.assertRaises(IntegrityError, Season.objects.create,
startDate="2009-01-01",
endDate="2009-01-01")
transaction.rollback()

when i run from console: python manage.py test, the test fails with
message:
"AssertionError: IntegrityError not raised"

Why it doesn't raise exception for a season object without a name??

Alex Koshelev

unread,
Jan 26, 2009, 12:49:16 PM1/26/09
to django...@googlegroups.com
What DB backend do you use? In some cases  it rises OperationalError

Malcolm Tredinnick

unread,
Jan 26, 2009, 10:46:22 PM1/26/09
to django...@googlegroups.com

Because it's not an integrity error. There are two things at work here:

(1) If you don't specify a value for any text-based field in Django
models (including CharField), Django will store the empty string (''),
which is valid as far as the database is concerned (no integrity error).

(2) Right now, blank=True/False is not validated at the model level.
It's only validated at the form level (via ModelForms) when data is
submitted via the admin or another form. So it's possible to store blank
values in text-based fields that don't have blank=False specified on
them if you create the model directly. That (model-aware validation) is
a feature that is coming in Django 1.1. Note that "blank" is a
Python/Django level concept, as opposed to "null" or "not null", which
is enforced at the database level. See point (1) and the Django
documentation for model fields for why null-ity plays no role for
CharFields.

If you had created the same object twice, you would, however, have seen
an IntegrityError, since the empty string (the second time) for the
"name" field would not have been unique.

Regards,
Malcolm


Reply all
Reply to author
Forward
0 new messages