【发布时间】:2016-12-14 20:30:45
【问题描述】:
我有一个 Django 项目,它将旧数据库(只读连接)中的数据提取到自己的数据库中,当我运行集成测试时,它会尝试从旧连接上的 test_account 读取。
(1049, "Unknown database 'test_account'")
有没有办法告诉 Django 保留旧连接以从测试数据库中读取?
【问题讨论】:
我有一个 Django 项目,它将旧数据库(只读连接)中的数据提取到自己的数据库中,当我运行集成测试时,它会尝试从旧连接上的 test_account 读取。
(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/
理论上你应该可以在这里使用覆盖设置并切换到差异
【讨论】: