如您所请求的,这就是我最终实现的内容。"遗留"数据库是指我们希望跳过创建的数据库——Django应该假定它已经存在。
首先,您需要添加这个稍作修改的测试运行程序:
project/runner.py
:
from django.test.runner import DiscoverRunner
from django.test.utils import get_unique_databases_and_mirrors
from django.db import connections
class LegacyDatabaseRunner(DiscoverRunner):
"""
Test runner that will skip attempting to create any database with LEGACY=True
in its TEST configuration dictionary
"""
def setup_databases(self, **kwargs):
return _setup_databases(
self.verbosity, self.interactive, self.keepdb, self.debug_sql,
self.parallel, **kwargs
)
def _setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, **kwargs):
"""Clone of django.test.utils.setup_databases"""
test_databases, mirrored_aliases = get_unique_databases_and_mirrors()
old_names = []
for db_name, aliases in test_databases.values():
first_alias = None
for alias in aliases:
connection = connections[alias]
if connection.settings_dict.get('TEST', {}).get('LEGACY', False):
continue
old_names.append((connection, db_name, first_alias is None))
if first_alias is None:
first_alias = alias
connection.creation.create_test_db(
verbosity=verbosity,
autoclobber=not interactive,
keepdb=keepdb,
serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
)
if parallel > 1:
for index in range(parallel):
connection.creation.clone_test_db(
suffix=str(index + 1),
verbosity=verbosity,
keepdb=keepdb,
)
else:
connections[alias].creation.set_as_test_mirror(connections[first_alias].settings_dict)
for alias, mirror_alias in mirrored_aliases.items():
connections[alias].creation.set_as_test_mirror(
connections[mirror_alias].settings_dict)
if debug_sql:
for alias in connections:
connections[alias].force_debug_cursor = True
return old_names
接下来,将其设置为您的
项目/settings.py
中的默认运行程序:
TEST_RUNNER = 'project.runner.LegacyDatabaseRunner'
如果你想跳过某些数据库的创建,请在设置中使用LEGACY=True
标记:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': ...,
},
'legacy_db1': {
'ENGINE': 'sql_server.pyodbc',
'NAME': ...,
'TEST': {
'LEGACY': True, # Do not manage this database during tests
},
},
}
希望您能正常运行
manage.py test
。
请注意,该方法无法在并行测试时使用。我对
ParallelTestSuite.init_worker
进行了一些修改,并对
setup_databases
进行了微调,但它还没有完全功能。
旧答案,临时可行:
这不是特别安全的方法,因为此配置选项的语义可能会更改,但您可以声明一个数据库是另一个数据库的“副本”。
DATABASES = {
'default': {
'NAME': 'transactional',
...
},
'analytical': {
'NAME': 'analytical',
...
'TEST': {
'MIRROR': 'default',
},
}
}
MIRROR
配置选项的文档可在此处找到:https://docs.djangoproject.com/en/dev/topics/testing/advanced/#testing-primary-replica-configurations
相关的 Django 源代码在这里:https://github.com/django/django/blob/master/django/test/utils.py