Django 单元测试约束

Django unit test constraints

所以我在为 Check 和 Unique 约束编写单元测试时遇到了问题。以下是它们的定义:

# assert that a partner can have only one headquarter
constraints = [
   models.UniqueConstraint(
       fields=['partner', 'active'],
       condition=models.Q(headquarter=True),
       name='HQ already set.'
     )
]


# assert every partner contant has at least one of email/phone number pair defined
constraints = [            
   models.CheckConstraint(
       check= (
                 models.Q(email__isnull=False) &
                 models.Q(phone_number__isnull=False)
              ),
       name='E-mail or phone number should be set.'
   )
]

并且单元测试断言哪个失败:

from django.db.utils import IntegrityError
....
# HQ already defined so it should work
with self.assertRaises(Exception) as raised:
    partnerHQCopy.save()

self.assertEqual(IntegrityError, type(raised.exception))

.....
# The contact added has both email and phone number None
with self.assertRaises(Exception) as raised:
    partnerContact.save()

self.assertEqual(IntegrityError, type(raised.exception))

以及回溯:

======================================================================
ERROR: test_unique_hq_for_partner (partners.tests.PartnerModelsTestCases)
----------------------------------------------------------------------

.....

sqlite3.IntegrityError: UNIQUE constraint failed: partners_partnerbranch.partner_id, partners_partnerbranch.active

.....

django.db.utils.IntegrityError: UNIQUE constraint failed: partners_partnerbranch.partner_id, partners_partnerbranch.active

======================================================================
ERROR: test_partner_contact_no_email_no_phone (partners.tests.PartnerModelsTestCases)
----------------------------------------------------------------------
.....

sqlite3.IntegrityError: CHECK constraint failed: E-mail or phone number should be set.

.....

django.db.utils.IntegrityError: CHECK constraint failed: E-mail or phone number should be set.

这些测试失败的原因是因为它引发了 sqlite3.IntegrityError,而不是 django.db.utils.IntegrityError,因此您应该声明正确的错误类型:

from <b>sqlite3</b> import IntegrityError

# …

# HQ already defined so it should work
with self.assertRaises(<b>IntegrityError</b>):
    partnerHQCopy.save()

# …

# The contact added has both email and phone number None
with self.assertRaises(<b>IntegrityError</b>):
    partnerContact.save()