test_commands.py 62 KB

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