test_base.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import os
  2. import shutil
  3. import tempfile
  4. from contextlib import contextmanager
  5. from importlib import import_module
  6. from django.apps import apps
  7. from django.db import connection, connections, migrations, models
  8. from django.db.migrations.migration import Migration
  9. from django.db.migrations.recorder import MigrationRecorder
  10. from django.db.migrations.state import ProjectState
  11. from django.test import TransactionTestCase
  12. from django.test.utils import extend_sys_path
  13. from django.utils.module_loading import module_dir
  14. class MigrationTestBase(TransactionTestCase):
  15. """
  16. Contains an extended set of asserts for testing migrations and schema operations.
  17. """
  18. available_apps = ["migrations"]
  19. databases = {"default", "other"}
  20. def tearDown(self):
  21. # Reset applied-migrations state.
  22. for db in self.databases:
  23. recorder = MigrationRecorder(connections[db])
  24. recorder.migration_qs.filter(app="migrations").delete()
  25. def get_table_description(self, table, using="default"):
  26. with connections[using].cursor() as cursor:
  27. return connections[using].introspection.get_table_description(cursor, table)
  28. def assertTableExists(self, table, using="default"):
  29. with connections[using].cursor() as cursor:
  30. self.assertIn(table, connections[using].introspection.table_names(cursor))
  31. def assertTableNotExists(self, table, using="default"):
  32. with connections[using].cursor() as cursor:
  33. self.assertNotIn(
  34. table, connections[using].introspection.table_names(cursor)
  35. )
  36. def assertColumnExists(self, table, column, using="default"):
  37. self.assertIn(
  38. column, [c.name for c in self.get_table_description(table, using=using)]
  39. )
  40. def assertColumnNotExists(self, table, column, using="default"):
  41. self.assertNotIn(
  42. column, [c.name for c in self.get_table_description(table, using=using)]
  43. )
  44. def _get_column_allows_null(self, table, column, using):
  45. return [
  46. c.null_ok
  47. for c in self.get_table_description(table, using=using)
  48. if c.name == column
  49. ][0]
  50. def assertColumnNull(self, table, column, using="default"):
  51. self.assertTrue(self._get_column_allows_null(table, column, using))
  52. def assertColumnNotNull(self, table, column, using="default"):
  53. self.assertFalse(self._get_column_allows_null(table, column, using))
  54. def _get_column_collation(self, table, column, using):
  55. return next(
  56. f.collation
  57. for f in self.get_table_description(table, using=using)
  58. if f.name == column
  59. )
  60. def assertColumnCollation(self, table, column, collation, using="default"):
  61. self.assertEqual(self._get_column_collation(table, column, using), collation)
  62. def assertIndexExists(
  63. self, table, columns, value=True, using="default", index_type=None
  64. ):
  65. with connections[using].cursor() as cursor:
  66. self.assertEqual(
  67. value,
  68. any(
  69. c["index"]
  70. for c in connections[using]
  71. .introspection.get_constraints(cursor, table)
  72. .values()
  73. if (
  74. c["columns"] == list(columns)
  75. and (index_type is None or c["type"] == index_type)
  76. and not c["unique"]
  77. )
  78. ),
  79. )
  80. def assertIndexNotExists(self, table, columns):
  81. return self.assertIndexExists(table, columns, False)
  82. def assertIndexNameExists(self, table, index, using="default"):
  83. with connections[using].cursor() as cursor:
  84. self.assertIn(
  85. index,
  86. connection.introspection.get_constraints(cursor, table),
  87. )
  88. def assertIndexNameNotExists(self, table, index, using="default"):
  89. with connections[using].cursor() as cursor:
  90. self.assertNotIn(
  91. index,
  92. connection.introspection.get_constraints(cursor, table),
  93. )
  94. def assertConstraintExists(self, table, name, value=True, using="default"):
  95. with connections[using].cursor() as cursor:
  96. constraints = (
  97. connections[using].introspection.get_constraints(cursor, table).items()
  98. )
  99. self.assertEqual(
  100. value,
  101. any(c["check"] for n, c in constraints if n == name),
  102. )
  103. def assertConstraintNotExists(self, table, name):
  104. return self.assertConstraintExists(table, name, False)
  105. def assertUniqueConstraintExists(self, table, columns, value=True, using="default"):
  106. with connections[using].cursor() as cursor:
  107. constraints = (
  108. connections[using].introspection.get_constraints(cursor, table).values()
  109. )
  110. self.assertEqual(
  111. value,
  112. any(c["unique"] for c in constraints if c["columns"] == list(columns)),
  113. )
  114. def assertFKExists(self, table, columns, to, value=True, using="default"):
  115. if not connections[using].features.can_introspect_foreign_keys:
  116. return
  117. with connections[using].cursor() as cursor:
  118. self.assertEqual(
  119. value,
  120. any(
  121. c["foreign_key"] == to
  122. for c in connections[using]
  123. .introspection.get_constraints(cursor, table)
  124. .values()
  125. if c["columns"] == list(columns)
  126. ),
  127. )
  128. def assertFKNotExists(self, table, columns, to):
  129. return self.assertFKExists(table, columns, to, False)
  130. @contextmanager
  131. def temporary_migration_module(self, app_label="migrations", module=None):
  132. """
  133. Allows testing management commands in a temporary migrations module.
  134. Wrap all invocations to makemigrations and squashmigrations with this
  135. context manager in order to avoid creating migration files in your
  136. source tree inadvertently.
  137. Takes the application label that will be passed to makemigrations or
  138. squashmigrations and the Python path to a migrations module.
  139. The migrations module is used as a template for creating the temporary
  140. migrations module. If it isn't provided, the application's migrations
  141. module is used, if it exists.
  142. Returns the filesystem path to the temporary migrations module.
  143. """
  144. with tempfile.TemporaryDirectory() as temp_dir:
  145. target_dir = tempfile.mkdtemp(dir=temp_dir)
  146. with open(os.path.join(target_dir, "__init__.py"), "w"):
  147. pass
  148. target_migrations_dir = os.path.join(target_dir, "migrations")
  149. if module is None:
  150. module = apps.get_app_config(app_label).name + ".migrations"
  151. try:
  152. source_migrations_dir = module_dir(import_module(module))
  153. except (ImportError, ValueError):
  154. pass
  155. else:
  156. shutil.copytree(source_migrations_dir, target_migrations_dir)
  157. with extend_sys_path(temp_dir):
  158. new_module = os.path.basename(target_dir) + ".migrations"
  159. with self.settings(MIGRATION_MODULES={app_label: new_module}):
  160. yield target_migrations_dir
  161. class OperationTestBase(MigrationTestBase):
  162. """Common functions to help test operations."""
  163. @classmethod
  164. def setUpClass(cls):
  165. super().setUpClass()
  166. cls._initial_table_names = frozenset(connection.introspection.table_names())
  167. def tearDown(self):
  168. self.cleanup_test_tables()
  169. super().tearDown()
  170. def cleanup_test_tables(self):
  171. table_names = (
  172. frozenset(connection.introspection.table_names())
  173. - self._initial_table_names
  174. )
  175. with connection.schema_editor() as editor:
  176. with connection.constraint_checks_disabled():
  177. for table_name in table_names:
  178. editor.execute(
  179. editor.sql_delete_table
  180. % {
  181. "table": editor.quote_name(table_name),
  182. }
  183. )
  184. def apply_operations(self, app_label, project_state, operations, atomic=True):
  185. migration = Migration("name", app_label)
  186. migration.operations = operations
  187. with connection.schema_editor(atomic=atomic) as editor:
  188. return migration.apply(project_state, editor)
  189. def unapply_operations(self, app_label, project_state, operations, atomic=True):
  190. migration = Migration("name", app_label)
  191. migration.operations = operations
  192. with connection.schema_editor(atomic=atomic) as editor:
  193. return migration.unapply(project_state, editor)
  194. def make_test_state(self, app_label, operation, **kwargs):
  195. """
  196. Makes a test state using set_up_test_model and returns the
  197. original state and the state after the migration is applied.
  198. """
  199. project_state = self.set_up_test_model(app_label, **kwargs)
  200. new_state = project_state.clone()
  201. operation.state_forwards(app_label, new_state)
  202. return project_state, new_state
  203. def set_up_test_model(
  204. self,
  205. app_label,
  206. second_model=False,
  207. third_model=False,
  208. index=False,
  209. multicol_index=False,
  210. related_model=False,
  211. mti_model=False,
  212. proxy_model=False,
  213. manager_model=False,
  214. unique_together=False,
  215. options=False,
  216. db_table=None,
  217. index_together=False, # RemovedInDjango51Warning.
  218. constraints=None,
  219. indexes=None,
  220. ):
  221. """Creates a test model state and database table."""
  222. # Make the "current" state.
  223. model_options = {
  224. "swappable": "TEST_SWAP_MODEL",
  225. # RemovedInDjango51Warning.
  226. "index_together": [["weight", "pink"]] if index_together else [],
  227. "unique_together": [["pink", "weight"]] if unique_together else [],
  228. }
  229. if options:
  230. model_options["permissions"] = [("can_groom", "Can groom")]
  231. if db_table:
  232. model_options["db_table"] = db_table
  233. operations = [
  234. migrations.CreateModel(
  235. "Pony",
  236. [
  237. ("id", models.AutoField(primary_key=True)),
  238. ("pink", models.IntegerField(default=3)),
  239. ("weight", models.FloatField()),
  240. ],
  241. options=model_options,
  242. )
  243. ]
  244. if index:
  245. operations.append(
  246. migrations.AddIndex(
  247. "Pony",
  248. models.Index(fields=["pink"], name="pony_pink_idx"),
  249. )
  250. )
  251. if multicol_index:
  252. operations.append(
  253. migrations.AddIndex(
  254. "Pony",
  255. models.Index(fields=["pink", "weight"], name="pony_test_idx"),
  256. )
  257. )
  258. if indexes:
  259. for index in indexes:
  260. operations.append(migrations.AddIndex("Pony", index))
  261. if constraints:
  262. for constraint in constraints:
  263. operations.append(migrations.AddConstraint("Pony", constraint))
  264. if second_model:
  265. operations.append(
  266. migrations.CreateModel(
  267. "Stable",
  268. [
  269. ("id", models.AutoField(primary_key=True)),
  270. ],
  271. )
  272. )
  273. if third_model:
  274. operations.append(
  275. migrations.CreateModel(
  276. "Van",
  277. [
  278. ("id", models.AutoField(primary_key=True)),
  279. ],
  280. )
  281. )
  282. if related_model:
  283. operations.append(
  284. migrations.CreateModel(
  285. "Rider",
  286. [
  287. ("id", models.AutoField(primary_key=True)),
  288. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  289. (
  290. "friend",
  291. models.ForeignKey("self", models.CASCADE, null=True),
  292. ),
  293. ],
  294. )
  295. )
  296. if mti_model:
  297. operations.append(
  298. migrations.CreateModel(
  299. "ShetlandPony",
  300. fields=[
  301. (
  302. "pony_ptr",
  303. models.OneToOneField(
  304. "Pony",
  305. models.CASCADE,
  306. auto_created=True,
  307. parent_link=True,
  308. primary_key=True,
  309. to_field="id",
  310. serialize=False,
  311. ),
  312. ),
  313. ("cuteness", models.IntegerField(default=1)),
  314. ],
  315. bases=["%s.Pony" % app_label],
  316. )
  317. )
  318. if proxy_model:
  319. operations.append(
  320. migrations.CreateModel(
  321. "ProxyPony",
  322. fields=[],
  323. options={"proxy": True},
  324. bases=["%s.Pony" % app_label],
  325. )
  326. )
  327. if manager_model:
  328. from .models import FoodManager, FoodQuerySet
  329. operations.append(
  330. migrations.CreateModel(
  331. "Food",
  332. fields=[
  333. ("id", models.AutoField(primary_key=True)),
  334. ],
  335. managers=[
  336. ("food_qs", FoodQuerySet.as_manager()),
  337. ("food_mgr", FoodManager("a", "b")),
  338. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  339. ],
  340. )
  341. )
  342. return self.apply_operations(app_label, ProjectState(), operations)