test_base.py 15 KB

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