[英]Django external mysql db connection in test complains “unknown database”
In my django project I have a few database connections: 在我的django项目中,我有一些数据库连接:
eg. 例如。
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}
}
}
Note: 注意:
default
and other_1
both are postgres
backends and other_2
is mysql
backend. default
和other_1
都是postgres
后端, other_2
是mysql
后端。 "TEST": {"MIRROR": default}
to the extra database config in a bid to avoid those databases being created during test. "TEST": {"MIRROR": default}
,以避免在测试期间创建这些数据库。 See this link . Problem: 问题:
When I run the test, it complains about Unknown database 'test_awesome'
, the stack trace shows it's from MYSQL backend: 当我运行测试时,它抱怨
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'")
If I comment out the other_2
connection, the test runs fine. 如果我注释掉
other_2
连接,则测试运行正常。
Looks like the problem is due to having backend? 看起来问题出在后台吗?
I dug into the setup_database
code , and if I remove other_2
in the mirrored_aliases
dict, then my test code works fine. 我研究了
setup_database
代码 ,如果我删除了mirrored_aliases
字典中的other_2
,那么我的测试代码可以正常工作。
So I created a test runner class to remove the other_2
connection because it's too deep into the code to remove from mirriored_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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.