当我运行单元测试时,Django 1.6 似乎没有创建一个空白数据库来进行测试,我不明白为什么。姜戈docs http://django.readthedocs.org/en/1.6/topics/testing/overview.html#the-test-database假设 Django 不使用您的生产数据库,而是创建一个单独的空白数据库用于测试。但是,当我调试测试“test_get_user_ids”并运行命令“UserProxy.objects.all()”时,我会看到生产数据库中的所有用户。现在我知道这个特定的测试将会失败,因为我没有将每个 UserProxy 实例保存到数据库中,因此没有生成要测试的 id。但事实是,当我查询 UserProxy 时,我仍然可以看到生产数据库中的所有用户,而我希望这些用户为空。为什么会发生这种情况?
顺便说一句,我正在使用nosetest运行测试:“nosetests -s apps.profile.tests.model_tests.py:UserProxyUT”
Thanks.
# 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)
我要说这是因为你正在使用nosetests
而不是 Django 测试运行器。因为你正在使用nosetests
, 姜戈的setup_test_environment
没有被调用,这意味着代码不知道如何正确使用测试数据库。
以下是 Django 文档中应该有所帮助的相关部分:
运行测试时从生产数据库查找数据? https://docs.djangoproject.com/en/1.6/topics/testing/overview/#the-test-database
如果您的代码在编译其模块时尝试访问数据库,这将在设置测试数据库之前发生,并可能产生意外结果。例如,如果您在模块级代码中有一个数据库查询并且存在真实的数据库,则生产数据可能会污染您的测试。无论如何,在代码中进行此类导入时数据库查询都是一个坏主意 - 重写代码以使其不会执行此操作。
And:
在测试运行程序之外运行测试 https://docs.djangoproject.com/en/1.6/topics/testing/advanced/#running-tests-outside-the-test-runner
如果您想在 ./manage.py test 之外运行测试(例如,从 shell 提示符),您需要首先设置测试环境。 Django 提供了一个方便的方法来做到这一点:
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)