creation.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import sys
  2. import time
  3. from django.apps import apps
  4. from django.conf import settings
  5. from django.core import serializers
  6. from django.db import router
  7. from django.utils.six import StringIO
  8. from django.utils.six.moves import input
  9. # The prefix to put on the default database name when creating
  10. # the test database.
  11. TEST_DATABASE_PREFIX = 'test_'
  12. class BaseDatabaseCreation(object):
  13. """
  14. This class encapsulates all backend-specific differences that pertain to
  15. creation and destruction of the test database.
  16. """
  17. def __init__(self, connection):
  18. self.connection = connection
  19. @property
  20. def _nodb_connection(self):
  21. """
  22. Used to be defined here, now moved to DatabaseWrapper.
  23. """
  24. return self.connection._nodb_connection
  25. def create_test_db(self, verbosity=1, autoclobber=False, serialize=True, keepdb=False):
  26. """
  27. Creates a test database, prompting the user for confirmation if the
  28. database already exists. Returns the name of the test database created.
  29. """
  30. # Don't import django.core.management if it isn't needed.
  31. from django.core.management import call_command
  32. test_database_name = self._get_test_db_name()
  33. if verbosity >= 1:
  34. test_db_repr = ''
  35. action = 'Creating'
  36. if verbosity >= 2:
  37. test_db_repr = " ('%s')" % test_database_name
  38. if keepdb:
  39. action = "Using existing"
  40. print("%s test database for alias '%s'%s..." % (
  41. action, self.connection.alias, test_db_repr))
  42. # We could skip this call if keepdb is True, but we instead
  43. # give it the keepdb param. This is to handle the case
  44. # where the test DB doesn't exist, in which case we need to
  45. # create it, then just not destroy it. If we instead skip
  46. # this, we will get an exception.
  47. self._create_test_db(verbosity, autoclobber, keepdb)
  48. self.connection.close()
  49. settings.DATABASES[self.connection.alias]["NAME"] = test_database_name
  50. self.connection.settings_dict["NAME"] = test_database_name
  51. # We report migrate messages at one level lower than that requested.
  52. # This ensures we don't get flooded with messages during testing
  53. # (unless you really ask to be flooded).
  54. call_command(
  55. 'migrate',
  56. verbosity=max(verbosity - 1, 0),
  57. interactive=False,
  58. database=self.connection.alias,
  59. run_syncdb=True,
  60. )
  61. # We then serialize the current state of the database into a string
  62. # and store it on the connection. This slightly horrific process is so people
  63. # who are testing on databases without transactions or who are using
  64. # a TransactionTestCase still get a clean database on every test run.
  65. if serialize:
  66. self.connection._test_serialized_contents = self.serialize_db_to_string()
  67. call_command('createcachetable', database=self.connection.alias)
  68. # Ensure a connection for the side effect of initializing the test database.
  69. self.connection.ensure_connection()
  70. return test_database_name
  71. def serialize_db_to_string(self):
  72. """
  73. Serializes all data in the database into a JSON string.
  74. Designed only for test runner usage; will not handle large
  75. amounts of data.
  76. """
  77. # Build list of all apps to serialize
  78. from django.db.migrations.loader import MigrationLoader
  79. loader = MigrationLoader(self.connection)
  80. app_list = []
  81. for app_config in apps.get_app_configs():
  82. if (
  83. app_config.models_module is not None and
  84. app_config.label in loader.migrated_apps and
  85. app_config.name not in settings.TEST_NON_SERIALIZED_APPS
  86. ):
  87. app_list.append((app_config, None))
  88. # Make a function to iteratively return every object
  89. def get_objects():
  90. for model in serializers.sort_dependencies(app_list):
  91. if (not model._meta.proxy and model._meta.managed and
  92. router.allow_migrate_model(self.connection.alias, model)):
  93. queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
  94. for obj in queryset.iterator():
  95. yield obj
  96. # Serialize to a string
  97. out = StringIO()
  98. serializers.serialize("json", get_objects(), indent=None, stream=out)
  99. return out.getvalue()
  100. def deserialize_db_from_string(self, data):
  101. """
  102. Reloads the database with data from a string generated by
  103. the serialize_db_to_string method.
  104. """
  105. data = StringIO(data)
  106. for obj in serializers.deserialize("json", data, using=self.connection.alias):
  107. obj.save()
  108. def _get_test_db_name(self):
  109. """
  110. Internal implementation - returns the name of the test DB that will be
  111. created. Only useful when called from create_test_db() and
  112. _create_test_db() and when no external munging is done with the 'NAME'
  113. or 'TEST_NAME' settings.
  114. """
  115. if self.connection.settings_dict['TEST']['NAME']:
  116. return self.connection.settings_dict['TEST']['NAME']
  117. return TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
  118. def _create_test_db(self, verbosity, autoclobber, keepdb=False):
  119. """
  120. Internal implementation - creates the test db tables.
  121. """
  122. suffix = self.sql_table_creation_suffix()
  123. test_database_name = self._get_test_db_name()
  124. qn = self.connection.ops.quote_name
  125. # Create the test database and connect to it.
  126. with self._nodb_connection.cursor() as cursor:
  127. try:
  128. cursor.execute(
  129. "CREATE DATABASE %s %s" % (qn(test_database_name), suffix))
  130. except Exception as e:
  131. # if we want to keep the db, then no need to do any of the below,
  132. # just return and skip it all.
  133. if keepdb:
  134. return test_database_name
  135. sys.stderr.write(
  136. "Got an error creating the test database: %s\n" % e)
  137. if not autoclobber:
  138. confirm = input(
  139. "Type 'yes' if you would like to try deleting the test "
  140. "database '%s', or 'no' to cancel: " % test_database_name)
  141. if autoclobber or confirm == 'yes':
  142. try:
  143. if verbosity >= 1:
  144. print("Destroying old test database '%s'..."
  145. % self.connection.alias)
  146. cursor.execute(
  147. "DROP DATABASE %s" % qn(test_database_name))
  148. cursor.execute(
  149. "CREATE DATABASE %s %s" % (qn(test_database_name),
  150. suffix))
  151. except Exception as e:
  152. sys.stderr.write(
  153. "Got an error recreating the test database: %s\n" % e)
  154. sys.exit(2)
  155. else:
  156. print("Tests cancelled.")
  157. sys.exit(1)
  158. return test_database_name
  159. def destroy_test_db(self, old_database_name, verbosity=1, keepdb=False):
  160. """
  161. Destroy a test database, prompting the user for confirmation if the
  162. database already exists.
  163. """
  164. self.connection.close()
  165. test_database_name = self.connection.settings_dict['NAME']
  166. if verbosity >= 1:
  167. test_db_repr = ''
  168. action = 'Destroying'
  169. if verbosity >= 2:
  170. test_db_repr = " ('%s')" % test_database_name
  171. if keepdb:
  172. action = 'Preserving'
  173. print("%s test database for alias '%s'%s..." % (
  174. action, self.connection.alias, test_db_repr))
  175. # if we want to preserve the database
  176. # skip the actual destroying piece.
  177. if not keepdb:
  178. self._destroy_test_db(test_database_name, verbosity)
  179. # Restore the original database name
  180. settings.DATABASES[self.connection.alias]["NAME"] = old_database_name
  181. self.connection.settings_dict["NAME"] = old_database_name
  182. def _destroy_test_db(self, test_database_name, verbosity):
  183. """
  184. Internal implementation - remove the test db tables.
  185. """
  186. # Remove the test database to clean up after
  187. # ourselves. Connect to the previous database (not the test database)
  188. # to do so, because it's not allowed to delete a database while being
  189. # connected to it.
  190. with self._nodb_connection.cursor() as cursor:
  191. # Wait to avoid "database is being accessed by other users" errors.
  192. time.sleep(1)
  193. cursor.execute("DROP DATABASE %s"
  194. % self.connection.ops.quote_name(test_database_name))
  195. def sql_table_creation_suffix(self):
  196. """
  197. SQL to append to the end of the test table creation statements.
  198. """
  199. return ''
  200. def test_db_signature(self):
  201. """
  202. Returns a tuple with elements of self.connection.settings_dict (a
  203. DATABASES setting value) that uniquely identify a database
  204. accordingly to the RDBMS particularities.
  205. """
  206. settings_dict = self.connection.settings_dict
  207. return (
  208. settings_dict['HOST'],
  209. settings_dict['PORT'],
  210. settings_dict['ENGINE'],
  211. settings_dict['NAME']
  212. )