我有一个从传统数据库(只读连接)中提取数据到自己的数据库中的Django项目,当我运行集成测试,它试图从test_account
遗留连接读取。Django的单元测试与传统的数据库连接
(1049, "Unknown database 'test_account'")
有没有办法告诉Django离开遗留连接单独从测试数据库读取?
我有一个从传统数据库(只读连接)中提取数据到自己的数据库中的Django项目,当我运行集成测试,它试图从test_account
遗留连接读取。Django的单元测试与传统的数据库连接
(1049, "Unknown database 'test_account'")
有没有办法告诉Django离开遗留连接单独从测试数据库读取?
如果您想查看如何创建单独的集成测试框架,我实际上已经编写了一些内容,可让您在djenga
(pypi上提供)中创建集成测试。
下面是测试运行我使用Django的单元测试框架时使用:
from django.test.runner import DiscoverRunner
from django.apps import apps
import sys
class UnManagedModelTestRunner(DiscoverRunner):
"""
Test runner that uses a legacy database connection for the duration of the test run.
Many thanks to the Caktus Group: https://www.caktusgroup.com/blog/2013/10/02/skipping-test-db-creation/
"""
def __init__(self, *args, **kwargs):
super(UnManagedModelTestRunner, self).__init__(*args, **kwargs)
self.unmanaged_models = None
self.test_connection = None
self.live_connection = None
self.old_names = None
def setup_databases(self, **kwargs):
# override keepdb so that we don't accidentally overwrite our existing legacy database
self.keepdb = True
# set the Test DB name to the current DB name, which makes this more of an
# integration test, but HEY, at least it's a start
DATABASES['legacy']['TEST'] = { 'NAME': DATABASES['legacy']['NAME'] }
result = super(UnManagedModelTestRunner, self).setup_databases(**kwargs)
return result
# Set Django's test runner to the custom class defined above
TEST_RUNNER = 'config.settings.test_settings.UnManagedModelTestRunner'
TEST_NON_SERIALIZED_APPS = [ 'legacy_app' ]
from django.test import TestCase, override_settings
@override_settings(LOGIN_URL='/other/login/')
class LoginTestCase(TestCase):
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
https://docs.djangoproject.com/en/1.10/topics/testing/tools/
你应该在理论上可以在这里使用的替代设置,并切换到一个DIF