creation.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import os
  2. import sys
  3. from io import StringIO
  4. from unittest import expectedFailure, skip
  5. from django.apps import apps
  6. from django.conf import settings
  7. from django.core import serializers
  8. from django.db import router
  9. from django.db.transaction import atomic
  10. from django.utils.module_loading import import_string
  11. # The prefix to put on the default database name when creating
  12. # the test database.
  13. TEST_DATABASE_PREFIX = 'test_'
  14. class BaseDatabaseCreation:
  15. """
  16. Encapsulate backend-specific differences pertaining to creation and
  17. destruction of the test database.
  18. """
  19. def __init__(self, connection):
  20. self.connection = connection
  21. def _nodb_cursor(self):
  22. return self.connection._nodb_cursor()
  23. def log(self, msg):
  24. sys.stderr.write(msg + os.linesep)
  25. def create_test_db(self, verbosity=1, autoclobber=False, serialize=True, keepdb=False):
  26. """
  27. Create a test database, prompting the user for confirmation if the
  28. database already exists. Return 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. action = 'Creating'
  35. if keepdb:
  36. action = "Using existing"
  37. self.log('%s test database for alias %s...' % (
  38. action,
  39. self._get_database_display_str(verbosity, test_database_name),
  40. ))
  41. # We could skip this call if keepdb is True, but we instead
  42. # give it the keepdb param. This is to handle the case
  43. # where the test DB doesn't exist, in which case we need to
  44. # create it, then just not destroy it. If we instead skip
  45. # this, we will get an exception.
  46. self._create_test_db(verbosity, autoclobber, keepdb)
  47. self.connection.close()
  48. settings.DATABASES[self.connection.alias]["NAME"] = test_database_name
  49. self.connection.settings_dict["NAME"] = test_database_name
  50. try:
  51. if self.connection.settings_dict['TEST']['MIGRATE'] is False:
  52. # Disable migrations for all apps.
  53. old_migration_modules = settings.MIGRATION_MODULES
  54. settings.MIGRATION_MODULES = {
  55. app.label: None
  56. for app in apps.get_app_configs()
  57. }
  58. # We report migrate messages at one level lower than that
  59. # requested. This ensures we don't get flooded with messages during
  60. # testing (unless you really ask to be flooded).
  61. call_command(
  62. 'migrate',
  63. verbosity=max(verbosity - 1, 0),
  64. interactive=False,
  65. database=self.connection.alias,
  66. run_syncdb=True,
  67. )
  68. finally:
  69. if self.connection.settings_dict['TEST']['MIGRATE'] is False:
  70. settings.MIGRATION_MODULES = old_migration_modules
  71. # We then serialize the current state of the database into a string
  72. # and store it on the connection. This slightly horrific process is so people
  73. # who are testing on databases without transactions or who are using
  74. # a TransactionTestCase still get a clean database on every test run.
  75. if serialize:
  76. self.connection._test_serialized_contents = self.serialize_db_to_string()
  77. call_command('createcachetable', database=self.connection.alias)
  78. # Ensure a connection for the side effect of initializing the test database.
  79. self.connection.ensure_connection()
  80. if os.environ.get('RUNNING_DJANGOS_TEST_SUITE') == 'true':
  81. self.mark_expected_failures_and_skips()
  82. return test_database_name
  83. def set_as_test_mirror(self, primary_settings_dict):
  84. """
  85. Set this database up to be used in testing as a mirror of a primary
  86. database whose settings are given.
  87. """
  88. self.connection.settings_dict['NAME'] = primary_settings_dict['NAME']
  89. def serialize_db_to_string(self):
  90. """
  91. Serialize all data in the database into a JSON string.
  92. Designed only for test runner usage; will not handle large
  93. amounts of data.
  94. """
  95. # Iteratively return every object for all models to serialize.
  96. def get_objects():
  97. from django.db.migrations.loader import MigrationLoader
  98. loader = MigrationLoader(self.connection)
  99. for app_config in apps.get_app_configs():
  100. if (
  101. app_config.models_module is not None and
  102. app_config.label in loader.migrated_apps and
  103. app_config.name not in settings.TEST_NON_SERIALIZED_APPS
  104. ):
  105. for model in app_config.get_models():
  106. if (
  107. model._meta.can_migrate(self.connection) and
  108. router.allow_migrate_model(self.connection.alias, model)
  109. ):
  110. queryset = model._base_manager.using(
  111. self.connection.alias,
  112. ).order_by(model._meta.pk.name)
  113. yield from queryset.iterator()
  114. # Serialize to a string
  115. out = StringIO()
  116. serializers.serialize("json", get_objects(), indent=None, stream=out)
  117. return out.getvalue()
  118. def deserialize_db_from_string(self, data):
  119. """
  120. Reload the database with data from a string generated by
  121. the serialize_db_to_string() method.
  122. """
  123. data = StringIO(data)
  124. table_names = set()
  125. # Load data in a transaction to handle forward references and cycles.
  126. with atomic(using=self.connection.alias):
  127. # Disable constraint checks, because some databases (MySQL) doesn't
  128. # support deferred checks.
  129. with self.connection.constraint_checks_disabled():
  130. for obj in serializers.deserialize('json', data, using=self.connection.alias):
  131. obj.save()
  132. table_names.add(obj.object.__class__._meta.db_table)
  133. # Manually check for any invalid keys that might have been added,
  134. # because constraint checks were disabled.
  135. self.connection.check_constraints(table_names=table_names)
  136. def _get_database_display_str(self, verbosity, database_name):
  137. """
  138. Return display string for a database for use in various actions.
  139. """
  140. return "'%s'%s" % (
  141. self.connection.alias,
  142. (" ('%s')" % database_name) if verbosity >= 2 else '',
  143. )
  144. def _get_test_db_name(self):
  145. """
  146. Internal implementation - return the name of the test DB that will be
  147. created. Only useful when called from create_test_db() and
  148. _create_test_db() and when no external munging is done with the 'NAME'
  149. settings.
  150. """
  151. if self.connection.settings_dict['TEST']['NAME']:
  152. return self.connection.settings_dict['TEST']['NAME']
  153. return TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
  154. def _execute_create_test_db(self, cursor, parameters, keepdb=False):
  155. cursor.execute('CREATE DATABASE %(dbname)s %(suffix)s' % parameters)
  156. def _create_test_db(self, verbosity, autoclobber, keepdb=False):
  157. """
  158. Internal implementation - create the test db tables.
  159. """
  160. test_database_name = self._get_test_db_name()
  161. test_db_params = {
  162. 'dbname': self.connection.ops.quote_name(test_database_name),
  163. 'suffix': self.sql_table_creation_suffix(),
  164. }
  165. # Create the test database and connect to it.
  166. with self._nodb_cursor() as cursor:
  167. try:
  168. self._execute_create_test_db(cursor, test_db_params, keepdb)
  169. except Exception as e:
  170. # if we want to keep the db, then no need to do any of the below,
  171. # just return and skip it all.
  172. if keepdb:
  173. return test_database_name
  174. self.log('Got an error creating the test database: %s' % e)
  175. if not autoclobber:
  176. confirm = input(
  177. "Type 'yes' if you would like to try deleting the test "
  178. "database '%s', or 'no' to cancel: " % test_database_name)
  179. if autoclobber or confirm == 'yes':
  180. try:
  181. if verbosity >= 1:
  182. self.log('Destroying old test database for alias %s...' % (
  183. self._get_database_display_str(verbosity, test_database_name),
  184. ))
  185. cursor.execute('DROP DATABASE %(dbname)s' % test_db_params)
  186. self._execute_create_test_db(cursor, test_db_params, keepdb)
  187. except Exception as e:
  188. self.log('Got an error recreating the test database: %s' % e)
  189. sys.exit(2)
  190. else:
  191. self.log('Tests cancelled.')
  192. sys.exit(1)
  193. return test_database_name
  194. def clone_test_db(self, suffix, verbosity=1, autoclobber=False, keepdb=False):
  195. """
  196. Clone a test database.
  197. """
  198. source_database_name = self.connection.settings_dict['NAME']
  199. if verbosity >= 1:
  200. action = 'Cloning test database'
  201. if keepdb:
  202. action = 'Using existing clone'
  203. self.log('%s for alias %s...' % (
  204. action,
  205. self._get_database_display_str(verbosity, source_database_name),
  206. ))
  207. # We could skip this call if keepdb is True, but we instead
  208. # give it the keepdb param. See create_test_db for details.
  209. self._clone_test_db(suffix, verbosity, keepdb)
  210. def get_test_db_clone_settings(self, suffix):
  211. """
  212. Return a modified connection settings dict for the n-th clone of a DB.
  213. """
  214. # When this function is called, the test database has been created
  215. # already and its name has been copied to settings_dict['NAME'] so
  216. # we don't need to call _get_test_db_name.
  217. orig_settings_dict = self.connection.settings_dict
  218. return {**orig_settings_dict, 'NAME': '{}_{}'.format(orig_settings_dict['NAME'], suffix)}
  219. def _clone_test_db(self, suffix, verbosity, keepdb=False):
  220. """
  221. Internal implementation - duplicate the test db tables.
  222. """
  223. raise NotImplementedError(
  224. "The database backend doesn't support cloning databases. "
  225. "Disable the option to run tests in parallel processes.")
  226. def destroy_test_db(self, old_database_name=None, verbosity=1, keepdb=False, suffix=None):
  227. """
  228. Destroy a test database, prompting the user for confirmation if the
  229. database already exists.
  230. """
  231. self.connection.close()
  232. if suffix is None:
  233. test_database_name = self.connection.settings_dict['NAME']
  234. else:
  235. test_database_name = self.get_test_db_clone_settings(suffix)['NAME']
  236. if verbosity >= 1:
  237. action = 'Destroying'
  238. if keepdb:
  239. action = 'Preserving'
  240. self.log('%s test database for alias %s...' % (
  241. action,
  242. self._get_database_display_str(verbosity, test_database_name),
  243. ))
  244. # if we want to preserve the database
  245. # skip the actual destroying piece.
  246. if not keepdb:
  247. self._destroy_test_db(test_database_name, verbosity)
  248. # Restore the original database name
  249. if old_database_name is not None:
  250. settings.DATABASES[self.connection.alias]["NAME"] = old_database_name
  251. self.connection.settings_dict["NAME"] = old_database_name
  252. def _destroy_test_db(self, test_database_name, verbosity):
  253. """
  254. Internal implementation - remove the test db tables.
  255. """
  256. # Remove the test database to clean up after
  257. # ourselves. Connect to the previous database (not the test database)
  258. # to do so, because it's not allowed to delete a database while being
  259. # connected to it.
  260. with self._nodb_cursor() as cursor:
  261. cursor.execute("DROP DATABASE %s"
  262. % self.connection.ops.quote_name(test_database_name))
  263. def mark_expected_failures_and_skips(self):
  264. """
  265. Mark tests in Django's test suite which are expected failures on this
  266. database and test which should be skipped on this database.
  267. """
  268. for test_name in self.connection.features.django_test_expected_failures:
  269. test_case_name, _, test_method_name = test_name.rpartition('.')
  270. test_app = test_name.split('.')[0]
  271. # Importing a test app that isn't installed raises RuntimeError.
  272. if test_app in settings.INSTALLED_APPS:
  273. test_case = import_string(test_case_name)
  274. test_method = getattr(test_case, test_method_name)
  275. setattr(test_case, test_method_name, expectedFailure(test_method))
  276. for reason, tests in self.connection.features.django_test_skips.items():
  277. for test_name in tests:
  278. test_case_name, _, test_method_name = test_name.rpartition('.')
  279. test_app = test_name.split('.')[0]
  280. # Importing a test app that isn't installed raises RuntimeError.
  281. if test_app in settings.INSTALLED_APPS:
  282. test_case = import_string(test_case_name)
  283. test_method = getattr(test_case, test_method_name)
  284. setattr(test_case, test_method_name, skip(reason)(test_method))
  285. def sql_table_creation_suffix(self):
  286. """
  287. SQL to append to the end of the test table creation statements.
  288. """
  289. return ''
  290. def test_db_signature(self):
  291. """
  292. Return a tuple with elements of self.connection.settings_dict (a
  293. DATABASES setting value) that uniquely identify a database
  294. accordingly to the RDBMS particularities.
  295. """
  296. settings_dict = self.connection.settings_dict
  297. return (
  298. settings_dict['HOST'],
  299. settings_dict['PORT'],
  300. settings_dict['ENGINE'],
  301. self._get_test_db_name(),
  302. )