Django test to use existing database

后端 未结 3 1423
再見小時候
再見小時候 2020-12-09 03:32

I\'m having a hard time customizing the test database setup behavior. I would like to achieve the following:

  • The test suites need to use an existing database
相关标签:
3条回答
  • 2020-12-09 04:10

    This TEST_RUNNER works in Django 1.3

    from django.test.simple import DjangoTestSuiteRunner as TestRunner
    
    class DjangoTestSuiteRunner(TestRunner):
        def setup_databases(self, **kwargs):
            pass
    
        def teardown_databases(self, old_config, **kwargs):
            pass
    
    0 讨论(0)
  • 2020-12-09 04:10

    You'll need to provide a custom test runner.

    The bits your interested in overriding with the default django.test.runner.DiscoverRunner are the DiscoverRunner.setup_databases and DiscoverRunner.teardown_databases methods. These two methods are involved with creating and destroying test databases and are executed only once. You'll want to provide test-specific project settings that use your existing test database by default and override these so that the dump data is loaded and the test database isn't destroyed.

    Depending on the size and contents of the dump, a safe bet might be to just create a subprocess that will pipe the dump to your database's SQL command-line interface, otherwise you might be able to obtain a cursor and execute queries directly.

    If your looking to get rid of fixture loading completely, you can provide a custom base test case that extends Django's default django.test.testcases.TestCase with the TestCase._fixutre_setup and TestCase._fixutre_teardown methods overriden to be noop.

    Caveat emptor: this runner will make it impossible to facilitate tests for anything but your application's sources. It's possible to customize the runner to create a specific alias for a connection to your existing database and load the dump, then provide a custom test case that overrides TestCase._database_names to point to it's alias.

    0 讨论(0)
  • 2020-12-09 04:21

    Fast forward to 2016 and the ability to retain the database between tests has been built into django. It's available in the form of the --keep flag to manage.py

    New in Django 1.8. Preserves the test database between test runs. This has the advantage of skipping both the create and destroy actions which can greatly decrease the time to run tests, especially those in a large test suite. If the test database does not exist, it will be created on the first run and then preserved for each subsequent run. Any unapplied migrations will also be applied to the test database before running the test suite.

    This pretty much fullfills all the criteria you have mentioned in your questions. In fact it even goes one step further. There is no need to import the dump before each and every run.

    0 讨论(0)
提交回复
热议问题