且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

测试IntegrityError UNIQUE约束失败

更新时间:2023-10-25 11:12:58

因此错误在右行(在 assertRaises 中)出现,但是我怀疑有两种不同的 IntegrityError 类在这里发挥作用-一种是由测试导入的,另一种是由数据库后端引发的.

So the error is being raised at the right line (in assertRaises), but I suspect there are two different kinds of IntegrityError classes at play here - one that is imported by the test, and one that is raised by the database backend.

例如: django.db.backends.postgresql.base.IntegrityError django.db.backends.sqlite3.base.IntegrityError 不同.最重要的是,有Django异常包装器 django.db.utils.IntegrityError

e.g.: django.db.backends.postgresql.base.IntegrityError is not the same as django.db.backends.sqlite3.base.IntegrityError. On top of that, there is the Django exception wrapper django.db.utils.IntegrityError

可以使用 self.assertRaises 作为上下文管理器来调试和验证问题:

The issue can be debugged and verified by using self.assertRaises as a context manager:

with self.assertRaises(Exception) as raised:  # top level exception as we want to figure out its exact type
    user2.save()
self.assertEqual(IntegrityError, type(raised.exception))  # if it fails, we'll get the correct type to import