首页 > 解决方案 > 使用自定义测试运行程序对现有数据库运行 Django 测试

问题描述

我有一个运行 Django 2 的应用程序,它连接到 Microsoft SQL Server 后端。

我们处于一个非常严格控制的大环境中 - 用户帐户可以访问包含我的 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'

我只是想让它使用我在设置中设置的用于测试目的的“默认”数据库。

值得注意的是 - 设置中指定的默认数据库是生产数据库的副本,但名称不同。

所以我只想让我的测试针对这个重复的数据库运行。我应该改变什么才能连接?

标签: djangounit-testingdjango-testingdjango-teststest-runner

解决方案


Django 测试不在现有数据库上运行,也不打算以这种方式使用。Django 总是为它的所有测试创建一个名为 test_db_name_specified_in_settings 的新数据库。

更多文档可以在这里找到:https ://docs.djangoproject.com/en/2.0/topics/testing/overview/#the-test-database


推荐阅读