Problems using User model in django unit tests

theycallmemorty picture theycallmemorty · May 15, 2010 · Viewed 12.1k times · Source

I have the following django test case that is giving me errors:

class MyTesting(unittest.TestCase):
    def setUp(self):
        self.u1 = User.objects.create(username='user1')
        self.up1 = UserProfile.objects.create(user=self.u1)

    def testA(self):
        ...

    def testB(self):
        ...

When I run my tests, testA will pass sucessfully but before testB starts, I get the following error:

IntegrityError: column username is not unique

It's clear that it is trying to create self.u1 before each test case and finding that it already exists in the Database. How do I get it to properly clean up after each test case so that subsequent cases run correctly?

Answer

Davor Lucic picture Davor Lucic · May 15, 2010

setUp and tearDown methods on Unittests are called before and after each test case. Define tearDown method which deletes the created user.

class MyTesting(unittest.TestCase):
    def setUp(self):
        self.u1 = User.objects.create(username='user1')
        self.up1 = UserProfile.objects.create(user=self.u1)

    def testA(self):
        ...

    def tearDown(self):
        self.up1.delete()
        self.u1.delete()

I would also advise to create user profiles using post_save signal unless you really want to create user profile manually for each user.

Follow-up on delete comment:

From Django docs:

When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.

In your case, user profile is pointing to user so you should delete the user first to delete the profile at the same time.