【问题标题】:Connect to Django test database连接到 Django 测试数据库
【发布时间】:2018-10-01 16:56:48
【问题描述】:

有没有办法使用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

【问题讨论】:

  • 您想在测试期间或测试之前/之后连接?
  • durng(在setUp方法中会很好),我只需要创建对象而不是从signals.py中分离信号(不想评论信号)

标签: django django-database django-tests


【解决方案1】:

根据docs

默认测试数据库名称是通过在 DATABASES 中每个 NAME 的值前添加 test_ 来创建的。

但在您的堆栈跟踪中,错误显示:

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()

【讨论】:

  • 将尝试,auto_tests 已添加到 settings.pay 作为测试数据库名称。
  • Note the exception: "如果 SQLite 数据库引擎使用默认值 (None),测试将使用内存驻留数据库。对于所有其他数据库引擎,测试数据库将使用名称'test_' + DATABASE_NAME。”
猜你喜欢
  • 2013-05-07
  • 2016-01-21
  • 2022-12-16
  • 2017-11-26
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多