【发布时间】:2015-03-04 20:08:12
【问题描述】:
当我运行单元测试时,Django 1.6 似乎没有创建一个空白数据库来进行测试,我不明白为什么。 Django docs 说 Django 不使用您的生产数据库,而是创建一个单独的空白数据库进行测试。但是,当我调试测试“test_get_user_ids”并运行命令“UserProxy.objects.all()”时,我会看到生产数据库中的所有用户。现在我知道这个特定的测试会失败,因为我没有将每个 UserProxy 实例保存到数据库中,因此没有生成要测试的 id。但事实仍然是,当我查询 UserProxy 时,我仍然可以看到我的生产数据库中的所有用户,我希望这些用户是空的。为什么会这样?
顺便说一句,我正在使用鼻子测试运行测试:“nosetests -s apps.profile.tests.model_tests.py:UserProxyUT”
谢谢。
# settings.py
DATABASES = {
'default': {
# Enable PostGIS extensions
'ENGINE' : 'django.contrib.gis.db.backends.postgis',
'NAME' : 'myapp',
'USER' : 'myappuser',
'PASSWORD': 'myapppw',
'HOST' : 'localhost',
'PORT' : '',
}
}
# apps/profile/models.py
from django.contrib.auth.models import User
class UserProxy(User):
"""Proxy for the auth.models User class."""
class Meta:
proxy = True
@staticmethod
def get_user_ids(usernames):
"""Return the user ID of each username in a list."""
user_ids = []
for name in usernames:
try:
u = User.objects.get(username__exact=name)
user_ids.append(u.id)
except ObjectDoesNotExist:
logger.error("We were unable to find '%s' in a list of usernames." % name)
return user_ids
# apps/profile/tests/model_tests.py
from django.contrib.auth.models import User
from django.test import TestCase
from apps.profile.models import UserProxy
class UserProxyUT(TestCase):
def test_get_user_ids(self):
debug()
# UserProxy.objects.all() shows usernames from my production database!
u1 = UserProxy(username='user1')
u2 = UserProxy(username='user2')
u3 = UserProxy(username='user3')
usernames = [u1, u2, u3]
expected = [u1.id, u2.id, u3.id]
actual = UserProxy.get_user_ids(usernames)
self.assertEqual(expected, actual)
【问题讨论】:
-
您确定没有将生产数据库数据存储为夹具吗?
-
同时显示
DATABASES设置值。谢谢。 -
@alecxe,很抱歉。已显示。
-
@MikeDeSimone,不,我从不使用灯具。
-
您是否使用不同的设置文件进行测试?
标签: django django-models django-testing