开发者

'IntegrityError: column username is not unique' while using Django User model in test

开发者 https://www.devze.com 2023-03-10 20:36 出处:网络
While running some tests, I started to get an Integri开发者_StackOverflow社区tyError in my setUp function. Here is my code:

While running some tests, I started to get an Integri开发者_StackOverflow社区tyError in my setUp function. Here is my code:

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 ...

Im wondering as to how this IntegrityError keeps getting raised. I delete all the users in the tearDown function and am using sqlite3 as my DB backend. I see no conflicting usernames and in production, I have no issues with using emails as usernames.

This started happening only half an hour ago, out of the blue. Has anyone run into a solution to this problem?


I'm sure you're not suffering this problem anymore since you wrote 18 months ago, but I had this problem too, and finally figured out what was happening. When using Postgres for test cases, DB changes are done in a transaction and simply rolled back, and so it is not necessary to explicitly clear tables in tearDown(), however, in SQLite, it is necessary.


Late but more appropriate answer, for the people who would land there after a google search:

When there is interaction with the database in your tests (typically, creating model instances), you should subclass your test class from django.test.TestCase, which flushes the database after each test is run.

Then you don't need to write a tedious tearDown method in all your test classes.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消