You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

creation.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import os
  2. import sys
  3. from io import StringIO
  4. from django.apps import apps
  5. from django.conf import settings
  6. from django.core import serializers
  7. from django.db import router
  8. # The prefix to put on the default database name when creating
  9. # the test database.
  10. TEST_DATABASE_PREFIX = 'test_'
  11. class BaseDatabaseCreation:
  12. """
  13. Encapsulate backend-specific differences pertaining to creation and
  14. destruction of the test database.
  15. """
  16. def __init__(self, connection):
  17. self.connection = connection
  18. @property
  19. def _nodb_connection(self):
  20. """
  21. Used to be defined here, now moved to DatabaseWrapper.
  22. """
  23. return self.connection._nodb_connection
  24. def log(self, msg):
  25. sys.stderr.write(msg + os.linesep)
  26. def create_test_db(self, verbosity=1, autoclobber=False, serialize=True, keepdb=False):
  27. """
  28. Create a test database, prompting the user for confirmation if the
  29. database already exists. Return the name of the test database created.
  30. """
  31. # Don't import django.core.management if it isn't needed.
  32. from django.core.management import call_command
  33. test_database_name = self._get_test_db_name()
  34. if verbosity >= 1:
  35. action = 'Creating'
  36. if keepdb:
  37. action = "Using existing"
  38. self.log('%s test database for alias %s...' % (
  39. action,
  40. self._get_database_display_str(verbosity, test_database_name),
  41. ))
  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 set_as_test_mirror(self, primary_settings_dict):
  72. """
  73. Set this database up to be used in testing as a mirror of a primary
  74. database whose settings are given.
  75. """
  76. self.connection.settings_dict['NAME'] = primary_settings_dict['NAME']
  77. def serialize_db_to_string(self):
  78. """
  79. Serialize all data in the database into a JSON string.
  80. Designed only for test runner usage; will not handle large
  81. amounts of data.
  82. """
  83. # Build list of all apps to serialize
  84. from django.db.migrations.loader import MigrationLoader
  85. loader = MigrationLoader(self.connection)
  86. app_list = []
  87. for app_config in apps.get_app_configs():
  88. if (
  89. app_config.models_module is not None and
  90. app_config.label in loader.migrated_apps and
  91. app_config.name not in settings.TEST_NON_SERIALIZED_APPS
  92. ):
  93. app_list.append((app_config, None))
  94. # Make a function to iteratively return every object
  95. def get_objects():
  96. for model in serializers.sort_dependencies(app_list):
  97. if (model._meta.can_migrate(self.connection) and
  98. router.allow_migrate_model(self.connection.alias, model)):
  99. queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
  100. yield from queryset.iterator()
  101. # Serialize to a string
  102. out = StringIO()
  103. serializers.serialize("json", get_objects(), indent=None, stream=out)
  104. return out.getvalue()
  105. def deserialize_db_from_string(self, data):
  106. """
  107. Reload the database with data from a string generated by
  108. the serialize_db_to_string() method.
  109. """
  110. data = StringIO(data)
  111. for obj in serializers.deserialize("json", data, using=self.connection.alias):
  112. obj.save()
  113. def _get_database_display_str(self, verbosity, database_name):
  114. """
  115. Return display string for a database for use in various actions.
  116. """
  117. return "'%s'%s" % (
  118. self.connection.alias,
  119. (" ('%s')" % database_name) if verbosity >= 2 else '',
  120. )
  121. def _get_test_db_name(self):
  122. """
  123. Internal implementation - return the name of the test DB that will be
  124. created. Only useful when called from create_test_db() and
  125. _create_test_db() and when no external munging is done with the 'NAME'
  126. settings.
  127. """
  128. if self.connection.settings_dict['TEST']['NAME']:
  129. return self.connection.settings_dict['TEST']['NAME']
  130. return TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
  131. def _execute_create_test_db(self, cursor, parameters, keepdb=False):
  132. cursor.execute('CREATE DATABASE %(dbname)s %(suffix)s' % parameters)
  133. def _create_test_db(self, verbosity, autoclobber, keepdb=False):
  134. """
  135. Internal implementation - create the test db tables.
  136. """
  137. test_database_name = self._get_test_db_name()
  138. test_db_params = {
  139. 'dbname': self.connection.ops.quote_name(test_database_name),
  140. 'suffix': self.sql_table_creation_suffix(),
  141. }
  142. # Create the test database and connect to it.
  143. with self._nodb_connection.cursor() as cursor:
  144. try:
  145. self._execute_create_test_db(cursor, test_db_params, keepdb)
  146. except Exception as e:
  147. # if we want to keep the db, then no need to do any of the below,
  148. # just return and skip it all.
  149. if keepdb:
  150. return test_database_name
  151. self.log('Got an error creating the test database: %s' % e)
  152. if not autoclobber:
  153. confirm = input(
  154. "Type 'yes' if you would like to try deleting the test "
  155. "database '%s', or 'no' to cancel: " % test_database_name)
  156. if autoclobber or confirm == 'yes':
  157. try:
  158. if verbosity >= 1:
  159. self.log('Destroying old test database for alias %s...' % (
  160. self._get_database_display_str(verbosity, test_database_name),
  161. ))
  162. cursor.execute('DROP DATABASE %(dbname)s' % test_db_params)
  163. self._execute_create_test_db(cursor, test_db_params, keepdb)
  164. except Exception as e:
  165. self.log('Got an error recreating the test database: %s' % e)
  166. sys.exit(2)
  167. else:
  168. self.log('Tests cancelled.')
  169. sys.exit(1)
  170. return test_database_name
  171. def clone_test_db(self, suffix, verbosity=1, autoclobber=False, keepdb=False):
  172. """
  173. Clone a test database.
  174. """
  175. source_database_name = self.connection.settings_dict['NAME']
  176. if verbosity >= 1:
  177. action = 'Cloning test database'
  178. if keepdb:
  179. action = 'Using existing clone'
  180. self.log('%s for alias %s...' % (
  181. action,
  182. self._get_database_display_str(verbosity, source_database_name),
  183. ))
  184. # We could skip this call if keepdb is True, but we instead
  185. # give it the keepdb param. See create_test_db for details.
  186. self._clone_test_db(suffix, verbosity, keepdb)
  187. def get_test_db_clone_settings(self, suffix):
  188. """
  189. Return a modified connection settings dict for the n-th clone of a DB.
  190. """
  191. # When this function is called, the test database has been created
  192. # already and its name has been copied to settings_dict['NAME'] so
  193. # we don't need to call _get_test_db_name.
  194. orig_settings_dict = self.connection.settings_dict
  195. return {**orig_settings_dict, 'NAME': '{}_{}'.format(orig_settings_dict['NAME'], suffix)}
  196. def _clone_test_db(self, suffix, verbosity, keepdb=False):
  197. """
  198. Internal implementation - duplicate the test db tables.
  199. """
  200. raise NotImplementedError(
  201. "The database backend doesn't support cloning databases. "
  202. "Disable the option to run tests in parallel processes.")
  203. def destroy_test_db(self, old_database_name=None, verbosity=1, keepdb=False, suffix=None):
  204. """
  205. Destroy a test database, prompting the user for confirmation if the
  206. database already exists.
  207. """
  208. self.connection.close()
  209. if suffix is None:
  210. test_database_name = self.connection.settings_dict['NAME']
  211. else:
  212. test_database_name = self.get_test_db_clone_settings(suffix)['NAME']
  213. if verbosity >= 1:
  214. action = 'Destroying'
  215. if keepdb:
  216. action = 'Preserving'
  217. self.log('%s test database for alias %s...' % (
  218. action,
  219. self._get_database_display_str(verbosity, test_database_name),
  220. ))
  221. # if we want to preserve the database
  222. # skip the actual destroying piece.
  223. if not keepdb:
  224. self._destroy_test_db(test_database_name, verbosity)
  225. # Restore the original database name
  226. if old_database_name is not None:
  227. settings.DATABASES[self.connection.alias]["NAME"] = old_database_name
  228. self.connection.settings_dict["NAME"] = old_database_name
  229. def _destroy_test_db(self, test_database_name, verbosity):
  230. """
  231. Internal implementation - remove the test db tables.
  232. """
  233. # Remove the test database to clean up after
  234. # ourselves. Connect to the previous database (not the test database)
  235. # to do so, because it's not allowed to delete a database while being
  236. # connected to it.
  237. with self.connection._nodb_connection.cursor() as cursor:
  238. cursor.execute("DROP DATABASE %s"
  239. % self.connection.ops.quote_name(test_database_name))
  240. def sql_table_creation_suffix(self):
  241. """
  242. SQL to append to the end of the test table creation statements.
  243. """
  244. return ''
  245. def test_db_signature(self):
  246. """
  247. Return a tuple with elements of self.connection.settings_dict (a
  248. DATABASES setting value) that uniquely identify a database
  249. accordingly to the RDBMS particularities.
  250. """
  251. settings_dict = self.connection.settings_dict
  252. return (
  253. settings_dict['HOST'],
  254. settings_dict['PORT'],
  255. settings_dict['ENGINE'],
  256. self._get_test_db_name(),
  257. )