测试 IntegrityError UNIQUE 约束失败

2024-03-02

我对电子邮件和商店有一个 unique_together 约束。我使用以下代码来测试唯一约束。我期望通过assertRaise 测试,但结果显示相反。我在这里缺少什么?

from django.db.backends.sqlite3.base import IntegrityError

class TestUserModel(TestCase):
    def setUp(self):
        self.store1 = Store.objects.create(name='store1')
        self.store2 = Store.objects.create(name='store2')

    def multiple_user_with_same_email_and_store(self):
        data1 = dict(email="[email protected] /cdn-cgi/l/email-protection", password="a", store=self.store1)
        data2 = dict(email="[email protected] /cdn-cgi/l/email-protection", password="abc", store=self.store1)
        self.user1 = User.objects.create(**data1)
        user2 = User(**data2)
        self.assertRaises(IntegrityError, user2.save)

追溯

    Creating test database for alias 'default'...
E
======================================================================
ERROR: multiple_user_with_same_email_and_store (user.tests.test_models.TestUserModel)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/ram/nk/project/helper/helper/user/tests/test_models.py", line 25, in multiple_user_with_same_email_and_store
    self.assertRaises(IntegrityError, user2.save)
  File "/usr/lib/python2.7/unittest/case.py", line 473, in assertRaises
    callableObj(*args, **kwargs)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/models/base.py", line 734, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/models/base.py", line 762, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/models/base.py", line 846, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/models/base.py", line 885, in _do_insert
    using=using, raw=raw)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/models/query.py", line 920, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 974, in execute_sql
    cursor.execute(sql, params)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/ram/.virtual/helper/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
    return Database.Cursor.execute(self, query, params)
IntegrityError: UNIQUE constraint failed: user_user.email, user_user.store_id


    ----------------------------------------------------------------------
    Ran 1 test in 0.003s

    FAILED (errors=1)

用户模型扩展了 AbstractUser(在 User 处没有添加其他内容),如下所示

class AbstractUser(auth_models.AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(_('email address'))
    store = models.ForeignKey(Store, verbose_name=_('Store Name'), null=True)
    first_name = models.CharField(_('First name'), max_length=255, blank=True)
    last_name = models.CharField(_('Last name'), max_length=255, blank=True)
    is_staff = models.BooleanField(
            _('Staff status'), default=False,
            help_text=_('Designates whether the user can log into this admin '
                        'site.'))
    is_active = models.BooleanField(
            _('Active'), default=True,
            help_text=_('Designates whether this user should be treated as '
                        'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'),
                                       default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['store']

    class Meta:
        abstract = True
        verbose_name = _('User')
        verbose_name_plural = _('Users')
        unique_together = ('email', 'store')

和用户管理器

class UserManager(auth_models.BaseUserManager):
    def create_user(self, store, email, password=None, **extra_fields):
        """
        Creates and saves a User with the given email and
        password.
        """
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = UserManager.normalize_email(email)
        try:
            with transaction.atomic():
                store, created = Store.objects.get_or_create(name=store)
                user = self.model(email=email, store=store, is_staff=False, is_active=True, is_superuser=False,
                        last_login=now, date_joined=now, **extra_fields)
                user.set_password(password)
                user.save(using=self._db)
        except Error as e:
            logging.ERROR(e)
            raise Error("Internal Error: Unable to create user")
        return user

    def create_superuser(self, store, email, password, **extra_fields):
        u = self.create_user(store, email, password, **extra_fields)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = True
        u.save(using=self._db)
        return u

    def create_staffuser(self, store, email, password, **extra_fields):
        u = self.create_user(store, email, password, **extra_fields)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = False
        u.save(using=self._db)
        return u

版本:1.8


所以错误是在右行引发的(在assertRaises),但我怀疑有两种不同的IntegrityError这里起作用的类 - 一个由测试导入,一个由数据库后端引发。

e.g.: django.db.backends.postgresql.base.IntegrityError不等于django.db.backends.sqlite3.base.IntegrityError。最重要的是,还有 Django 异常包装器django.db.utils.IntegrityError

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

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

测试 IntegrityError UNIQUE 约束失败 的相关文章

随机推荐

  • 出现 gdbm 错误:(13,'权限被拒绝') — 尽管 posix 权限看起来没问题

    我正在 python 2 7 6 中使用 shelve 进行缓存计算 并且遇到了所描述的问题HERE https stackoverflow com q 35771816 4038337对于我制作并实施的搁置文件建议的解决方案 https
  • 无法启动模拟器。原因:当react-native run-android时,模拟器在React Native启动之前退出

    我正在根据这个网站安装React Nativehttps medium com leonardobrunolima react native tips setting up your development environment for
  • 在 XAML 绑定表达式中使用变量

    我正在构建一个可以编辑 POCO 的控件 POCO 中有一个需要编辑的字段的描述符集合 我正在绑定一个ListBox s ItemsSource到这个集合 除其他外 描述符使我能够选择合适的DataTemplate以及 POCO 中的变量名
  • 周期可调的PRNG

    我需要构建一个周期可调的就地伪随机数生成器 另外 在一段时间内不得发生碰撞 也就是说 以下内容必须返回 true prng is generated at run time though a by hand solution would w
  • 如何克服导航栏的影响

    在我的应用程序中 我想在转到上一个视图时隐藏导航栏 并且我在 viewwiilldisaapper 方法中隐藏导航栏 但效果仍然存在 意味着它在弹出时显示白屏 那么任何人都可以告诉我解决方案吗 谢谢大家 您需要使用隐藏该页面 viewWil
  • 滚动然后对齐到顶部

    只是想知道是否有人知道我如何重新创建我不久前看到的导航栏样式 我刚刚找到了我在上面看到的网站 但不确定他们是如何到达那里的 基本上希望它随页面滚动然后锁定到顶部 http lesscss org http lesscss org 只需快速
  • iOS 中 @property 的默认值是多少?

    iOS 中 property 的默认值是什么 例如 如果我声明 property NSString Photographer 是默认值 分配 还是 保留 还是其他什么 原子 非原子 我无法从文档中找到此信息 谢谢 我相信默认值是 atomi
  • sklearn.impute.IterativeImputer 的实现

    考虑data其中包含以下一些 nan Column 1 Column 2 Column 3 Column 4 Column 5 0 NaN 15 0 63 0 8 0 40 0 1 60 0 51 0 NaN 54 0 31 0 2 15
  • 相交并合并两个对象数组

    我有两个数组 var odd name 1 extraProp1 propValue1 name 3 extraProp1 propValue2 var even name 1 extraProp2 prop1 name 2 extraPr
  • Javascript 未捕获类型错误:.split 不是函数

    我想做一个功能 用户每天只能领取一次硬币 我做了这个功能 split这样它就只比较日期Date 仅比较日期和时间 但是 我收到了这个 JavaScript 错误 未捕获的 TypeError 中间值 split 不是函数 有人知道如何解决这
  • 如何在主目录上撤消 git init ?

    I did git init and git add 在我的主目录中 我认为这减慢了每个操作的速度 因为该目录太大了 我怎样才能撤消git init主目录的 你可以这样做rm rf HOME git删除 git 存储的所有版本控制信息 这会
  • Python:每月的第三个星期五

    我是一个菜鸟Python程序员 我需要编写一个脚本来检查给定日期 以 月 日 年 形式作为字符串传递 是否是该月的第三个星期五 我正在使用Python 2 7 例如 这些日期可以帮助您更好地理解我的问题 手头有一份年度日历 输入 gt 输出
  • LINQ(或伪代码)按邻近度对项目进行分组

    有谁能够启发我如何使用 LINQ 或者必要时更合适的东西 来创建一个整数列表列表 这些整数列表按彼此的接近程度进行分组 基本上 我想创建组中的数字与任何其他数字在 5 以内 所以 给定 3 27 53 79 113 129 134 140
  • Inno Setup 查找子文件夹

    是否有办法获取目录中的所有 或仅第一个 子文件夹 我正在尝试将文件安装到具有动态名称的子目录中 它不是 Inno Setup 可用的常量之一 有办法找到这个子目录名吗 那么 要获取某个文件夹中第一个找到的子文件夹的名称 无论它是哪个 您可以
  • 将不需要的值替换为最接近且恰好为正的索引值

    这个问题与上一个问题不同 如何找到具有负值的索引并将该值替换为最接近的正值索引值 https stackoverflow com questions 59742108 how to find indices with a negative
  • 设置 NSStreamNetworkServiceTypeBackground “幕后作用”是什么?

    我有一个内部应用程序 不适用于 iPhone 商店分发 因此不受 Apple 批准 它需要在运行时保持少量 TCP 和 UDP 套接字绑定 在测试时 我注意到我的绑定套接字有一些奇怪的行为 只要设备进入睡眠状态 它就会关闭 例如 当您按下手
  • 设置为 Theme.NoTitleBar.Fullscreen 后应用程序崩溃

    如果我不取消标题栏 我的应用程序就会启动 但是当我取消标题栏时 它一启动就会崩溃 这是我到目前为止的代码 xml version 1 0 encoding utf 8 gt
  • 在 Angular 7 中使用 getElementById 在 DOM 元素上应用指令

    我有一些由第三方 plotly 生成的 HTML 我很想在它创建的 DOM 元素之一上应用我们已有的指令 该指令在单击时打开一个 colorPicker 并将颜色设置为字符串 我可以通过以下方式到达元素querySelector or ge
  • 英特尔 MKL 错误:参数 6 输入时不正确

    我收到以下错误 Intel MKL ERROR Parameter 6 was incorrect on entry to DGELSD 在 scipy 上运行 Savitzky Golay 过滤器时 函数scipy signal savg
  • 测试 IntegrityError UNIQUE 约束失败

    我对电子邮件和商店有一个 unique together 约束 我使用以下代码来测试唯一约束 我期望通过assertRaise 测试 但结果显示相反 我在这里缺少什么 from django db backends sqlite3 base