У меня возникла проблема при написании модульных тестов для ограничений 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.

Ответы (1)

Причина неудачи этих тестов заключается в том, что они вызывают sqlite3.IntegrityError, а не django.db.utils.IntegrityError, поэтому вам следует утверждать правильный тип ошибки:

.
from sqlite3 import IntegrityError

# …

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

# …

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

2022 WebDevInsider