【问题标题】:Django test runner cannot find non-default database connectionDjango 测试运行器找不到非默认数据库连接
【发布时间】:2016-11-23 09:17:20
【问题描述】:

我的 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 中运行。

【问题讨论】:

    标签: django python-2.7 unit-testing


    【解决方案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'}
                    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2013-05-07
      • 2016-01-21
      • 2011-12-12
      • 2017-03-20
      相关资源
      最近更新 更多