Using django: IntegrityError: duplicate key value in django unit test on newest questions tagged django – Stack Overflow

I am trying to run the following unit test for my django project:

from django.test import TestCase
from django.contrib.auth.models import User
from CarbonEmissions import models

class DbTest(TestCase):
    #is called before each test case (e.g test_insertingUserProfiles)
    def setUp(self):
        self.user = User.objects.create(username='ppoliani')
        self.userProfile = models.UserProfile.objects.create(user=self.user, title='Mr', type='student', occupation='student')

    def test_insertingUserProfiles(self):
        """
            Testing the insertion of user profiles into our datbase
        """
        self.assertEqual(self.user.get_profile().title,'Mr')

    #is called after each test case (e.g test_insertingUserProfiles)
    def tearDown(self):
        self.user.delete()
        self.userProfile.delete()

The test fails throwing the following error:

IntegrityError: duplicate key value violates unique constraint "CarbonEmissions_userprofile_user_id_key" DETAIL:  Key (user_id)=(1) already exists.

I can’t understand what’s wrong with that code.

See Answers


source: http://stackoverflow.com/questions/11915519/integrityerror-duplicate-key-value-in-django-unit-test
Using django: using-django



online applications demo