【问题标题】:'IntegrityError: column username is not unique' while using Django User model in test在测试中使用 Django 用户模型时出现“IntegrityError:列用户名不是唯一的”
【发布时间】:2011-06-07 16:04:05
【问题描述】:

在运行一些测试时,我的 setUp 函数开始出现 IntegrityError。这是我的代码:

def setUp(self):
    self.client = Client()

    self.emplUser = User.objects.create_user('employee@email.com', 'employee@email.com', 'nothing')
    self.servUser1 = User.objects.create_user('thebestcompany@email.com', 'thebestcompany@email.com', 'nothing')
    self.servUser2 = User.objects.create_user('theothercompany@email.com', 'theothercompany@email.com', 'nothing')
    self.custUser1 = User.objects.create_user('john@email.com', 'john@email.com', 'nothing')
    self.custUser2 = User.objects.create_user('marcus@email.com', 'marcus@email.com', 'nothing')

    ... save users here ...

我想知道这个 IntegrityError 是如何不断提高的。我删除了 tearDown 函数中的所有用户,并使用 sqlite3 作为我的数据库后端。我没有看到有冲突的用户名,并且在生产中,使用电子邮件作为用户名没有任何问题。

这只是半小时前才开始发生的,出乎意料。有没有人遇到过这个问题的解决方案?

【问题讨论】:

    标签: database django testing


    【解决方案1】:

    我敢肯定,自从您 18 个月前写作以来,您已经不再遇到这个问题了,但我也遇到了这个问题,终于弄清楚发生了什么。在使用 Postgres 进行测试用例时,DB 更改在事务中完成并简单地回滚,因此无需显式清除 tearDown() 中的表,但在 SQLite 中,这是必要的。

    【讨论】:

    • 感谢我所做的。
    【解决方案2】:

    迟到但更合适的答案,对于那些在谷歌搜索后会登陆那里的人:

    当您的测试中与数据库交互时(通常是创建模型实例),您应该从 django.test.TestCase 子类化您的测试类,这会在每次测试运行后刷新数据库。

    那么您就不需要在所有测试类中编写繁琐的 tearDown 方法了。

    https://docs.djangoproject.com/en/dev/topics/testing/overview/#writing-tests

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 2018-01-22
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      • 2020-09-21
      • 1970-01-01
      • 2017-02-02
      相关资源
      最近更新 更多