Wednesday, February 9, 2011

How Django's test client replaces the current database with a test one..

Django stores this information inside the self.connection.settings_dict, which gets replaced with test_database_name when a test database is created. This create_test_db() gets invoked by its various Django management commands to setup a test database.

def create_test_db(self, verbosity=1, autoclobber=False):
        Creates a test database, prompting the user for confirmation if the                                                                                                       
        database already exists. Returns the name of the test database created.                                                                                                   
        if verbosity >= 1:
            print "Creating test database '%s'..." % self.connection.alias

        test_database_name = self._create_test_db(verbosity, autoclobber)

        self.connection.settings_dict["NAME"] = test_database_name
        can_rollback = self._rollback_works()
        self.connection.settings_dict["SUPPORTS_TRANSACTIONS"] = can_rollback

        call_command('syncdb', verbosity=verbosity, interactive=False, database=self.connection.alias)

        if settings.CACHE_BACKEND.startswith('db://'):
            from django.core.cache import parse_backend_uri, cache
            from django.db import router
            if router.allow_syncdb(self.connection.alias, cache.cache_model_class):
                _, cache_name, _ = parse_backend_uri(settings.CACHE_BACKEND)
                call_command('createcachetable', cache_name, database=self.connection.alias)

        # Get a cursor (even though we don't need one yet). This has                                                                                                              
        # the side effect of initializing the test database.                                                                                                                      
        cursor = self.connection.cursor()

        return test_database_name

Also, within the code, the TEST_NAME determines the database name. If it doesn't exist, the TEST_DATABASE_PREFIX is used:
     if self.connection.settings_dict['TEST_NAME']:
            test_database_name = self.connection.settings_dict['TEST_NAME']
            test_database_name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']

No comments:

Post a Comment