123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244 |
- import sys
- import time
- from django.apps import apps
- from django.conf import settings
- from django.core import serializers
- from django.db import router
- from django.utils.six import StringIO
- from django.utils.six.moves import input
- TEST_DATABASE_PREFIX = 'test_'
- class BaseDatabaseCreation(object):
- """
- This class encapsulates all backend-specific differences that pertain to
- creation and destruction of the test database.
- """
- def __init__(self, connection):
- self.connection = connection
- @property
- def _nodb_connection(self):
- """
- Used to be defined here, now moved to DatabaseWrapper.
- """
- return self.connection._nodb_connection
- def create_test_db(self, verbosity=1, autoclobber=False, serialize=True, keepdb=False):
- """
- Creates a test database, prompting the user for confirmation if the
- database already exists. Returns the name of the test database created.
- """
-
- from django.core.management import call_command
- test_database_name = self._get_test_db_name()
- if verbosity >= 1:
- test_db_repr = ''
- action = 'Creating'
- if verbosity >= 2:
- test_db_repr = " ('%s')" % test_database_name
- if keepdb:
- action = "Using existing"
- print("%s test database for alias '%s'%s..." % (
- action, self.connection.alias, test_db_repr))
-
-
-
-
-
- self._create_test_db(verbosity, autoclobber, keepdb)
- self.connection.close()
- settings.DATABASES[self.connection.alias]["NAME"] = test_database_name
- self.connection.settings_dict["NAME"] = test_database_name
-
-
-
- call_command(
- 'migrate',
- verbosity=max(verbosity - 1, 0),
- interactive=False,
- database=self.connection.alias,
- run_syncdb=True,
- )
-
-
-
-
- if serialize:
- self.connection._test_serialized_contents = self.serialize_db_to_string()
- call_command('createcachetable', database=self.connection.alias)
-
- self.connection.ensure_connection()
- return test_database_name
- def serialize_db_to_string(self):
- """
- Serializes all data in the database into a JSON string.
- Designed only for test runner usage; will not handle large
- amounts of data.
- """
-
- from django.db.migrations.loader import MigrationLoader
- loader = MigrationLoader(self.connection)
- app_list = []
- for app_config in apps.get_app_configs():
- if (
- app_config.models_module is not None and
- app_config.label in loader.migrated_apps and
- app_config.name not in settings.TEST_NON_SERIALIZED_APPS
- ):
- app_list.append((app_config, None))
-
- def get_objects():
- for model in serializers.sort_dependencies(app_list):
- if (not model._meta.proxy and model._meta.managed and
- router.allow_migrate_model(self.connection.alias, model)):
- queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
- for obj in queryset.iterator():
- yield obj
-
- out = StringIO()
- serializers.serialize("json", get_objects(), indent=None, stream=out)
- return out.getvalue()
- def deserialize_db_from_string(self, data):
- """
- Reloads the database with data from a string generated by
- the serialize_db_to_string method.
- """
- data = StringIO(data)
- for obj in serializers.deserialize("json", data, using=self.connection.alias):
- obj.save()
- def _get_test_db_name(self):
- """
- Internal implementation - returns the name of the test DB that will be
- created. Only useful when called from create_test_db() and
- _create_test_db() and when no external munging is done with the 'NAME'
- or 'TEST_NAME' settings.
- """
- if self.connection.settings_dict['TEST']['NAME']:
- return self.connection.settings_dict['TEST']['NAME']
- return TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
- def _create_test_db(self, verbosity, autoclobber, keepdb=False):
- """
- Internal implementation - creates the test db tables.
- """
- suffix = self.sql_table_creation_suffix()
- test_database_name = self._get_test_db_name()
- qn = self.connection.ops.quote_name
-
- with self._nodb_connection.cursor() as cursor:
- try:
- cursor.execute(
- "CREATE DATABASE %s %s" % (qn(test_database_name), suffix))
- except Exception as e:
-
-
- if keepdb:
- return test_database_name
- sys.stderr.write(
- "Got an error creating the test database: %s\n" % e)
- if not autoclobber:
- confirm = input(
- "Type 'yes' if you would like to try deleting the test "
- "database '%s', or 'no' to cancel: " % test_database_name)
- if autoclobber or confirm == 'yes':
- try:
- if verbosity >= 1:
- print("Destroying old test database '%s'..."
- % self.connection.alias)
- cursor.execute(
- "DROP DATABASE %s" % qn(test_database_name))
- cursor.execute(
- "CREATE DATABASE %s %s" % (qn(test_database_name),
- suffix))
- except Exception as e:
- sys.stderr.write(
- "Got an error recreating the test database: %s\n" % e)
- sys.exit(2)
- else:
- print("Tests cancelled.")
- sys.exit(1)
- return test_database_name
- def destroy_test_db(self, old_database_name, verbosity=1, keepdb=False):
- """
- Destroy a test database, prompting the user for confirmation if the
- database already exists.
- """
- self.connection.close()
- test_database_name = self.connection.settings_dict['NAME']
- if verbosity >= 1:
- test_db_repr = ''
- action = 'Destroying'
- if verbosity >= 2:
- test_db_repr = " ('%s')" % test_database_name
- if keepdb:
- action = 'Preserving'
- print("%s test database for alias '%s'%s..." % (
- action, self.connection.alias, test_db_repr))
-
-
- if not keepdb:
- self._destroy_test_db(test_database_name, verbosity)
-
- settings.DATABASES[self.connection.alias]["NAME"] = old_database_name
- self.connection.settings_dict["NAME"] = old_database_name
- def _destroy_test_db(self, test_database_name, verbosity):
- """
- Internal implementation - remove the test db tables.
- """
-
-
-
-
- with self._nodb_connection.cursor() as cursor:
-
- time.sleep(1)
- cursor.execute("DROP DATABASE %s"
- % self.connection.ops.quote_name(test_database_name))
- def sql_table_creation_suffix(self):
- """
- SQL to append to the end of the test table creation statements.
- """
- return ''
- def test_db_signature(self):
- """
- Returns a tuple with elements of self.connection.settings_dict (a
- DATABASES setting value) that uniquely identify a database
- accordingly to the RDBMS particularities.
- """
- settings_dict = self.connection.settings_dict
- return (
- settings_dict['HOST'],
- settings_dict['PORT'],
- settings_dict['ENGINE'],
- settings_dict['NAME']
- )
|