Skip to content
Advertisement

DJango testing multiple database application

I have django application which has two database defaultdb and externdb

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        "NAME": config("DB_NAME"),
        "USER": config("DB_USER"),
        "PASSWORD": config("DB_PASSWORD"),
        "HOST": config("DB_HOST"),
        "PORT": config("DB_PORT"),
        'OPTIONS': {
            'charset': 'utf8mb4',
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
        },
        'TEST': {
            'NAME': 'test_{0}'.format(config("DB_NAME")),
            'MIRROR': "default",
        },
    },
    'extern': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': config("DB_EXTERN_NAME"),
        'USER': config("DB_EXTERN_USER"),
        'PASSWORD': config("DB_EXTERN_PASSWORD"),
        'HOST': config("DB_EXTERN_HOST"),
        'PORT': config("DB_EXTERN_PORT"),
        'TEST': {
            'NAME': 'test_{0}'.format(config("DB_EXTERN_NAME")),
            'MIRROR': "extern",
        },
    }
}

The application works well but when testing ,this error occurs below

when trying to access the extern database

from extern_db.models import TBasicInfo

class HelpViewTest(TestCase):
    def test_api(self):
        tb = TBasicInfo.objects.get(info_id=10352)

This error occurs

AssertionError: Database queries to 'extern' are not allowed in this test. Add 'extern' to defapp.tests.HelpViewTest.databases to ensure proper test isolation and silence this failure.

which setting should I check??

Advertisement

Answer

Change:

    tb = TBasicInfo.objects.get(info_id=10352)

to this:

    tb = TBasicInfo.objects.using("extern").get(info_id=10352)

OR

You can also add databases = “extern” to this:

from extern_db.models import TBasicInfo

class HelpViewTest(TestCase):
    def test_api(self):
        tb = TBasicInfo.objects.get(info_id=10352)

final version:

from extern_db.models import TBasicInfo

class HelpViewTest(TestCase):
    databases = 'extern'

    def test_api(self):
        tb = TBasicInfo.objects.get(info_id=10352)

This method is what it basically suggests you to do in that message.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement