在我的django项目中,我有一些数据库连接:
例如
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "awesome",
...
},
"other_1": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "other_1",
"TEST": {"MIRROR": default}
...
},
"other_2": {
"ENGINE": "django.db.backends.mysql",
"NAME": "other_2",
"TEST": {"MIRROR": default}
}
}
注意:
default
和other_1
都是postgres
的后端,
other_2
是mysql
的后端。"TEST": {"MIRROR": default}
添加到了额外的数据库配置中,以避免在测试期间创建这些数据库。参见此link。问题:
运行测试时,它抱怨Unknown database 'test_awesome'
,堆栈跟踪显示它来自MYSQL后端:
Traceback (most recent call last):
File "/Users/jlin/virtualenvs/awesome-1SH6mAZ2/lib/python3.6/site-packages/django/test/testcases.py", line 1005, in setUpClass
if not connections_support_transactions():
File "/Users/jlin/virtualenvs/awesome-1SH6mAZ2/lib/python3.6/site-packages/django/test/testcases.py", line 970, in connections_support_transactions
...
File "/Users/jlin/virtualenvs/awesome-1SH6mAZ2/lib/python3.6/site-packages/MySQLdb/__init__.py", line 85, in Connect
return Connection(*args, **kwargs)
File "/Users/jlin/virtualenvs/awesome-1SH6mAZ2/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__
super(Connection, self).__init__(*args, **kwargs2)
django.db.utils.OperationalError: (1049, "Unknown database 'test_awesome'")
如果我注释掉other_2
连接,则测试运行正常。
答案 0 :(得分:0)
看起来问题出在后端吗?
我钻入了setup_database
code,如果我从other_2
字典中删除了mirrored_aliases
,那么我的测试代码就可以正常工作。
所以我创建了一个测试运行器类来删除other_2
连接,因为它太深了,无法从mirriored_aliases
中删除。
class TestRunner(DiscoverRunner):
def setup_databases(self, **kwargs):
# to get around this problem
# https://stackoverflow.com/questions/54189925/django-external-mysql-db-connection-in-test-complains-unknown-database
settings.DATABASES.pop('other_2', None)
return super(TestRunner, self).setup_databases(**kwargs)