我正在尝试为我的
django项目运行以下单元测试:
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()
测试失败引发以下错误:
IntegrityError: duplicate key value violates unique constraint "CarbonEmissions_userprofile_user_id_key" DETAIL: Key (user_id)=(1) already exists.
我无法理解该代码有什么问题.
最佳答案 错误消息告诉您约束“CarbonEmissions_userprofile_user_id_key”失败,因为在某些表中,已经有一行user_id等于1.
要解决这个问题,最简单的方法是使用pgAdminIII查看约束和数据,pgAdminIII通常与PostgreSQL一起安装.展开表名以查看列,约束等.展开约束以查看其名称和属性.右键单击表名,然后选择“查看数据”以查看允许您浏览数据的选项.