我正在尝试在我正在开发的应用程序上运行测试,但我遇到了问题。该应用程序使用 2 个数据库,一个 MySQL 用于配置和关系数据,一个 MongoDB 用于其他一些非关系记录。当我正常使用它时它可以工作,因为 Y 只是 syncdb 关系数据库......但是当我尝试运行测试时,Django 正在尝试同步两个数据库然后崩溃,因为它在模型的 mongo 中出现了一些错误。有什么建议么?
这是数据库的配置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'app',
'USER': 'test',
'PASSWORD': 'test',
'HOST': '127.0.0.1',
'PORT': '3306',
},
'nonsql': {
'ENGINE' : 'django_mongodb_engine',
'NAME' : 'app',
'HOST': '127.0.0.1',
'PORT': 27017,
},
}
路由器:
class AppRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'nonsql':
return 'nonsql'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'nonsql':
return 'nonsql'
return None
def allow_relation(self, obj1, obj2, **hints):
if obj1._meta.app_label == 'nonsql' or \
obj2._meta.app_label == 'nonsql':
return True
return None
def allow_syncdb(self, db, model):
if db == 'auth_db':
return model._meta.app_label == 'nonsql'
elif model._meta.app_label == 'nonsql':
return False
return None
测试代码:
import pymongo
from django.test import TestCase
from app import views
from app.models import Car
from bson.objectid import ObjectId
from django.test import Client
import json
class CarTest(TestCase):
def setUp(self):
Operation.objects.create(id = ObjectId("5396d352421aa93f63ca45d5"), name = "Test Car", description= "Test Description",
start_date="2011-03-26 13:54:37.355", end_date="2014-09-11 13:54:37.355")
def test_adding_operation(self):
c = Client()
response = c.post('/cars/',{"name":"Test car 002", "description":"Test description car 002", "start_date":"2014-09-05 13:54:37.355", "end_date":"2014-09-11 13:54:37.355"})
content = json.loads(response.content)
# we expect to receive status success and an id
self.assertEqual("ok",content['status'])
self.assertNotEqual("",content['result'])