运行 Django 使用自定义测试运行器对现有数据库进行测试
Run Django tests against an existing database with custom testrunner
我有一个 运行ning Django 2 应用程序连接到 Microsoft SQL 服务器后端。
我们处在一个大环境中,这里的一切都受到非常严格的控制 - 一个用户帐户可以访问包含我的 Django 应用程序的所有表的数据库。
所以我通过各种帖子发现我需要为我的应用程序创建一个 testrunner
- 这很好。我可以覆盖 setup_databases
函数 - 但我不确定 确切地 如何做到这一点。
我的 TestRunner(DiscoverRunner)
看起来像这样:
class ExistingDbTestRunner(DiscoverRunner):
""" A test runner to test without database creation """
def setup_databases(self, **kwargs):
""" Override the database creation defined in parent class """
# force Django to connect to the correct db for tests
connection = self.connections['default']
db_conf = connection.settings_dict
connection.connect()
def teardown_databases(self, old_config, **kwargs):
""" Override the database teardown defined in parent class """
pass
但这失败了 AttributeError: 'ExistingDbTestRunner' object has no attribute 'connections'
我只是想让它使用我在设置中为测试目的设置的 'default' 数据库。
值得注意 - 设置中指定的默认数据库是生产数据库的副本,但名称不同。
所以我只想针对这个重复的数据库运行 进行测试。我应该更改什么才能连接?
Django 测试不在现有数据库上运行,或者旨在以这种方式使用。 Django 总是会为所有测试创建一个名为 test_db_name_specified_in_settings 的新数据库。
可以在此处找到更多文档:https://docs.djangoproject.com/en/2.0/topics/testing/overview/#the-test-database
我有一个 运行ning Django 2 应用程序连接到 Microsoft SQL 服务器后端。
我们处在一个大环境中,这里的一切都受到非常严格的控制 - 一个用户帐户可以访问包含我的 Django 应用程序的所有表的数据库。
所以我通过各种帖子发现我需要为我的应用程序创建一个 testrunner
- 这很好。我可以覆盖 setup_databases
函数 - 但我不确定 确切地 如何做到这一点。
我的 TestRunner(DiscoverRunner)
看起来像这样:
class ExistingDbTestRunner(DiscoverRunner):
""" A test runner to test without database creation """
def setup_databases(self, **kwargs):
""" Override the database creation defined in parent class """
# force Django to connect to the correct db for tests
connection = self.connections['default']
db_conf = connection.settings_dict
connection.connect()
def teardown_databases(self, old_config, **kwargs):
""" Override the database teardown defined in parent class """
pass
但这失败了 AttributeError: 'ExistingDbTestRunner' object has no attribute 'connections'
我只是想让它使用我在设置中为测试目的设置的 'default' 数据库。
值得注意 - 设置中指定的默认数据库是生产数据库的副本,但名称不同。
所以我只想针对这个重复的数据库运行 进行测试。我应该更改什么才能连接?
Django 测试不在现有数据库上运行,或者旨在以这种方式使用。 Django 总是会为所有测试创建一个名为 test_db_name_specified_in_settings 的新数据库。
可以在此处找到更多文档:https://docs.djangoproject.com/en/2.0/topics/testing/overview/#the-test-database