TEST Mirror默认数据库,但无数据 [英] TEST Mirror default database but no data
问题描述
我正在尝试在我的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'
}
我的测试:
data_school = DataSchool.objects.all()
self.assertTrue(data_school.exists())
我很困惑,数据库管理员将test_mirrors配置为默认数据库的只读副本.理论上,默认数据库中的任何数据都可以用于测试吗?如果我有任何配置错误,请告诉我们.谢谢
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
推荐答案
这是Django中的一个已知错误: https://code.djangoproject.com/ticket/23718
This is a known bug in Django: https://code.djangoproject.com/ticket/23718
该票中描述的解决方法是最好的选择.我遇到了同样的问题,并通过定义自定义TestCase类并在所有测试中从该自定义测试用例继承来实现了变通方法.我还选择使用setUpClass和tearDownClass代替bug票证中所述的setUp和tearDown.无论哪种都可以.
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()
这篇关于TEST Mirror默认数据库,但无数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!