之前提出的问题,但错误是数据库中的用户名相同。
在我的情况下,数据库完全是空的。,这是测试用例:
def create_django_contrib_auth_models_user(**kwargs):
defaults = {}
defaults["username"] = "adminadmin"
defaults["email"] = "test@testus.com"
defaults["password"] = "testpass"
defaults.update(**kwargs)
return User.objects.create(**defaults)
我运行python manage.py tests
时收到此错误,并导致其他大多数测试失败
django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username
更新
以下是完整的tests.py
文件:
import unittest
from django.urls import reverse
from django.test import Client
from .models import Branch, Storage, Worker, job, Category, StorageItem, StorageMoves, Item
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
def create_django_contrib_auth_models_user(**kwargs):
defaults = {}
defaults["username"] = "adminadmin"
defaults["email"] = "test@testus.com"
defaults["password"] = "testpass"
defaults.update(**kwargs)
return User.objects.create(**defaults)
def create_django_contrib_auth_models_group(**kwargs):
defaults = {}
defaults["name"] = "group"
defaults.update(**kwargs)
return Group.objects.create(**defaults)
def create_django_contrib_contenttypes_models_contenttype(**kwargs):
defaults = {}
defaults.update(**kwargs)
return ContentType.objects.create(**defaults)
def create_branch(**kwargs):
defaults = {}
defaults["name"] = "name"
defaults.update(**kwargs)
return Branch.objects.create(**defaults)
def create_storage(**kwargs):
defaults = {}
defaults["name"] = "name"
defaults.update(**kwargs)
if "branch" not in defaults:
defaults["branch"] = create_branch()
return Storage.objects.create(**defaults)
def create_worker(**kwargs):
defaults = {}
defaults["name"] = "name"
defaults["phone"] = "01207199086"
defaults["address"] = "address"
defaults["date_joined"] = "1956-01-01"
defaults["image"] = "image"
defaults["is_active"] = False
defaults.update(**kwargs)
if "branch" not in defaults:
defaults["branch"] = create_branch()
return Worker.objects.create(**defaults)
def create_job(**kwargs):
defaults = {}
defaults["name"] = "name"
defaults.update(**kwargs)
return job.objects.create(**defaults)
def create_category(**kwargs):
defaults = {}
defaults["name"] = "name"
defaults.update(**kwargs)
return Category.objects.create(**defaults)
def create_storageitem(**kwargs):
defaults = {}
defaults["name"] = "name"
defaults["quantity"] = "15"
defaults.update(**kwargs)
if "storage" not in defaults:
defaults["storage"] = create_storage()
return StorageItem.objects.create(**defaults)
def create_storagemoves(**kwargs):
defaults = {}
defaults["name"] = "name"
defaults["quantity"] = "15"
defaults["text"] = "text"
defaults["type"] = "خروج"
defaults.update(**kwargs)
if "storage" not in defaults:
defaults["storage"] = create_storage()
if "user" not in defaults:
defaults["user"] = create_django_contrib_auth_models_user()
return StorageMoves.objects.create(**defaults)
def create_item(**kwargs):
defaults = {}
defaults["name"] = "name"
defaults.update(**kwargs)
if "category" not in defaults:
defaults["category"] = create_category()
return Item.objects.create(**defaults)
class BranchViewTest(unittest.TestCase):
'''
Tests for Branch
'''
def setUp(self):
self.client = Client()
def test_list_branch(self):
url = reverse('erp_branch_list')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_create_branch(self):
url = reverse('erp_branch_create')
data = {
"name": "name",
}
response = self.client.post(url, data=data)
self.assertEqual(response.status_code, 302)
def test_detail_branch(self):
branch = create_branch()
url = reverse('erp_branch_detail', args=[branch.slug, ])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_update_branch(self):
branch = create_branch()
data = {
"name": "name",
}
url = reverse('erp_branch_update', args=[branch.slug, ])
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
class StorageViewTest(unittest.TestCase):
'''
Tests for Storage
'''
def setUp(self):
self.client = Client()
def test_list_storage(self):
url = reverse('erp_storage_list')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_create_storage(self):
url = reverse('erp_storage_create')
data = {
"name": "name",
"branch": create_branch().pk,
}
response = self.client.post(url, data=data)
self.assertEqual(response.status_code, 302)
def test_detail_storage(self):
storage = create_storage()
url = reverse('erp_storage_detail', args=[storage.slug, ])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_update_storage(self):
storage = create_storage()
data = {
"name": "name",
"branch": create_branch().pk,
}
url = reverse('erp_storage_update', args=[storage.slug, ])
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
class WorkerViewTest(unittest.TestCase):
'''
Tests for Worker
'''
def setUp(self):
self.client = Client()
def test_list_worker(self):
url = reverse('erp_worker_list')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_create_worker(self):
url = reverse('erp_worker_create')
data = {
"name": "name",
"phone": "phone",
"address": "address",
"date_joined": "1956-01-01",
"image": "image",
"is_active": "is_active",
"branch": create_branch().pk,
}
response = self.client.post(url, data=data)
self.assertEqual(response.status_code, 302)
def test_detail_worker(self):
worker = create_worker()
url = reverse('erp_worker_detail', args=[worker.slug, ])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_update_worker(self):
worker = create_worker()
data = {
"name": "name",
"phone": "01207199086",
"address": "address",
"date_joined": "1956-01-01",
"image": "image",
"is_active": 'False',
"branch": create_branch().pk,
}
url = reverse('erp_worker_update', args=[worker.slug, ])
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
class jobViewTest(unittest.TestCase):
'''
Tests for job
'''
def setUp(self):
self.client = Client()
def test_list_job(self):
url = reverse('erp_job_list')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_create_job(self):
url = reverse('erp_job_create')
data = {
"name": "name",
}
response = self.client.post(url, data=data)
self.assertEqual(response.status_code, 302)
def test_detail_job(self):
job = create_job()
url = reverse('erp_job_detail', args=[job.slug, ])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_update_job(self):
job = create_job()
data = {
"name": "name",
}
url = reverse('erp_job_update', args=[job.slug, ])
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
class CategoryViewTest(unittest.TestCase):
'''
Tests for Category
'''
def setUp(self):
self.client = Client()
def test_list_category(self):
url = reverse('erp_category_list')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_create_category(self):
url = reverse('erp_category_create')
data = {
"name": "name",
}
response = self.client.post(url, data=data)
self.assertEqual(response.status_code, 302)
def test_detail_category(self):
category = create_category()
url = reverse('erp_category_detail', args=[category.slug, ])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_update_category(self):
category = create_category()
data = {
"name": "name",
}
url = reverse('erp_category_update', args=[category.slug, ])
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
class StorageItemViewTest(unittest.TestCase):
'''
Tests for StorageItem
'''
def setUp(self):
self.client = Client()
def test_list_storageitem(self):
url = reverse('erp_storageitem_list')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_create_storageitem(self):
url = reverse('erp_storageitem_create')
data = {
"name": "name",
"quantity": "quantity",
"storage": create_storage().pk,
}
response = self.client.post(url, data=data)
self.assertEqual(response.status_code, 302)
def test_detail_storageitem(self):
storageitem = create_storageitem()
url = reverse('erp_storageitem_detail', args=[storageitem.slug, ])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_update_storageitem(self):
storageitem = create_storageitem()
data = {
"name": "name",
"quantity": "quantity",
"storage": create_storage().pk,
}
url = reverse('erp_storageitem_update', args=[storageitem.slug, ])
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
class StorageMovesViewTest(unittest.TestCase):
'''
Tests for StorageMoves
'''
def setUp(self):
self.client = Client()
def test_list_storagemoves(self):
url = reverse('erp_storagemoves_list')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_create_storagemoves(self):
url = reverse('erp_storagemoves_create')
data = {
"name": "name",
"quantity": "15",
"text": "text",
"type": "دخول",
"storage": create_storage().pk,
"user": create_django_contrib_auth_models_user().pk,
}
response = self.client.post(url, data=data)
self.assertEqual(response.status_code, 302)
def test_detail_storagemoves(self):
storagemoves = create_storagemoves()
url = reverse('erp_storagemoves_detail', args=[storagemoves.slug, ])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_update_storagemoves(self):
storagemoves = create_storagemoves()
data = {
"name": "name",
"quantity": "quantity",
"text": "text",
"type": "دخول",
"storage": create_storage().pk,
"user": create_django_contrib_auth_models_user().pk,
}
url = reverse('erp_storagemoves_update', args=[storagemoves.slug, ])
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
class ItemViewTest(unittest.TestCase):
'''
Tests for Item
'''
def setUp(self):
self.client = Client()
def test_list_item(self):
url = reverse('erp_item_list')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_create_item(self):
url = reverse('erp_item_create')
data = {
"name": "name",
"category": create_category().pk,
}
response = self.client.post(url, data=data)
self.assertEqual(response.status_code, 302)
def test_detail_item(self):
item = create_item()
url = reverse('erp_item_detail', args=[item.slug, ])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_update_item(self):
item = create_item()
data = {
"name": "name",
"category": create_category().pk,
}
url = reverse('erp_item_update', args=[item.slug, ])
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
Settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', 'CHANGEME')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'crispy_forms',
'rest_framework',
'erp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'revo_erp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'revo_erp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, # noqa
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, # noqa
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, # noqa
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, # noqa
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
答案 0 :(得分:3)
测试用例应遵循django's documentation
的特定设置例如测试用户
class UserTest(TestCase):
""" Test module for GET all USERS API """
user = None
user2 = None
def setUp(self):
"""
Construct fake Users
:return:
"""
self.user = User.objects.create_user(username="user1", superuser_status=True
password="test1234")
self.user2= User.objects.create_user(username="admin",
password="123456")
def test_get_all_users(self):
"""
Test all users retrieval
:return:
"""
request = APIRequestFactory().get("/users/")
users_list = UserViewSet.as_view({'get': 'list'})
# get data from db
users = User.objects.all()
force_authenticate(request, user=self.user)
response = users_list(request)
serializer = UserSerializer(users, many=True)
self.assertEqual(response.data['results'], serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
答案 1 :(得分:2)
我认为这种情况正在发生,因为您在test_update_storagemoves
中两次创建了用户对象。一次致电create_storagemoves
,一次致电create_django_contrib_auth_models_user
。
create_storagemoves
在内部调用create_django_contrib_auth_models_user
,因此基本上您要调用create_django_contrib_auth_models_user
两次,并且基本上要创建两个具有相同User
的{{1}}实例具有username
约束。