0

In my django project I have a few database connections:

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:

  1. The default and other_1 both are postgres backends and other_2 is mysql backend.
  2. I added "TEST": {"MIRROR": default} to the extra database config in a bid to avoid those databases being created during test. 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:

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.

James Lin
  • 25,028
  • 36
  • 133
  • 233

1 Answers1

0

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.

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.

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)
James Lin
  • 25,028
  • 36
  • 133
  • 233