3

Is there a way to connect to django test database using connections?

I have tried cursor = connections['test_name_of_main_db'].cursor() and also specified the test db name in settings but I still receive errors:

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
djvg
  • 11,722
  • 5
  • 72
  • 103
Beliaf
  • 577
  • 2
  • 8
  • 25
  • You want to connect during the tests or before/after the tests? – Ralf Apr 20 '18 at 23:39
  • durng(will be nice in setUp method), i just need to create the object and not to dispacted singnal from signals.py( don't want to comment signals ) – Beliaf Apr 21 '18 at 10:23

1 Answers1

2

According to the docs:

The default test database names are created by prepending test_ to the value of each NAME in DATABASES.

But in your stacktrace the error says:

django.db.utils.ConnectionDoesNotExist: The connection auto_tests doesn't exist

Are you sure you are using the right alias? According to the error, it is looking for a database named auto_tests.

As another debugging step, you could print all the aliases during the test to see which ones are available

for alias in connections:
    print(alias)

Of course, you could also try to use the default database and see if that works for you during the tests:

# note that it is 'connection' and not 'connections'
from django.db import connection
cursor = connection.cursor()
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • will try, the `auto_tests` was add to settings.pay as test db name. – Beliaf Apr 21 '18 at 11:40
  • [Note the exception](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-TEST_NAME): "If the default value (`None`) is used with the SQLite database engine, the tests will use a memory resident database. For all other database engines the test database will use the name `'test_' + DATABASE_NAME`." – djvg Mar 22 '21 at 19:49