test_commands.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  1. import datetime
  2. import importlib
  3. import io
  4. import os
  5. import sys
  6. from unittest import mock
  7. from django.apps import apps
  8. from django.core.management import CommandError, call_command
  9. from django.db import (
  10. ConnectionHandler, DatabaseError, connection, connections, models,
  11. )
  12. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  13. from django.db.migrations.exceptions import (
  14. InconsistentMigrationHistory, MigrationSchemaMissing,
  15. )
  16. from django.db.migrations.recorder import MigrationRecorder
  17. from django.test import override_settings
  18. from django.utils.encoding import force_text
  19. from .models import UnicodeModel, UnserializableModel
  20. from .routers import TestRouter
  21. from .test_base import MigrationTestBase
  22. class MigrateTests(MigrationTestBase):
  23. """
  24. Tests running the migrate command.
  25. """
  26. multi_db = True
  27. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  28. def test_migrate(self):
  29. """
  30. Tests basic usage of the migrate command.
  31. """
  32. # No tables are created
  33. self.assertTableNotExists("migrations_author")
  34. self.assertTableNotExists("migrations_tribble")
  35. self.assertTableNotExists("migrations_book")
  36. # Run the migrations to 0001 only
  37. call_command("migrate", "migrations", "0001", verbosity=0)
  38. # The correct tables exist
  39. self.assertTableExists("migrations_author")
  40. self.assertTableExists("migrations_tribble")
  41. self.assertTableNotExists("migrations_book")
  42. # Run migrations all the way
  43. call_command("migrate", verbosity=0)
  44. # The correct tables exist
  45. self.assertTableExists("migrations_author")
  46. self.assertTableNotExists("migrations_tribble")
  47. self.assertTableExists("migrations_book")
  48. # Unmigrate everything
  49. call_command("migrate", "migrations", "zero", verbosity=0)
  50. # Tables are gone
  51. self.assertTableNotExists("migrations_author")
  52. self.assertTableNotExists("migrations_tribble")
  53. self.assertTableNotExists("migrations_book")
  54. @override_settings(INSTALLED_APPS=[
  55. 'django.contrib.auth',
  56. 'django.contrib.contenttypes',
  57. 'migrations.migrations_test_apps.migrated_app',
  58. ])
  59. def test_migrate_with_system_checks(self):
  60. out = io.StringIO()
  61. call_command('migrate', skip_checks=False, no_color=True, stdout=out)
  62. self.assertIn('Apply all migrations: migrated_app', out.getvalue())
  63. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"})
  64. def test_migrate_initial_false(self):
  65. """
  66. `Migration.initial = False` skips fake-initial detection.
  67. """
  68. # Make sure no tables are created
  69. self.assertTableNotExists("migrations_author")
  70. self.assertTableNotExists("migrations_tribble")
  71. # Run the migrations to 0001 only
  72. call_command("migrate", "migrations", "0001", verbosity=0)
  73. # Fake rollback
  74. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  75. # Make sure fake-initial detection does not run
  76. with self.assertRaises(DatabaseError):
  77. call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0)
  78. call_command("migrate", "migrations", "0001", fake=True, verbosity=0)
  79. # Real rollback
  80. call_command("migrate", "migrations", "zero", verbosity=0)
  81. # Make sure it's all gone
  82. self.assertTableNotExists("migrations_author")
  83. self.assertTableNotExists("migrations_tribble")
  84. self.assertTableNotExists("migrations_book")
  85. @override_settings(
  86. MIGRATION_MODULES={"migrations": "migrations.test_migrations"},
  87. DATABASE_ROUTERS=['migrations.routers.TestRouter'],
  88. )
  89. def test_migrate_fake_initial(self):
  90. """
  91. --fake-initial only works if all tables created in the initial
  92. migration of an app exists. Database routers must be obeyed when doing
  93. that check.
  94. """
  95. # Make sure no tables are created
  96. for db in connections:
  97. self.assertTableNotExists("migrations_author", using=db)
  98. self.assertTableNotExists("migrations_tribble", using=db)
  99. # Run the migrations to 0001 only
  100. call_command("migrate", "migrations", "0001", verbosity=0)
  101. call_command("migrate", "migrations", "0001", verbosity=0, database="other")
  102. # Make sure the right tables exist
  103. self.assertTableExists("migrations_author")
  104. self.assertTableNotExists("migrations_tribble")
  105. # Also check the "other" database
  106. self.assertTableNotExists("migrations_author", using="other")
  107. self.assertTableExists("migrations_tribble", using="other")
  108. # Fake a roll-back
  109. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  110. call_command("migrate", "migrations", "zero", fake=True, verbosity=0, database="other")
  111. # Make sure the tables still exist
  112. self.assertTableExists("migrations_author")
  113. self.assertTableExists("migrations_tribble", using="other")
  114. # Try to run initial migration
  115. with self.assertRaises(DatabaseError):
  116. call_command("migrate", "migrations", "0001", verbosity=0)
  117. # Run initial migration with an explicit --fake-initial
  118. out = io.StringIO()
  119. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  120. call_command("migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1)
  121. call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0, database="other")
  122. self.assertIn(
  123. "migrations.0001_initial... faked",
  124. out.getvalue().lower()
  125. )
  126. # Run migrations all the way
  127. call_command("migrate", verbosity=0)
  128. call_command("migrate", verbosity=0, database="other")
  129. # Make sure the right tables exist
  130. self.assertTableExists("migrations_author")
  131. self.assertTableNotExists("migrations_tribble")
  132. self.assertTableExists("migrations_book")
  133. self.assertTableNotExists("migrations_author", using="other")
  134. self.assertTableNotExists("migrations_tribble", using="other")
  135. self.assertTableNotExists("migrations_book", using="other")
  136. # Fake a roll-back
  137. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  138. call_command("migrate", "migrations", "zero", fake=True, verbosity=0, database="other")
  139. # Make sure the tables still exist
  140. self.assertTableExists("migrations_author")
  141. self.assertTableNotExists("migrations_tribble")
  142. self.assertTableExists("migrations_book")
  143. # Try to run initial migration
  144. with self.assertRaises(DatabaseError):
  145. call_command("migrate", "migrations", verbosity=0)
  146. # Run initial migration with an explicit --fake-initial
  147. with self.assertRaises(DatabaseError):
  148. # Fails because "migrations_tribble" does not exist but needs to in
  149. # order to make --fake-initial work.
  150. call_command("migrate", "migrations", fake_initial=True, verbosity=0)
  151. # Fake a apply
  152. call_command("migrate", "migrations", fake=True, verbosity=0)
  153. call_command("migrate", "migrations", fake=True, verbosity=0, database="other")
  154. # Unmigrate everything
  155. call_command("migrate", "migrations", "zero", verbosity=0)
  156. call_command("migrate", "migrations", "zero", verbosity=0, database="other")
  157. # Make sure it's all gone
  158. for db in connections:
  159. self.assertTableNotExists("migrations_author", using=db)
  160. self.assertTableNotExists("migrations_tribble", using=db)
  161. self.assertTableNotExists("migrations_book", using=db)
  162. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_fake_split_initial"})
  163. def test_migrate_fake_split_initial(self):
  164. """
  165. Split initial migrations can be faked with --fake-initial.
  166. """
  167. call_command("migrate", "migrations", "0002", verbosity=0)
  168. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  169. out = io.StringIO()
  170. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  171. call_command("migrate", "migrations", "0002", fake_initial=True, stdout=out, verbosity=1)
  172. value = out.getvalue().lower()
  173. self.assertIn("migrations.0001_initial... faked", value)
  174. self.assertIn("migrations.0002_second... faked", value)
  175. # Fake an apply
  176. call_command("migrate", "migrations", fake=True, verbosity=0)
  177. # Unmigrate everything
  178. call_command("migrate", "migrations", "zero", verbosity=0)
  179. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"})
  180. def test_migrate_conflict_exit(self):
  181. """
  182. migrate exits if it detects a conflict.
  183. """
  184. with self.assertRaisesMessage(CommandError, "Conflicting migrations detected"):
  185. call_command("migrate", "migrations")
  186. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  187. def test_showmigrations_list(self):
  188. """
  189. showmigrations --list displays migrations and whether or not they're
  190. applied.
  191. """
  192. out = io.StringIO()
  193. with mock.patch('django.core.management.color.supports_color', lambda *args: True):
  194. call_command("showmigrations", format='list', stdout=out, verbosity=0, no_color=False)
  195. self.assertEqual(
  196. '\x1b[1mmigrations\n\x1b[0m'
  197. ' [ ] 0001_initial\n'
  198. ' [ ] 0002_second\n',
  199. out.getvalue().lower()
  200. )
  201. call_command("migrate", "migrations", "0001", verbosity=0)
  202. out = io.StringIO()
  203. # Giving the explicit app_label tests for selective `show_list` in the command
  204. call_command("showmigrations", "migrations", format='list', stdout=out, verbosity=0, no_color=True)
  205. self.assertEqual(
  206. 'migrations\n'
  207. ' [x] 0001_initial\n'
  208. ' [ ] 0002_second\n',
  209. out.getvalue().lower()
  210. )
  211. # Cleanup by unmigrating everything
  212. call_command("migrate", "migrations", "zero", verbosity=0)
  213. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"})
  214. def test_showmigrations_plan(self):
  215. """
  216. Tests --plan output of showmigrations command
  217. """
  218. out = io.StringIO()
  219. call_command("showmigrations", format='plan', stdout=out)
  220. self.assertEqual(
  221. "[ ] migrations.0001_initial\n"
  222. "[ ] migrations.0003_third\n"
  223. "[ ] migrations.0002_second\n",
  224. out.getvalue().lower()
  225. )
  226. out = io.StringIO()
  227. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  228. self.assertEqual(
  229. "[ ] migrations.0001_initial\n"
  230. "[ ] migrations.0003_third ... (migrations.0001_initial)\n"
  231. "[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
  232. out.getvalue().lower()
  233. )
  234. call_command("migrate", "migrations", "0003", verbosity=0)
  235. out = io.StringIO()
  236. call_command("showmigrations", format='plan', stdout=out)
  237. self.assertEqual(
  238. "[x] migrations.0001_initial\n"
  239. "[x] migrations.0003_third\n"
  240. "[ ] migrations.0002_second\n",
  241. out.getvalue().lower()
  242. )
  243. out = io.StringIO()
  244. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  245. self.assertEqual(
  246. "[x] migrations.0001_initial\n"
  247. "[x] migrations.0003_third ... (migrations.0001_initial)\n"
  248. "[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
  249. out.getvalue().lower()
  250. )
  251. # Cleanup by unmigrating everything
  252. call_command("migrate", "migrations", "zero", verbosity=0)
  253. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"})
  254. def test_showmigrations_plan_no_migrations(self):
  255. """
  256. Tests --plan output of showmigrations command without migrations
  257. """
  258. out = io.StringIO()
  259. call_command("showmigrations", format='plan', stdout=out)
  260. self.assertEqual("", out.getvalue().lower())
  261. out = io.StringIO()
  262. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  263. self.assertEqual("", out.getvalue().lower())
  264. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"})
  265. def test_showmigrations_plan_squashed(self):
  266. """
  267. Tests --plan output of showmigrations command with squashed migrations.
  268. """
  269. out = io.StringIO()
  270. call_command("showmigrations", format='plan', stdout=out)
  271. self.assertEqual(
  272. "[ ] migrations.1_auto\n"
  273. "[ ] migrations.2_auto\n"
  274. "[ ] migrations.3_squashed_5\n"
  275. "[ ] migrations.6_auto\n"
  276. "[ ] migrations.7_auto\n",
  277. out.getvalue().lower()
  278. )
  279. out = io.StringIO()
  280. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  281. self.assertEqual(
  282. "[ ] migrations.1_auto\n"
  283. "[ ] migrations.2_auto ... (migrations.1_auto)\n"
  284. "[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n"
  285. "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
  286. "[ ] migrations.7_auto ... (migrations.6_auto)\n",
  287. out.getvalue().lower()
  288. )
  289. call_command("migrate", "migrations", "3_squashed_5", verbosity=0)
  290. out = io.StringIO()
  291. call_command("showmigrations", format='plan', stdout=out)
  292. self.assertEqual(
  293. "[x] migrations.1_auto\n"
  294. "[x] migrations.2_auto\n"
  295. "[x] migrations.3_squashed_5\n"
  296. "[ ] migrations.6_auto\n"
  297. "[ ] migrations.7_auto\n",
  298. out.getvalue().lower()
  299. )
  300. out = io.StringIO()
  301. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  302. self.assertEqual(
  303. "[x] migrations.1_auto\n"
  304. "[x] migrations.2_auto ... (migrations.1_auto)\n"
  305. "[x] migrations.3_squashed_5 ... (migrations.2_auto)\n"
  306. "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
  307. "[ ] migrations.7_auto ... (migrations.6_auto)\n",
  308. out.getvalue().lower()
  309. )
  310. @override_settings(INSTALLED_APPS=[
  311. 'migrations.migrations_test_apps.mutate_state_b',
  312. 'migrations.migrations_test_apps.alter_fk.author_app',
  313. 'migrations.migrations_test_apps.alter_fk.book_app',
  314. ])
  315. def test_showmigrations_plan_single_app_label(self):
  316. """
  317. `showmigrations --plan app_label` output with a single app_label.
  318. """
  319. # Single app with no dependencies on other apps.
  320. out = io.StringIO()
  321. call_command('showmigrations', 'mutate_state_b', format='plan', stdout=out)
  322. self.assertEqual(
  323. '[ ] mutate_state_b.0001_initial\n'
  324. '[ ] mutate_state_b.0002_add_field\n',
  325. out.getvalue()
  326. )
  327. # Single app with dependencies.
  328. out = io.StringIO()
  329. call_command('showmigrations', 'author_app', format='plan', stdout=out)
  330. self.assertEqual(
  331. '[ ] author_app.0001_initial\n'
  332. '[ ] book_app.0001_initial\n'
  333. '[ ] author_app.0002_alter_id\n',
  334. out.getvalue()
  335. )
  336. # Some migrations already applied.
  337. call_command('migrate', 'author_app', '0001', verbosity=0)
  338. out = io.StringIO()
  339. call_command('showmigrations', 'author_app', format='plan', stdout=out)
  340. self.assertEqual(
  341. '[X] author_app.0001_initial\n'
  342. '[ ] book_app.0001_initial\n'
  343. '[ ] author_app.0002_alter_id\n',
  344. out.getvalue()
  345. )
  346. # Cleanup by unmigrating author_app.
  347. call_command('migrate', 'author_app', 'zero', verbosity=0)
  348. @override_settings(INSTALLED_APPS=[
  349. 'migrations.migrations_test_apps.mutate_state_b',
  350. 'migrations.migrations_test_apps.alter_fk.author_app',
  351. 'migrations.migrations_test_apps.alter_fk.book_app',
  352. ])
  353. def test_showmigrations_plan_multiple_app_labels(self):
  354. """
  355. `showmigrations --plan app_label` output with multiple app_labels.
  356. """
  357. # Multiple apps: author_app depends on book_app; mutate_state_b doesn't
  358. # depend on other apps.
  359. out = io.StringIO()
  360. call_command('showmigrations', 'mutate_state_b', 'author_app', format='plan', stdout=out)
  361. self.assertEqual(
  362. '[ ] author_app.0001_initial\n'
  363. '[ ] book_app.0001_initial\n'
  364. '[ ] author_app.0002_alter_id\n'
  365. '[ ] mutate_state_b.0001_initial\n'
  366. '[ ] mutate_state_b.0002_add_field\n',
  367. out.getvalue()
  368. )
  369. # Multiple apps: args order shouldn't matter (the same result is
  370. # expected as above).
  371. out = io.StringIO()
  372. call_command('showmigrations', 'author_app', 'mutate_state_b', format='plan', stdout=out)
  373. self.assertEqual(
  374. '[ ] author_app.0001_initial\n'
  375. '[ ] book_app.0001_initial\n'
  376. '[ ] author_app.0002_alter_id\n'
  377. '[ ] mutate_state_b.0001_initial\n'
  378. '[ ] mutate_state_b.0002_add_field\n',
  379. out.getvalue()
  380. )
  381. @override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
  382. def test_showmigrations_plan_app_label_error(self):
  383. """
  384. `showmigrations --plan app_label` raises an error when no app or
  385. no migrations are present in provided app labels.
  386. """
  387. # App with no migrations.
  388. with self.assertRaisesMessage(CommandError, 'No migrations present for: unmigrated_app'):
  389. call_command('showmigrations', 'unmigrated_app', format='plan')
  390. # Nonexistent app (wrong app label).
  391. with self.assertRaisesMessage(CommandError, 'No migrations present for: nonexistent_app'):
  392. call_command('showmigrations', 'nonexistent_app', format='plan')
  393. # Multiple nonexistent apps; input order shouldn't matter.
  394. with self.assertRaisesMessage(CommandError, 'No migrations present for: nonexistent_app1, nonexistent_app2'):
  395. call_command('showmigrations', 'nonexistent_app1', 'nonexistent_app2', format='plan')
  396. with self.assertRaisesMessage(CommandError, 'No migrations present for: nonexistent_app1, nonexistent_app2'):
  397. call_command('showmigrations', 'nonexistent_app2', 'nonexistent_app1', format='plan')
  398. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  399. def test_sqlmigrate_forwards(self):
  400. """
  401. sqlmigrate outputs forward looking SQL.
  402. """
  403. out = io.StringIO()
  404. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  405. output = out.getvalue().lower()
  406. index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
  407. index_op_desc_author = output.find('-- create model author')
  408. index_create_table = output.find('create table')
  409. index_op_desc_tribble = output.find('-- create model tribble')
  410. index_op_desc_unique_together = output.find('-- alter unique_together')
  411. index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
  412. self.assertGreater(index_tx_start, -1, "Transaction start not found")
  413. self.assertGreater(
  414. index_op_desc_author, index_tx_start,
  415. "Operation description (author) not found or found before transaction start"
  416. )
  417. self.assertGreater(
  418. index_create_table, index_op_desc_author,
  419. "CREATE TABLE not found or found before operation description (author)"
  420. )
  421. self.assertGreater(
  422. index_op_desc_tribble, index_create_table,
  423. "Operation description (tribble) not found or found before CREATE TABLE (author)"
  424. )
  425. self.assertGreater(
  426. index_op_desc_unique_together, index_op_desc_tribble,
  427. "Operation description (unique_together) not found or found before operation description (tribble)"
  428. )
  429. self.assertGreater(
  430. index_tx_end, index_op_desc_unique_together,
  431. "Transaction end not found or found before operation description (unique_together)"
  432. )
  433. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  434. def test_sqlmigrate_backwards(self):
  435. """
  436. sqlmigrate outputs reverse looking SQL.
  437. """
  438. # Cannot generate the reverse SQL unless we've applied the migration.
  439. call_command("migrate", "migrations", verbosity=0)
  440. out = io.StringIO()
  441. call_command("sqlmigrate", "migrations", "0001", stdout=out, backwards=True)
  442. output = out.getvalue().lower()
  443. index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
  444. index_op_desc_unique_together = output.find('-- alter unique_together')
  445. index_op_desc_tribble = output.find('-- create model tribble')
  446. index_op_desc_author = output.find('-- create model author')
  447. index_drop_table = output.rfind('drop table')
  448. index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
  449. self.assertGreater(index_tx_start, -1, "Transaction start not found")
  450. self.assertGreater(
  451. index_op_desc_unique_together, index_tx_start,
  452. "Operation description (unique_together) not found or found before transaction start"
  453. )
  454. self.assertGreater(
  455. index_op_desc_tribble, index_op_desc_unique_together,
  456. "Operation description (tribble) not found or found before operation description (unique_together)"
  457. )
  458. self.assertGreater(
  459. index_op_desc_author, index_op_desc_tribble,
  460. "Operation description (author) not found or found before operation description (tribble)"
  461. )
  462. self.assertGreater(
  463. index_drop_table, index_op_desc_author,
  464. "DROP TABLE not found or found before operation description (author)"
  465. )
  466. self.assertGreater(
  467. index_tx_end, index_op_desc_unique_together,
  468. "Transaction end not found or found before DROP TABLE"
  469. )
  470. # Cleanup by unmigrating everything
  471. call_command("migrate", "migrations", "zero", verbosity=0)
  472. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"})
  473. def test_sqlmigrate_for_non_atomic_migration(self):
  474. """
  475. Transaction wrappers aren't shown for non-atomic migrations.
  476. """
  477. out = io.StringIO()
  478. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  479. output = out.getvalue().lower()
  480. queries = [q.strip() for q in output.splitlines()]
  481. if connection.ops.start_transaction_sql():
  482. self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)
  483. self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
  484. @override_settings(
  485. INSTALLED_APPS=[
  486. "migrations.migrations_test_apps.migrated_app",
  487. "migrations.migrations_test_apps.migrated_unapplied_app",
  488. "migrations.migrations_test_apps.unmigrated_app",
  489. ],
  490. )
  491. def test_regression_22823_unmigrated_fk_to_migrated_model(self):
  492. """
  493. Assuming you have 3 apps, `A`, `B`, and `C`, such that:
  494. * `A` has migrations
  495. * `B` has a migration we want to apply
  496. * `C` has no migrations, but has an FK to `A`
  497. When we try to migrate "B", an exception occurs because the
  498. "B" was not included in the ProjectState that is used to detect
  499. soft-applied migrations (#22823).
  500. """
  501. call_command("migrate", "migrated_unapplied_app", stdout=io.StringIO())
  502. # unmigrated_app.SillyModel has a foreign key to 'migrations.Tribble',
  503. # but that model is only defined in a migration, so the global app
  504. # registry never sees it and the reference is left dangling. Remove it
  505. # to avoid problems in subsequent tests.
  506. del apps._pending_operations[('migrations', 'tribble')]
  507. @override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app_syncdb'])
  508. def test_migrate_syncdb_deferred_sql_executed_with_schemaeditor(self):
  509. """
  510. For an app without migrations, editor.execute() is used for executing
  511. the syncdb deferred SQL.
  512. """
  513. with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
  514. call_command('migrate', run_syncdb=True, verbosity=0)
  515. create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
  516. self.assertEqual(create_table_count, 2)
  517. # There's at least one deferred SQL for creating the foreign key
  518. # index.
  519. self.assertGreater(len(execute.mock_calls), 2)
  520. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
  521. def test_migrate_record_replaced(self):
  522. """
  523. Running a single squashed migration should record all of the original
  524. replaced migrations as run.
  525. """
  526. recorder = MigrationRecorder(connection)
  527. out = io.StringIO()
  528. call_command("migrate", "migrations", verbosity=0)
  529. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  530. self.assertEqual(
  531. 'migrations\n'
  532. ' [x] 0001_squashed_0002 (2 squashed migrations)\n',
  533. out.getvalue().lower()
  534. )
  535. applied_migrations = recorder.applied_migrations()
  536. self.assertIn(("migrations", "0001_initial"), applied_migrations)
  537. self.assertIn(("migrations", "0002_second"), applied_migrations)
  538. self.assertIn(("migrations", "0001_squashed_0002"), applied_migrations)
  539. # Rollback changes
  540. call_command("migrate", "migrations", "zero", verbosity=0)
  541. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
  542. def test_migrate_record_squashed(self):
  543. """
  544. Running migrate for a squashed migration should record as run
  545. if all of the replaced migrations have been run (#25231).
  546. """
  547. recorder = MigrationRecorder(connection)
  548. recorder.record_applied("migrations", "0001_initial")
  549. recorder.record_applied("migrations", "0002_second")
  550. out = io.StringIO()
  551. call_command("migrate", "migrations", verbosity=0)
  552. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  553. self.assertEqual(
  554. 'migrations\n'
  555. ' [x] 0001_squashed_0002 (2 squashed migrations)\n',
  556. out.getvalue().lower()
  557. )
  558. self.assertIn(
  559. ("migrations", "0001_squashed_0002"),
  560. recorder.applied_migrations()
  561. )
  562. # No changes were actually applied so there is nothing to rollback
  563. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
  564. def test_migrate_inconsistent_history(self):
  565. """
  566. Running migrate with some migrations applied before their dependencies
  567. should not be allowed.
  568. """
  569. recorder = MigrationRecorder(connection)
  570. recorder.record_applied("migrations", "0002_second")
  571. msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
  572. with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
  573. call_command("migrate")
  574. applied_migrations = recorder.applied_migrations()
  575. self.assertNotIn(("migrations", "0001_initial"), applied_migrations)
  576. class MakeMigrationsTests(MigrationTestBase):
  577. """
  578. Tests running the makemigrations command.
  579. """
  580. def setUp(self):
  581. super(MakeMigrationsTests, self).setUp()
  582. self._old_models = apps.app_configs['migrations'].models.copy()
  583. def tearDown(self):
  584. apps.app_configs['migrations'].models = self._old_models
  585. apps.all_models['migrations'] = self._old_models
  586. apps.clear_cache()
  587. super(MakeMigrationsTests, self).tearDown()
  588. def test_files_content(self):
  589. self.assertTableNotExists("migrations_unicodemodel")
  590. apps.register_model('migrations', UnicodeModel)
  591. with self.temporary_migration_module() as migration_dir:
  592. call_command("makemigrations", "migrations", verbosity=0)
  593. # Check for empty __init__.py file in migrations folder
  594. init_file = os.path.join(migration_dir, "__init__.py")
  595. self.assertTrue(os.path.exists(init_file))
  596. with open(init_file, 'r') as fp:
  597. content = force_text(fp.read())
  598. self.assertEqual(content, '')
  599. # Check for existing 0001_initial.py file in migration folder
  600. initial_file = os.path.join(migration_dir, "0001_initial.py")
  601. self.assertTrue(os.path.exists(initial_file))
  602. with open(initial_file, 'r', encoding='utf-8') as fp:
  603. content = fp.read()
  604. self.assertIn('migrations.CreateModel', content)
  605. self.assertIn('initial = True', content)
  606. self.assertIn('úñí©óðé µóðéø', content) # Meta.verbose_name
  607. self.assertIn('úñí©óðé µóðéøß', content) # Meta.verbose_name_plural
  608. self.assertIn('ÚÑÍ¢ÓÐÉ', content) # title.verbose_name
  609. self.assertIn('“Ðjáñgó”', content) # title.default
  610. def test_makemigrations_order(self):
  611. """
  612. makemigrations should recognize number-only migrations (0001.py).
  613. """
  614. module = 'migrations.test_migrations_order'
  615. with self.temporary_migration_module(module=module) as migration_dir:
  616. if hasattr(importlib, 'invalidate_caches'):
  617. # Python 3 importlib caches os.listdir() on some platforms like
  618. # Mac OS X (#23850).
  619. importlib.invalidate_caches()
  620. call_command('makemigrations', 'migrations', '--empty', '-n', 'a', '-v', '0')
  621. self.assertTrue(os.path.exists(os.path.join(migration_dir, '0002_a.py')))
  622. def test_makemigrations_empty_connections(self):
  623. empty_connections = ConnectionHandler({'default': {}})
  624. with mock.patch('django.core.management.commands.makemigrations.connections', new=empty_connections):
  625. # with no apps
  626. out = io.StringIO()
  627. call_command('makemigrations', stdout=out)
  628. self.assertIn('No changes detected', out.getvalue())
  629. # with an app
  630. with self.temporary_migration_module() as migration_dir:
  631. call_command('makemigrations', 'migrations', verbosity=0)
  632. init_file = os.path.join(migration_dir, '__init__.py')
  633. self.assertTrue(os.path.exists(init_file))
  634. @override_settings(INSTALLED_APPS=['migrations', 'migrations2'])
  635. def test_makemigrations_consistency_checks_respect_routers(self):
  636. """
  637. The history consistency checks in makemigrations respect
  638. settings.DATABASE_ROUTERS.
  639. """
  640. def patched_ensure_schema(migration_recorder):
  641. if migration_recorder.connection is connections['other']:
  642. raise MigrationSchemaMissing('Patched')
  643. else:
  644. return mock.DEFAULT
  645. self.assertTableNotExists('migrations_unicodemodel')
  646. apps.register_model('migrations', UnicodeModel)
  647. with mock.patch.object(
  648. MigrationRecorder, 'ensure_schema',
  649. autospec=True, side_effect=patched_ensure_schema) as ensure_schema:
  650. with self.temporary_migration_module() as migration_dir:
  651. call_command("makemigrations", "migrations", verbosity=0)
  652. initial_file = os.path.join(migration_dir, "0001_initial.py")
  653. self.assertTrue(os.path.exists(initial_file))
  654. self.assertEqual(ensure_schema.call_count, 1) # 'default' is checked
  655. # Router says not to migrate 'other' so consistency shouldn't
  656. # be checked.
  657. with self.settings(DATABASE_ROUTERS=['migrations.routers.TestRouter']):
  658. call_command('makemigrations', 'migrations', verbosity=0)
  659. self.assertEqual(ensure_schema.call_count, 2) # 'default' again
  660. # With a router that doesn't prohibit migrating 'other',
  661. # consistency is checked.
  662. with self.settings(DATABASE_ROUTERS=['migrations.routers.EmptyRouter']):
  663. with self.assertRaisesMessage(MigrationSchemaMissing, 'Patched'):
  664. call_command('makemigrations', 'migrations', verbosity=0)
  665. self.assertEqual(ensure_schema.call_count, 4) # 'default' and 'other'
  666. # With a router that doesn't allow migrating on any database,
  667. # no consistency checks are made.
  668. with self.settings(DATABASE_ROUTERS=['migrations.routers.TestRouter']):
  669. with mock.patch.object(TestRouter, 'allow_migrate', return_value=False) as allow_migrate:
  670. call_command('makemigrations', 'migrations', verbosity=0)
  671. allow_migrate.assert_any_call('other', 'migrations', model_name='UnicodeModel')
  672. # allow_migrate() is called with the correct arguments.
  673. self.assertGreater(len(allow_migrate.mock_calls), 0)
  674. for mock_call in allow_migrate.mock_calls:
  675. _, call_args, call_kwargs = mock_call
  676. connection_alias, app_name = call_args
  677. self.assertIn(connection_alias, ['default', 'other'])
  678. # Raises an error if invalid app_name/model_name occurs.
  679. apps.get_app_config(app_name).get_model(call_kwargs['model_name'])
  680. self.assertEqual(ensure_schema.call_count, 4)
  681. def test_failing_migration(self):
  682. # If a migration fails to serialize, it shouldn't generate an empty file. #21280
  683. apps.register_model('migrations', UnserializableModel)
  684. with self.temporary_migration_module() as migration_dir:
  685. with self.assertRaisesMessage(ValueError, 'Cannot serialize'):
  686. call_command("makemigrations", "migrations", verbosity=0)
  687. initial_file = os.path.join(migration_dir, "0001_initial.py")
  688. self.assertFalse(os.path.exists(initial_file))
  689. def test_makemigrations_conflict_exit(self):
  690. """
  691. makemigrations exits if it detects a conflict.
  692. """
  693. with self.temporary_migration_module(module="migrations.test_migrations_conflict"):
  694. with self.assertRaises(CommandError):
  695. call_command("makemigrations")
  696. def test_makemigrations_merge_no_conflict(self):
  697. """
  698. makemigrations exits if in merge mode with no conflicts.
  699. """
  700. out = io.StringIO()
  701. with self.temporary_migration_module(module="migrations.test_migrations"):
  702. call_command("makemigrations", merge=True, stdout=out)
  703. self.assertIn("No conflicts detected to merge.", out.getvalue())
  704. def test_makemigrations_no_app_sys_exit(self):
  705. """
  706. makemigrations exits if a non-existent app is specified.
  707. """
  708. err = io.StringIO()
  709. with self.assertRaises(SystemExit):
  710. call_command("makemigrations", "this_app_does_not_exist", stderr=err)
  711. self.assertIn("'this_app_does_not_exist' could not be found.", err.getvalue())
  712. def test_makemigrations_empty_no_app_specified(self):
  713. """
  714. makemigrations exits if no app is specified with 'empty' mode.
  715. """
  716. with self.assertRaises(CommandError):
  717. call_command("makemigrations", empty=True)
  718. def test_makemigrations_empty_migration(self):
  719. """
  720. makemigrations properly constructs an empty migration.
  721. """
  722. with self.temporary_migration_module() as migration_dir:
  723. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  724. # Check for existing 0001_initial.py file in migration folder
  725. initial_file = os.path.join(migration_dir, "0001_initial.py")
  726. self.assertTrue(os.path.exists(initial_file))
  727. with open(initial_file, 'r', encoding='utf-8') as fp:
  728. content = fp.read()
  729. # Remove all whitespace to check for empty dependencies and operations
  730. content = content.replace(' ', '')
  731. self.assertIn('dependencies=[\n]', content)
  732. self.assertIn('operations=[\n]', content)
  733. @override_settings(MIGRATION_MODULES={"migrations": None})
  734. def test_makemigrations_disabled_migrations_for_app(self):
  735. """
  736. makemigrations raises a nice error when migrations are disabled for an
  737. app.
  738. """
  739. msg = (
  740. "Django can't create migrations for app 'migrations' because migrations "
  741. "have been disabled via the MIGRATION_MODULES setting."
  742. )
  743. with self.assertRaisesMessage(ValueError, msg):
  744. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  745. def test_makemigrations_no_changes_no_apps(self):
  746. """
  747. makemigrations exits when there are no changes and no apps are specified.
  748. """
  749. out = io.StringIO()
  750. call_command("makemigrations", stdout=out)
  751. self.assertIn("No changes detected", out.getvalue())
  752. def test_makemigrations_no_changes(self):
  753. """
  754. makemigrations exits when there are no changes to an app.
  755. """
  756. out = io.StringIO()
  757. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  758. call_command("makemigrations", "migrations", stdout=out)
  759. self.assertIn("No changes detected in app 'migrations'", out.getvalue())
  760. def test_makemigrations_no_apps_initial(self):
  761. """
  762. makemigrations should detect initial is needed on empty migration
  763. modules if no app provided.
  764. """
  765. out = io.StringIO()
  766. with self.temporary_migration_module(module="migrations.test_migrations_empty"):
  767. call_command("makemigrations", stdout=out)
  768. self.assertIn("0001_initial.py", out.getvalue())
  769. def test_makemigrations_migrations_announce(self):
  770. """
  771. makemigrations announces the migration at the default verbosity level.
  772. """
  773. out = io.StringIO()
  774. with self.temporary_migration_module():
  775. call_command("makemigrations", "migrations", stdout=out)
  776. self.assertIn("Migrations for 'migrations'", out.getvalue())
  777. def test_makemigrations_no_common_ancestor(self):
  778. """
  779. makemigrations fails to merge migrations with no common ancestor.
  780. """
  781. with self.assertRaises(ValueError) as context:
  782. with self.temporary_migration_module(module="migrations.test_migrations_no_ancestor"):
  783. call_command("makemigrations", "migrations", merge=True)
  784. exception_message = str(context.exception)
  785. self.assertIn("Could not find common ancestor of", exception_message)
  786. self.assertIn("0002_second", exception_message)
  787. self.assertIn("0002_conflicting_second", exception_message)
  788. def test_makemigrations_interactive_reject(self):
  789. """
  790. makemigrations enters and exits interactive mode properly.
  791. """
  792. # Monkeypatch interactive questioner to auto reject
  793. with mock.patch('builtins.input', mock.Mock(return_value='N')):
  794. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  795. call_command("makemigrations", "migrations", name="merge", merge=True, interactive=True, verbosity=0)
  796. merge_file = os.path.join(migration_dir, '0003_merge.py')
  797. self.assertFalse(os.path.exists(merge_file))
  798. def test_makemigrations_interactive_accept(self):
  799. """
  800. makemigrations enters interactive mode and merges properly.
  801. """
  802. # Monkeypatch interactive questioner to auto accept
  803. with mock.patch('builtins.input', mock.Mock(return_value='y')):
  804. out = io.StringIO()
  805. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  806. call_command("makemigrations", "migrations", name="merge", merge=True, interactive=True, stdout=out)
  807. merge_file = os.path.join(migration_dir, '0003_merge.py')
  808. self.assertTrue(os.path.exists(merge_file))
  809. self.assertIn("Created new merge migration", out.getvalue())
  810. @mock.patch('django.db.migrations.utils.datetime')
  811. def test_makemigrations_default_merge_name(self, mock_datetime):
  812. mock_datetime.datetime.now.return_value = datetime.datetime(2016, 1, 2, 3, 4)
  813. with mock.patch('builtins.input', mock.Mock(return_value='y')):
  814. out = io.StringIO()
  815. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  816. call_command("makemigrations", "migrations", merge=True, interactive=True, stdout=out)
  817. merge_file = os.path.join(migration_dir, '0003_merge_20160102_0304.py')
  818. self.assertTrue(os.path.exists(merge_file))
  819. self.assertIn("Created new merge migration", out.getvalue())
  820. def test_makemigrations_non_interactive_not_null_addition(self):
  821. """
  822. Non-interactive makemigrations fails when a default is missing on a
  823. new not-null field.
  824. """
  825. class SillyModel(models.Model):
  826. silly_field = models.BooleanField(default=False)
  827. silly_int = models.IntegerField()
  828. class Meta:
  829. app_label = "migrations"
  830. out = io.StringIO()
  831. with self.assertRaises(SystemExit):
  832. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  833. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  834. def test_makemigrations_non_interactive_not_null_alteration(self):
  835. """
  836. Non-interactive makemigrations fails when a default is missing on a
  837. field changed to not-null.
  838. """
  839. class Author(models.Model):
  840. name = models.CharField(max_length=255)
  841. slug = models.SlugField()
  842. age = models.IntegerField(default=0)
  843. class Meta:
  844. app_label = "migrations"
  845. out = io.StringIO()
  846. with self.temporary_migration_module(module="migrations.test_migrations"):
  847. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  848. self.assertIn("Alter field slug on author", out.getvalue())
  849. def test_makemigrations_non_interactive_no_model_rename(self):
  850. """
  851. makemigrations adds and removes a possible model rename in
  852. non-interactive mode.
  853. """
  854. class RenamedModel(models.Model):
  855. silly_field = models.BooleanField(default=False)
  856. class Meta:
  857. app_label = "migrations"
  858. out = io.StringIO()
  859. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  860. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  861. self.assertIn("Delete model SillyModel", out.getvalue())
  862. self.assertIn("Create model RenamedModel", out.getvalue())
  863. def test_makemigrations_non_interactive_no_field_rename(self):
  864. """
  865. makemigrations adds and removes a possible field rename in
  866. non-interactive mode.
  867. """
  868. class SillyModel(models.Model):
  869. silly_rename = models.BooleanField(default=False)
  870. class Meta:
  871. app_label = "migrations"
  872. out = io.StringIO()
  873. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  874. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  875. self.assertIn("Remove field silly_field from sillymodel", out.getvalue())
  876. self.assertIn("Add field silly_rename to sillymodel", out.getvalue())
  877. def test_makemigrations_handle_merge(self):
  878. """
  879. makemigrations properly merges the conflicting migrations with --noinput.
  880. """
  881. out = io.StringIO()
  882. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  883. call_command("makemigrations", "migrations", name="merge", merge=True, interactive=False, stdout=out)
  884. merge_file = os.path.join(migration_dir, '0003_merge.py')
  885. self.assertTrue(os.path.exists(merge_file))
  886. output = out.getvalue()
  887. self.assertIn("Merging migrations", output)
  888. self.assertIn("Branch 0002_second", output)
  889. self.assertIn("Branch 0002_conflicting_second", output)
  890. self.assertIn("Created new merge migration", output)
  891. def test_makemigration_merge_dry_run(self):
  892. """
  893. makemigrations respects --dry-run option when fixing migration
  894. conflicts (#24427).
  895. """
  896. out = io.StringIO()
  897. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  898. call_command(
  899. "makemigrations", "migrations", name="merge", dry_run=True,
  900. merge=True, interactive=False, stdout=out,
  901. )
  902. merge_file = os.path.join(migration_dir, '0003_merge.py')
  903. self.assertFalse(os.path.exists(merge_file))
  904. output = out.getvalue()
  905. self.assertIn("Merging migrations", output)
  906. self.assertIn("Branch 0002_second", output)
  907. self.assertIn("Branch 0002_conflicting_second", output)
  908. self.assertNotIn("Created new merge migration", output)
  909. def test_makemigration_merge_dry_run_verbosity_3(self):
  910. """
  911. `makemigrations --merge --dry-run` writes the merge migration file to
  912. stdout with `verbosity == 3` (#24427).
  913. """
  914. out = io.StringIO()
  915. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  916. call_command(
  917. "makemigrations", "migrations", name="merge", dry_run=True,
  918. merge=True, interactive=False, stdout=out, verbosity=3,
  919. )
  920. merge_file = os.path.join(migration_dir, '0003_merge.py')
  921. self.assertFalse(os.path.exists(merge_file))
  922. output = out.getvalue()
  923. self.assertIn("Merging migrations", output)
  924. self.assertIn("Branch 0002_second", output)
  925. self.assertIn("Branch 0002_conflicting_second", output)
  926. self.assertNotIn("Created new merge migration", output)
  927. # Additional output caused by verbosity 3
  928. # The complete merge migration file that would be written
  929. self.assertIn("class Migration(migrations.Migration):", output)
  930. self.assertIn("dependencies = [", output)
  931. self.assertIn("('migrations', '0002_second')", output)
  932. self.assertIn("('migrations', '0002_conflicting_second')", output)
  933. self.assertIn("operations = [", output)
  934. self.assertIn("]", output)
  935. def test_makemigrations_dry_run(self):
  936. """
  937. `makemigrations --dry-run` should not ask for defaults.
  938. """
  939. class SillyModel(models.Model):
  940. silly_field = models.BooleanField(default=False)
  941. silly_date = models.DateField() # Added field without a default
  942. class Meta:
  943. app_label = "migrations"
  944. out = io.StringIO()
  945. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  946. call_command("makemigrations", "migrations", dry_run=True, stdout=out)
  947. # Output the expected changes directly, without asking for defaults
  948. self.assertIn("Add field silly_date to sillymodel", out.getvalue())
  949. def test_makemigrations_dry_run_verbosity_3(self):
  950. """
  951. Allow `makemigrations --dry-run` to output the migrations file to
  952. stdout (with verbosity == 3).
  953. """
  954. class SillyModel(models.Model):
  955. silly_field = models.BooleanField(default=False)
  956. silly_char = models.CharField(default="")
  957. class Meta:
  958. app_label = "migrations"
  959. out = io.StringIO()
  960. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  961. call_command("makemigrations", "migrations", dry_run=True, stdout=out, verbosity=3)
  962. # Normal --dry-run output
  963. self.assertIn("- Add field silly_char to sillymodel", out.getvalue())
  964. # Additional output caused by verbosity 3
  965. # The complete migrations file that would be written
  966. self.assertIn("class Migration(migrations.Migration):", out.getvalue())
  967. self.assertIn("dependencies = [", out.getvalue())
  968. self.assertIn("('migrations', '0001_initial'),", out.getvalue())
  969. self.assertIn("migrations.AddField(", out.getvalue())
  970. self.assertIn("model_name='sillymodel',", out.getvalue())
  971. self.assertIn("name='silly_char',", out.getvalue())
  972. def test_makemigrations_migrations_modules_path_not_exist(self):
  973. """
  974. makemigrations creates migrations when specifying a custom location
  975. for migration files using MIGRATION_MODULES if the custom path
  976. doesn't already exist.
  977. """
  978. class SillyModel(models.Model):
  979. silly_field = models.BooleanField(default=False)
  980. class Meta:
  981. app_label = "migrations"
  982. out = io.StringIO()
  983. migration_module = "migrations.test_migrations_path_doesnt_exist.foo.bar"
  984. with self.temporary_migration_module(module=migration_module) as migration_dir:
  985. call_command("makemigrations", "migrations", stdout=out)
  986. # Migrations file is actually created in the expected path.
  987. initial_file = os.path.join(migration_dir, "0001_initial.py")
  988. self.assertTrue(os.path.exists(initial_file))
  989. # Command output indicates the migration is created.
  990. self.assertIn(" - Create model SillyModel", out.getvalue())
  991. def test_makemigrations_interactive_by_default(self):
  992. """
  993. The user is prompted to merge by default if there are conflicts and
  994. merge is True. Answer negative to differentiate it from behavior when
  995. --noinput is specified.
  996. """
  997. # Monkeypatch interactive questioner to auto reject
  998. out = io.StringIO()
  999. with mock.patch('builtins.input', mock.Mock(return_value='N')):
  1000. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  1001. call_command("makemigrations", "migrations", name="merge", merge=True, stdout=out)
  1002. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1003. # This will fail if interactive is False by default
  1004. self.assertFalse(os.path.exists(merge_file))
  1005. self.assertNotIn("Created new merge migration", out.getvalue())
  1006. @override_settings(
  1007. INSTALLED_APPS=[
  1008. "migrations",
  1009. "migrations.migrations_test_apps.unspecified_app_with_conflict"])
  1010. def test_makemigrations_unspecified_app_with_conflict_no_merge(self):
  1011. """
  1012. makemigrations does not raise a CommandError when an unspecified app
  1013. has conflicting migrations.
  1014. """
  1015. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  1016. call_command("makemigrations", "migrations", merge=False, verbosity=0)
  1017. @override_settings(
  1018. INSTALLED_APPS=[
  1019. "migrations.migrations_test_apps.migrated_app",
  1020. "migrations.migrations_test_apps.unspecified_app_with_conflict"])
  1021. def test_makemigrations_unspecified_app_with_conflict_merge(self):
  1022. """
  1023. makemigrations does not create a merge for an unspecified app even if
  1024. it has conflicting migrations.
  1025. """
  1026. # Monkeypatch interactive questioner to auto accept
  1027. with mock.patch('builtins.input', mock.Mock(return_value='y')):
  1028. out = io.StringIO()
  1029. with self.temporary_migration_module(app_label="migrated_app") as migration_dir:
  1030. call_command("makemigrations", "migrated_app", name="merge", merge=True, interactive=True, stdout=out)
  1031. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1032. self.assertFalse(os.path.exists(merge_file))
  1033. self.assertIn("No conflicts detected to merge.", out.getvalue())
  1034. @override_settings(
  1035. INSTALLED_APPS=[
  1036. "migrations.migrations_test_apps.migrated_app",
  1037. "migrations.migrations_test_apps.conflicting_app_with_dependencies"])
  1038. def test_makemigrations_merge_dont_output_dependency_operations(self):
  1039. """
  1040. makemigrations --merge does not output any operations from apps that
  1041. don't belong to a given app.
  1042. """
  1043. # Monkeypatch interactive questioner to auto accept
  1044. with mock.patch('builtins.input', mock.Mock(return_value='N')):
  1045. out = io.StringIO()
  1046. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  1047. call_command(
  1048. "makemigrations", "conflicting_app_with_dependencies",
  1049. merge=True, interactive=True, stdout=out
  1050. )
  1051. val = out.getvalue().lower()
  1052. self.assertIn('merging conflicting_app_with_dependencies\n', val)
  1053. self.assertIn(
  1054. ' branch 0002_conflicting_second\n'
  1055. ' - create model something\n',
  1056. val
  1057. )
  1058. self.assertIn(
  1059. ' branch 0002_second\n'
  1060. ' - delete model tribble\n'
  1061. ' - remove field silly_field from author\n'
  1062. ' - add field rating to author\n'
  1063. ' - create model book\n',
  1064. val
  1065. )
  1066. def test_makemigrations_with_custom_name(self):
  1067. """
  1068. makemigrations --name generate a custom migration name.
  1069. """
  1070. with self.temporary_migration_module() as migration_dir:
  1071. def cmd(migration_count, migration_name, *args):
  1072. call_command("makemigrations", "migrations", "--verbosity", "0", "--name", migration_name, *args)
  1073. migration_file = os.path.join(migration_dir, "%s_%s.py" % (migration_count, migration_name))
  1074. # Check for existing migration file in migration folder
  1075. self.assertTrue(os.path.exists(migration_file))
  1076. with open(migration_file, "r", encoding="utf-8") as fp:
  1077. content = fp.read()
  1078. content = content.replace(" ", "")
  1079. return content
  1080. # generate an initial migration
  1081. migration_name_0001 = "my_initial_migration"
  1082. content = cmd("0001", migration_name_0001)
  1083. self.assertIn("dependencies=[\n]", content)
  1084. # Python 3 importlib caches os.listdir() on some platforms like
  1085. # Mac OS X (#23850).
  1086. if hasattr(importlib, 'invalidate_caches'):
  1087. importlib.invalidate_caches()
  1088. # generate an empty migration
  1089. migration_name_0002 = "my_custom_migration"
  1090. content = cmd("0002", migration_name_0002, "--empty")
  1091. self.assertIn("dependencies=[\n('migrations','0001_%s'),\n]" % migration_name_0001, content)
  1092. self.assertIn("operations=[\n]", content)
  1093. def test_makemigrations_check(self):
  1094. """
  1095. makemigrations --check should exit with a non-zero status when
  1096. there are changes to an app requiring migrations.
  1097. """
  1098. with self.temporary_migration_module():
  1099. with self.assertRaises(SystemExit):
  1100. call_command("makemigrations", "--check", "migrations", verbosity=0)
  1101. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  1102. call_command("makemigrations", "--check", "migrations", verbosity=0)
  1103. def test_makemigrations_migration_path_output(self):
  1104. """
  1105. makemigrations should print the relative paths to the migrations unless
  1106. they are outside of the current tree, in which case the absolute path
  1107. should be shown.
  1108. """
  1109. out = io.StringIO()
  1110. apps.register_model('migrations', UnicodeModel)
  1111. with self.temporary_migration_module() as migration_dir:
  1112. call_command("makemigrations", "migrations", stdout=out)
  1113. self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
  1114. def test_makemigrations_migration_path_output_valueerror(self):
  1115. """
  1116. makemigrations prints the absolute path if os.path.relpath() raises a
  1117. ValueError when it's impossible to obtain a relative path, e.g. on
  1118. Windows if Django is installed on a different drive than where the
  1119. migration files are created.
  1120. """
  1121. out = io.StringIO()
  1122. with self.temporary_migration_module() as migration_dir:
  1123. with mock.patch('os.path.relpath', side_effect=ValueError):
  1124. call_command('makemigrations', 'migrations', stdout=out)
  1125. self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
  1126. def test_makemigrations_inconsistent_history(self):
  1127. """
  1128. makemigrations should raise InconsistentMigrationHistory exception if
  1129. there are some migrations applied before their dependencies.
  1130. """
  1131. recorder = MigrationRecorder(connection)
  1132. recorder.record_applied('migrations', '0002_second')
  1133. msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
  1134. with self.temporary_migration_module(module="migrations.test_migrations"):
  1135. with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
  1136. call_command("makemigrations")
  1137. @mock.patch('builtins.input', return_value='1')
  1138. @mock.patch('django.db.migrations.questioner.sys.stdin', mock.MagicMock(encoding=sys.getdefaultencoding()))
  1139. def test_makemigrations_auto_now_add_interactive(self, *args):
  1140. """
  1141. makemigrations prompts the user when adding auto_now_add to an existing
  1142. model.
  1143. """
  1144. class Entry(models.Model):
  1145. title = models.CharField(max_length=255)
  1146. creation_date = models.DateTimeField(auto_now_add=True)
  1147. class Meta:
  1148. app_label = 'migrations'
  1149. # Monkeypatch interactive questioner to auto accept
  1150. with mock.patch('django.db.migrations.questioner.sys.stdout', new_callable=io.StringIO) as prompt_stdout:
  1151. out = io.StringIO()
  1152. with self.temporary_migration_module(module='migrations.test_auto_now_add'):
  1153. call_command('makemigrations', 'migrations', interactive=True, stdout=out)
  1154. output = out.getvalue()
  1155. prompt_output = prompt_stdout.getvalue()
  1156. self.assertIn("You can accept the default 'timezone.now' by pressing 'Enter'", prompt_output)
  1157. self.assertIn("Add field creation_date to entry", output)
  1158. class SquashMigrationsTests(MigrationTestBase):
  1159. """
  1160. Tests running the squashmigrations command.
  1161. """
  1162. def test_squashmigrations_squashes(self):
  1163. """
  1164. squashmigrations squashes migrations.
  1165. """
  1166. with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
  1167. call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
  1168. squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
  1169. self.assertTrue(os.path.exists(squashed_migration_file))
  1170. def test_squashmigrations_initial_attribute(self):
  1171. with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
  1172. call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
  1173. squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
  1174. with open(squashed_migration_file, "r", encoding="utf-8") as fp:
  1175. content = fp.read()
  1176. self.assertIn("initial = True", content)
  1177. def test_squashmigrations_optimizes(self):
  1178. """
  1179. squashmigrations optimizes operations.
  1180. """
  1181. out = io.StringIO()
  1182. with self.temporary_migration_module(module="migrations.test_migrations"):
  1183. call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=1, stdout=out)
  1184. self.assertIn("Optimized from 8 operations to 3 operations.", out.getvalue())
  1185. def test_ticket_23799_squashmigrations_no_optimize(self):
  1186. """
  1187. squashmigrations --no-optimize doesn't optimize operations.
  1188. """
  1189. out = io.StringIO()
  1190. with self.temporary_migration_module(module="migrations.test_migrations"):
  1191. call_command("squashmigrations", "migrations", "0002",
  1192. interactive=False, verbosity=1, no_optimize=True, stdout=out)
  1193. self.assertIn("Skipping optimization", out.getvalue())
  1194. def test_squashmigrations_valid_start(self):
  1195. """
  1196. squashmigrations accepts a starting migration.
  1197. """
  1198. out = io.StringIO()
  1199. with self.temporary_migration_module(module="migrations.test_migrations_no_changes") as migration_dir:
  1200. call_command("squashmigrations", "migrations", "0002", "0003",
  1201. interactive=False, verbosity=1, stdout=out)
  1202. squashed_migration_file = os.path.join(migration_dir, "0002_second_squashed_0003_third.py")
  1203. with open(squashed_migration_file, "r", encoding="utf-8") as fp:
  1204. content = fp.read()
  1205. self.assertIn(" ('migrations', '0001_initial')", content)
  1206. self.assertNotIn("initial = True", content)
  1207. out = out.getvalue()
  1208. self.assertNotIn(" - 0001_initial", out)
  1209. self.assertIn(" - 0002_second", out)
  1210. self.assertIn(" - 0003_third", out)
  1211. def test_squashmigrations_invalid_start(self):
  1212. """
  1213. squashmigrations doesn't accept a starting migration after the ending migration.
  1214. """
  1215. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  1216. msg = (
  1217. "The migration 'migrations.0003_third' cannot be found. Maybe "
  1218. "it comes after the migration 'migrations.0002_second'"
  1219. )
  1220. with self.assertRaisesMessage(CommandError, msg):
  1221. call_command("squashmigrations", "migrations", "0003", "0002", interactive=False, verbosity=0)