有没有办法使用connections
连接到django测试数据库?
我试过了
cursor = connections['test_name_of_main_db'].cursor()
并在设置中指定了测试数据库名称,但仍然收到错误:
Traceback (most recent call last):
File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 176, in ensure_defaults
conn = self.databases[alias]
KeyError: 'auto_tests'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/tets/healthware_server/component/medical/tests.py", line 72, in test_model_observation
cursor = connections['auto_tests'].cursor()
File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 208, in __getitem__ self.ensure_defaults(alias)
File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 178, in ensure_defaults
raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)
django.db.utils.ConnectionDoesNotExist: The connection auto_tests doesn't exist
答案 0 :(得分:1)
根据docs:
默认测试数据库名称是通过将
test_
添加到DATABASES中每个NAME的值来创建的。
但是在你的stacktrace中错误说:
django.db.utils.ConnectionDoesNotExist: The connection auto_tests doesn't exist
您确定使用正确的别名吗?根据错误,它正在寻找名为auto_tests
的数据库。
作为另一个调试步骤,您可以在测试期间打印所有别名以查看哪些别名可用
for alias in connections:
print(alias)
当然,您也可以尝试使用默认数据库,看看它在测试期间是否适用于您:
# note that it is 'connection' and not 'connections'
from django.db import connection
cursor = connection.cursor()