Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TEST Mirror default database but no data

Tags:

django

I am trying to set up some testing on my Django application. I have used a database mirror for the test database. When I try to run few test it appears the data from 'default database' is not available in the mirror test database.

'default': { #'sqlite': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'OPTIONS':{
            'timeout': 180,
        },
        #  'TEST':{
        #     'MIRROR': 'default',
        #
        # }


    },
'replica': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'OPTIONS':{
            'timeout': 180,
        },
        'TEST_MIRROR': 'default'


    }

my tests:

data_school = DataSchool.objects.all()
self.assertTrue(data_school.exists())

I am confused, the test_mirrors configured by the database administrator as a read replica of default database.and in theory any data in default database should be available for test? If I have any configuration errors please do let know. Thanks

like image 762
djpy Avatar asked Jan 07 '23 03:01

djpy


1 Answers

This is a known bug in Django: https://code.djangoproject.com/ticket/23718

The workaround described in that ticket is your best bet. I ran into this same issue and implemented the workaround by defining a custom TestCase class and inheriting from that custom test case in all my tests. I also chose to use setUpClass and tearDownClass instead of setUp and tearDown as described in the bug ticket. Either should work though.

from django.db import connections

class CustomTestCase(TestCase):

    @classmethod
    def setUpClass(cls):
        super(CustomTestCase, cls).setUpClass()
        connections['replica']._orig_cursor = connections['replica'].cursor
        connections['replica'].cursor = connections['default'].cursor

    @classmethod
    def tearDownClass(cls):
        connections['replica'].cursor = connections['replica']._orig_cursor
        super(CustomTestCase, cls).tearDownClass()
like image 50
Sean Azlin Avatar answered Jan 14 '23 20:01

Sean Azlin