Django测试运行器找不到非默认数据库连接

时间:2016-07-20 08:27:45

标签: django python-2.7 unit-testing

我的Django应用程序运行正常,但我对Django的内置单元测试有问题。当使用非默认数据库以外的数据库在应用程序上运行Django测试运行器时,我收到错误:

python manage.py test qc
...      
File "/usr/lib64/python2.7/site-packages/django/db/utils.py", line 179, in ensure_defaults
        raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)
    ConnectionDoesNotExist: The connection other_db doesn't exist

在settings.py中:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_default',
        'USER': 'xxx',
        'PASSWORD': 'yyy',
        'HOST': os.environ["MYSQL_HOST"],
        'PORT': os.environ["MYSQL_PORT"],
    },
    'other_db': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_other',
        'USER': 'xxx',
        'PASSWORD': 'yyy',
        'HOST': os.environ["MYSQL_HOST"],
        'PORT': os.environ["MYSQL_PORT"],
    }
}

也许相关,在routers.py中:

def allow_migrate(self, db, app_label, model_name=None, **hints):

    if hints.has_key('model'):
        model = hints['model']

        if db == 'other_db':
            return model._meta.app_label == 'qc'
        elif model._meta.app_label == 'qc':
            return False
        return None
    else:
        if db == 'other_db':
            return app_label == 'qc'
        elif app_label == 'qc':
            return False

我试图在qc / tests.py中运行的测试用例:

from django.test import TestCase
from qc.models import *

class HybridTestCase(TestCase):

    def setUp(self):
        baseA = MyModel.objects.create(id='A',name="NonName")

Django版本:1.9.8。我正在使用CentOS 7在Docker中运行。

1 个答案:

答案 0 :(得分:1)

问题是我在settings.py文件中覆盖了DATABASES字典,以防测试:

if 'test' in sys.argv:
    DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}

为'other_db'添加内存数据库之后再次工作:

if 'test' in sys.argv:
    DATABASES = {
                 'default': {'ENGINE': 'django.db.backends.sqlite3'}, 
                 'other_db': {'ENGINE': 'django.db.backends.sqlite3'}
                }  
相关问题