test_commands.py 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  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, OperationalError, connection,
  11. connections, models,
  12. )
  13. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  14. from django.db.backends.utils import truncate_name
  15. from django.db.migrations.exceptions import InconsistentMigrationHistory
  16. from django.db.migrations.recorder import MigrationRecorder
  17. from django.test import TestCase, override_settings, skipUnlessDBFeature
  18. from django.test.utils import captured_stdout
  19. from django.utils import timezone
  20. from django.utils.version import get_docs_version
  21. from .models import UnicodeModel, UnserializableModel
  22. from .routers import TestRouter
  23. from .test_base import MigrationTestBase
  24. class MigrateTests(MigrationTestBase):
  25. """
  26. Tests running the migrate command.
  27. """
  28. databases = {'default', 'other'}
  29. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  30. def test_migrate(self):
  31. """
  32. Tests basic usage of the migrate command.
  33. """
  34. # No tables are created
  35. self.assertTableNotExists("migrations_author")
  36. self.assertTableNotExists("migrations_tribble")
  37. self.assertTableNotExists("migrations_book")
  38. # Run the migrations to 0001 only
  39. stdout = io.StringIO()
  40. call_command('migrate', 'migrations', '0001', verbosity=2, stdout=stdout, no_color=True)
  41. stdout = stdout.getvalue()
  42. self.assertIn('Target specific migration: 0001_initial, from migrations', stdout)
  43. self.assertIn('Applying migrations.0001_initial... OK', stdout)
  44. self.assertIn('Running pre-migrate handlers for application migrations', stdout)
  45. self.assertIn('Running post-migrate handlers for application migrations', stdout)
  46. # The correct tables exist
  47. self.assertTableExists("migrations_author")
  48. self.assertTableExists("migrations_tribble")
  49. self.assertTableNotExists("migrations_book")
  50. # Run migrations all the way
  51. call_command("migrate", verbosity=0)
  52. # The correct tables exist
  53. self.assertTableExists("migrations_author")
  54. self.assertTableNotExists("migrations_tribble")
  55. self.assertTableExists("migrations_book")
  56. # Unmigrate everything
  57. stdout = io.StringIO()
  58. call_command('migrate', 'migrations', 'zero', verbosity=2, stdout=stdout, no_color=True)
  59. stdout = stdout.getvalue()
  60. self.assertIn('Unapply all migrations: migrations', stdout)
  61. self.assertIn('Unapplying migrations.0002_second... OK', stdout)
  62. self.assertIn('Running pre-migrate handlers for application migrations', stdout)
  63. self.assertIn('Running post-migrate handlers for application migrations', stdout)
  64. # Tables are gone
  65. self.assertTableNotExists("migrations_author")
  66. self.assertTableNotExists("migrations_tribble")
  67. self.assertTableNotExists("migrations_book")
  68. @override_settings(INSTALLED_APPS=[
  69. 'django.contrib.auth',
  70. 'django.contrib.contenttypes',
  71. 'migrations.migrations_test_apps.migrated_app',
  72. ])
  73. def test_migrate_with_system_checks(self):
  74. out = io.StringIO()
  75. call_command('migrate', skip_checks=False, no_color=True, stdout=out)
  76. self.assertIn('Apply all migrations: migrated_app', out.getvalue())
  77. @override_settings(INSTALLED_APPS=['migrations', 'migrations.migrations_test_apps.unmigrated_app_syncdb'])
  78. def test_app_without_migrations(self):
  79. msg = "App 'unmigrated_app_syncdb' does not have migrations."
  80. with self.assertRaisesMessage(CommandError, msg):
  81. call_command('migrate', app_label='unmigrated_app_syncdb')
  82. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_clashing_prefix'})
  83. def test_ambiguous_prefix(self):
  84. msg = (
  85. "More than one migration matches 'a' in app 'migrations'. Please "
  86. "be more specific."
  87. )
  88. with self.assertRaisesMessage(CommandError, msg):
  89. call_command('migrate', app_label='migrations', migration_name='a')
  90. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
  91. def test_unknown_prefix(self):
  92. msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'."
  93. with self.assertRaisesMessage(CommandError, msg):
  94. call_command('migrate', app_label='migrations', migration_name='nonexistent')
  95. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"})
  96. def test_migrate_initial_false(self):
  97. """
  98. `Migration.initial = False` skips fake-initial detection.
  99. """
  100. # Make sure no tables are created
  101. self.assertTableNotExists("migrations_author")
  102. self.assertTableNotExists("migrations_tribble")
  103. # Run the migrations to 0001 only
  104. call_command("migrate", "migrations", "0001", verbosity=0)
  105. # Fake rollback
  106. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  107. # Make sure fake-initial detection does not run
  108. with self.assertRaises(DatabaseError):
  109. call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0)
  110. call_command("migrate", "migrations", "0001", fake=True, verbosity=0)
  111. # Real rollback
  112. call_command("migrate", "migrations", "zero", verbosity=0)
  113. # Make sure it's all gone
  114. self.assertTableNotExists("migrations_author")
  115. self.assertTableNotExists("migrations_tribble")
  116. self.assertTableNotExists("migrations_book")
  117. @override_settings(
  118. MIGRATION_MODULES={"migrations": "migrations.test_migrations"},
  119. DATABASE_ROUTERS=['migrations.routers.TestRouter'],
  120. )
  121. def test_migrate_fake_initial(self):
  122. """
  123. --fake-initial only works if all tables created in the initial
  124. migration of an app exists. Database routers must be obeyed when doing
  125. that check.
  126. """
  127. # Make sure no tables are created
  128. for db in self.databases:
  129. self.assertTableNotExists("migrations_author", using=db)
  130. self.assertTableNotExists("migrations_tribble", using=db)
  131. # Run the migrations to 0001 only
  132. call_command("migrate", "migrations", "0001", verbosity=0)
  133. call_command("migrate", "migrations", "0001", verbosity=0, database="other")
  134. # Make sure the right tables exist
  135. self.assertTableExists("migrations_author")
  136. self.assertTableNotExists("migrations_tribble")
  137. # Also check the "other" database
  138. self.assertTableNotExists("migrations_author", using="other")
  139. self.assertTableExists("migrations_tribble", using="other")
  140. # Fake a roll-back
  141. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  142. call_command("migrate", "migrations", "zero", fake=True, verbosity=0, database="other")
  143. # Make sure the tables still exist
  144. self.assertTableExists("migrations_author")
  145. self.assertTableExists("migrations_tribble", using="other")
  146. # Try to run initial migration
  147. with self.assertRaises(DatabaseError):
  148. call_command("migrate", "migrations", "0001", verbosity=0)
  149. # Run initial migration with an explicit --fake-initial
  150. out = io.StringIO()
  151. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  152. call_command("migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1)
  153. call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0, database="other")
  154. self.assertIn(
  155. "migrations.0001_initial... faked",
  156. out.getvalue().lower()
  157. )
  158. try:
  159. # Run migrations all the way.
  160. call_command('migrate', verbosity=0)
  161. call_command('migrate', verbosity=0, database="other")
  162. self.assertTableExists('migrations_author')
  163. self.assertTableNotExists('migrations_tribble')
  164. self.assertTableExists('migrations_book')
  165. self.assertTableNotExists('migrations_author', using='other')
  166. self.assertTableNotExists('migrations_tribble', using='other')
  167. self.assertTableNotExists('migrations_book', using='other')
  168. # Fake a roll-back.
  169. call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0)
  170. call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0, database='other')
  171. self.assertTableExists('migrations_author')
  172. self.assertTableNotExists('migrations_tribble')
  173. self.assertTableExists('migrations_book')
  174. # Run initial migration.
  175. with self.assertRaises(DatabaseError):
  176. call_command('migrate', 'migrations', verbosity=0)
  177. # Run initial migration with an explicit --fake-initial.
  178. with self.assertRaises(DatabaseError):
  179. # Fails because "migrations_tribble" does not exist but needs
  180. # to in order to make --fake-initial work.
  181. call_command('migrate', 'migrations', fake_initial=True, verbosity=0)
  182. # Fake an apply.
  183. call_command('migrate', 'migrations', fake=True, verbosity=0)
  184. call_command('migrate', 'migrations', fake=True, verbosity=0, database='other')
  185. finally:
  186. # Unmigrate everything.
  187. call_command('migrate', 'migrations', 'zero', verbosity=0)
  188. call_command('migrate', 'migrations', 'zero', verbosity=0, database='other')
  189. # Make sure it's all gone
  190. for db in self.databases:
  191. self.assertTableNotExists("migrations_author", using=db)
  192. self.assertTableNotExists("migrations_tribble", using=db)
  193. self.assertTableNotExists("migrations_book", using=db)
  194. @skipUnlessDBFeature('ignores_table_name_case')
  195. def test_migrate_fake_initial_case_insensitive(self):
  196. with override_settings(MIGRATION_MODULES={
  197. 'migrations': 'migrations.test_fake_initial_case_insensitive.initial',
  198. }):
  199. call_command('migrate', 'migrations', '0001', verbosity=0)
  200. call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0)
  201. with override_settings(MIGRATION_MODULES={
  202. 'migrations': 'migrations.test_fake_initial_case_insensitive.fake_initial',
  203. }):
  204. out = io.StringIO()
  205. call_command(
  206. 'migrate',
  207. 'migrations',
  208. '0001',
  209. fake_initial=True,
  210. stdout=out,
  211. verbosity=1,
  212. no_color=True,
  213. )
  214. self.assertIn(
  215. 'migrations.0001_initial... faked',
  216. out.getvalue().lower(),
  217. )
  218. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_fake_split_initial"})
  219. def test_migrate_fake_split_initial(self):
  220. """
  221. Split initial migrations can be faked with --fake-initial.
  222. """
  223. try:
  224. call_command('migrate', 'migrations', '0002', verbosity=0)
  225. call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0)
  226. out = io.StringIO()
  227. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  228. call_command('migrate', 'migrations', '0002', fake_initial=True, stdout=out, verbosity=1)
  229. value = out.getvalue().lower()
  230. self.assertIn('migrations.0001_initial... faked', value)
  231. self.assertIn('migrations.0002_second... faked', value)
  232. finally:
  233. # Fake an apply.
  234. call_command('migrate', 'migrations', fake=True, verbosity=0)
  235. # Unmigrate everything.
  236. call_command('migrate', 'migrations', 'zero', verbosity=0)
  237. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"})
  238. def test_migrate_conflict_exit(self):
  239. """
  240. migrate exits if it detects a conflict.
  241. """
  242. msg = (
  243. "Conflicting migrations detected; multiple leaf nodes in the "
  244. "migration graph: (0002_conflicting_second, 0002_second in "
  245. "migrations).\n"
  246. "To fix them run 'python manage.py makemigrations --merge'"
  247. )
  248. with self.assertRaisesMessage(CommandError, msg):
  249. call_command("migrate", "migrations")
  250. @override_settings(MIGRATION_MODULES={
  251. 'migrations': 'migrations.test_migrations',
  252. })
  253. def test_migrate_check(self):
  254. with self.assertRaises(SystemExit):
  255. call_command('migrate', 'migrations', '0001', check_unapplied=True)
  256. self.assertTableNotExists('migrations_author')
  257. self.assertTableNotExists('migrations_tribble')
  258. self.assertTableNotExists('migrations_book')
  259. @override_settings(MIGRATION_MODULES={
  260. 'migrations': 'migrations.test_migrations_plan',
  261. })
  262. def test_migrate_check_plan(self):
  263. out = io.StringIO()
  264. with self.assertRaises(SystemExit):
  265. call_command(
  266. 'migrate',
  267. 'migrations',
  268. '0001',
  269. check_unapplied=True,
  270. plan=True,
  271. stdout=out,
  272. no_color=True,
  273. )
  274. self.assertEqual(
  275. 'Planned operations:\n'
  276. 'migrations.0001_initial\n'
  277. ' Create model Salamander\n'
  278. ' Raw Python operation -> Grow salamander tail.\n',
  279. out.getvalue(),
  280. )
  281. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  282. def test_showmigrations_list(self):
  283. """
  284. showmigrations --list displays migrations and whether or not they're
  285. applied.
  286. """
  287. out = io.StringIO()
  288. with mock.patch('django.core.management.color.supports_color', lambda *args: True):
  289. call_command("showmigrations", format='list', stdout=out, verbosity=0, no_color=False)
  290. self.assertEqual(
  291. '\x1b[1mmigrations\n\x1b[0m'
  292. ' [ ] 0001_initial\n'
  293. ' [ ] 0002_second\n',
  294. out.getvalue().lower()
  295. )
  296. call_command("migrate", "migrations", "0001", verbosity=0)
  297. out = io.StringIO()
  298. # Giving the explicit app_label tests for selective `show_list` in the command
  299. call_command("showmigrations", "migrations", format='list', stdout=out, verbosity=0, no_color=True)
  300. self.assertEqual(
  301. 'migrations\n'
  302. ' [x] 0001_initial\n'
  303. ' [ ] 0002_second\n',
  304. out.getvalue().lower()
  305. )
  306. out = io.StringIO()
  307. # Applied datetimes are displayed at verbosity 2+.
  308. call_command('showmigrations', 'migrations', stdout=out, verbosity=2, no_color=True)
  309. migration1 = MigrationRecorder(connection).migration_qs.get(app='migrations', name='0001_initial')
  310. self.assertEqual(
  311. 'migrations\n'
  312. ' [x] 0001_initial (applied at %s)\n'
  313. ' [ ] 0002_second\n' % migration1.applied.strftime('%Y-%m-%d %H:%M:%S'),
  314. out.getvalue().lower()
  315. )
  316. # Cleanup by unmigrating everything
  317. call_command("migrate", "migrations", "zero", verbosity=0)
  318. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
  319. def test_showmigrations_list_squashed(self):
  320. out = io.StringIO()
  321. call_command('showmigrations', format='list', stdout=out, verbosity=2, no_color=True)
  322. self.assertEqual(
  323. 'migrations\n'
  324. ' [ ] 0001_squashed_0002 (2 squashed migrations)\n',
  325. out.getvalue().lower(),
  326. )
  327. out = io.StringIO()
  328. call_command(
  329. 'migrate',
  330. 'migrations',
  331. '0001_squashed_0002',
  332. stdout=out,
  333. verbosity=2,
  334. no_color=True,
  335. )
  336. try:
  337. self.assertIn(
  338. 'operations to perform:\n'
  339. ' target specific migration: 0001_squashed_0002, from migrations\n'
  340. 'running pre-migrate handlers for application migrations\n'
  341. 'running migrations:\n'
  342. ' applying migrations.0001_squashed_0002... ok (',
  343. out.getvalue().lower(),
  344. )
  345. out = io.StringIO()
  346. call_command('showmigrations', format='list', stdout=out, verbosity=2, no_color=True)
  347. self.assertEqual(
  348. 'migrations\n'
  349. ' [x] 0001_squashed_0002 (2 squashed migrations)\n',
  350. out.getvalue().lower(),
  351. )
  352. finally:
  353. # Unmigrate everything.
  354. call_command('migrate', 'migrations', 'zero', verbosity=0)
  355. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"})
  356. def test_showmigrations_plan(self):
  357. """
  358. Tests --plan output of showmigrations command
  359. """
  360. out = io.StringIO()
  361. call_command("showmigrations", format='plan', stdout=out)
  362. self.assertEqual(
  363. "[ ] migrations.0001_initial\n"
  364. "[ ] migrations.0003_third\n"
  365. "[ ] migrations.0002_second\n",
  366. out.getvalue().lower()
  367. )
  368. out = io.StringIO()
  369. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  370. self.assertEqual(
  371. "[ ] migrations.0001_initial\n"
  372. "[ ] migrations.0003_third ... (migrations.0001_initial)\n"
  373. "[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
  374. out.getvalue().lower()
  375. )
  376. call_command("migrate", "migrations", "0003", verbosity=0)
  377. out = io.StringIO()
  378. call_command("showmigrations", format='plan', stdout=out)
  379. self.assertEqual(
  380. "[x] migrations.0001_initial\n"
  381. "[x] migrations.0003_third\n"
  382. "[ ] migrations.0002_second\n",
  383. out.getvalue().lower()
  384. )
  385. out = io.StringIO()
  386. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  387. self.assertEqual(
  388. "[x] migrations.0001_initial\n"
  389. "[x] migrations.0003_third ... (migrations.0001_initial)\n"
  390. "[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
  391. out.getvalue().lower()
  392. )
  393. # Cleanup by unmigrating everything
  394. call_command("migrate", "migrations", "zero", verbosity=0)
  395. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_plan'})
  396. def test_migrate_plan(self):
  397. """Tests migrate --plan output."""
  398. out = io.StringIO()
  399. # Show the plan up to the third migration.
  400. call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
  401. self.assertEqual(
  402. 'Planned operations:\n'
  403. 'migrations.0001_initial\n'
  404. ' Create model Salamander\n'
  405. ' Raw Python operation -> Grow salamander tail.\n'
  406. 'migrations.0002_second\n'
  407. ' Create model Book\n'
  408. " Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
  409. 'migrations.0003_third\n'
  410. ' Create model Author\n'
  411. " Raw SQL operation -> ['SELECT * FROM migrations_author']\n",
  412. out.getvalue()
  413. )
  414. try:
  415. # Migrate to the third migration.
  416. call_command('migrate', 'migrations', '0003', verbosity=0)
  417. out = io.StringIO()
  418. # Show the plan for when there is nothing to apply.
  419. call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
  420. self.assertEqual(
  421. 'Planned operations:\n'
  422. ' No planned migration operations.\n',
  423. out.getvalue()
  424. )
  425. out = io.StringIO()
  426. # Show the plan for reverse migration back to 0001.
  427. call_command('migrate', 'migrations', '0001', plan=True, stdout=out, no_color=True)
  428. self.assertEqual(
  429. 'Planned operations:\n'
  430. 'migrations.0003_third\n'
  431. ' Undo Create model Author\n'
  432. " Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
  433. 'migrations.0002_second\n'
  434. ' Undo Create model Book\n'
  435. " Raw SQL operation -> ['SELECT * FROM migrations_salamand…\n",
  436. out.getvalue()
  437. )
  438. out = io.StringIO()
  439. # Show the migration plan to fourth, with truncated details.
  440. call_command('migrate', 'migrations', '0004', plan=True, stdout=out, no_color=True)
  441. self.assertEqual(
  442. 'Planned operations:\n'
  443. 'migrations.0004_fourth\n'
  444. ' Raw SQL operation -> SELECT * FROM migrations_author WHE…\n',
  445. out.getvalue()
  446. )
  447. # Show the plan when an operation is irreversible.
  448. # Migrate to the fourth migration.
  449. call_command('migrate', 'migrations', '0004', verbosity=0)
  450. out = io.StringIO()
  451. call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
  452. self.assertEqual(
  453. 'Planned operations:\n'
  454. 'migrations.0004_fourth\n'
  455. ' Raw SQL operation -> IRREVERSIBLE\n',
  456. out.getvalue()
  457. )
  458. out = io.StringIO()
  459. call_command('migrate', 'migrations', '0005', plan=True, stdout=out, no_color=True)
  460. # Operation is marked as irreversible only in the revert plan.
  461. self.assertEqual(
  462. 'Planned operations:\n'
  463. 'migrations.0005_fifth\n'
  464. ' Raw Python operation\n'
  465. ' Raw Python operation\n'
  466. ' Raw Python operation -> Feed salamander.\n',
  467. out.getvalue()
  468. )
  469. call_command('migrate', 'migrations', '0005', verbosity=0)
  470. out = io.StringIO()
  471. call_command('migrate', 'migrations', '0004', plan=True, stdout=out, no_color=True)
  472. self.assertEqual(
  473. 'Planned operations:\n'
  474. 'migrations.0005_fifth\n'
  475. ' Raw Python operation -> IRREVERSIBLE\n'
  476. ' Raw Python operation -> IRREVERSIBLE\n'
  477. ' Raw Python operation\n',
  478. out.getvalue()
  479. )
  480. finally:
  481. # Cleanup by unmigrating everything: fake the irreversible, then
  482. # migrate all to zero.
  483. call_command('migrate', 'migrations', '0003', fake=True, verbosity=0)
  484. call_command('migrate', 'migrations', 'zero', verbosity=0)
  485. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_empty'})
  486. def test_showmigrations_no_migrations(self):
  487. out = io.StringIO()
  488. call_command('showmigrations', stdout=out, no_color=True)
  489. self.assertEqual('migrations\n (no migrations)\n', out.getvalue().lower())
  490. @override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
  491. def test_showmigrations_unmigrated_app(self):
  492. out = io.StringIO()
  493. call_command('showmigrations', 'unmigrated_app', stdout=out, no_color=True)
  494. try:
  495. self.assertEqual('unmigrated_app\n (no migrations)\n', out.getvalue().lower())
  496. finally:
  497. # unmigrated_app.SillyModel has a foreign key to
  498. # 'migrations.Tribble', but that model is only defined in a
  499. # migration, so the global app registry never sees it and the
  500. # reference is left dangling. Remove it to avoid problems in
  501. # subsequent tests.
  502. apps._pending_operations.pop(('migrations', 'tribble'), None)
  503. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"})
  504. def test_showmigrations_plan_no_migrations(self):
  505. """
  506. Tests --plan output of showmigrations command without migrations
  507. """
  508. out = io.StringIO()
  509. call_command('showmigrations', format='plan', stdout=out, no_color=True)
  510. self.assertEqual('(no migrations)\n', out.getvalue().lower())
  511. out = io.StringIO()
  512. call_command('showmigrations', format='plan', stdout=out, verbosity=2, no_color=True)
  513. self.assertEqual('(no migrations)\n', out.getvalue().lower())
  514. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"})
  515. def test_showmigrations_plan_squashed(self):
  516. """
  517. Tests --plan output of showmigrations command with squashed migrations.
  518. """
  519. out = io.StringIO()
  520. call_command("showmigrations", format='plan', stdout=out)
  521. self.assertEqual(
  522. "[ ] migrations.1_auto\n"
  523. "[ ] migrations.2_auto\n"
  524. "[ ] migrations.3_squashed_5\n"
  525. "[ ] migrations.6_auto\n"
  526. "[ ] migrations.7_auto\n",
  527. out.getvalue().lower()
  528. )
  529. out = io.StringIO()
  530. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  531. self.assertEqual(
  532. "[ ] migrations.1_auto\n"
  533. "[ ] migrations.2_auto ... (migrations.1_auto)\n"
  534. "[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n"
  535. "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
  536. "[ ] migrations.7_auto ... (migrations.6_auto)\n",
  537. out.getvalue().lower()
  538. )
  539. call_command("migrate", "migrations", "3_squashed_5", verbosity=0)
  540. out = io.StringIO()
  541. call_command("showmigrations", format='plan', stdout=out)
  542. self.assertEqual(
  543. "[x] migrations.1_auto\n"
  544. "[x] migrations.2_auto\n"
  545. "[x] migrations.3_squashed_5\n"
  546. "[ ] migrations.6_auto\n"
  547. "[ ] migrations.7_auto\n",
  548. out.getvalue().lower()
  549. )
  550. out = io.StringIO()
  551. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  552. self.assertEqual(
  553. "[x] migrations.1_auto\n"
  554. "[x] migrations.2_auto ... (migrations.1_auto)\n"
  555. "[x] migrations.3_squashed_5 ... (migrations.2_auto)\n"
  556. "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
  557. "[ ] migrations.7_auto ... (migrations.6_auto)\n",
  558. out.getvalue().lower()
  559. )
  560. @override_settings(INSTALLED_APPS=[
  561. 'migrations.migrations_test_apps.mutate_state_b',
  562. 'migrations.migrations_test_apps.alter_fk.author_app',
  563. 'migrations.migrations_test_apps.alter_fk.book_app',
  564. ])
  565. def test_showmigrations_plan_single_app_label(self):
  566. """
  567. `showmigrations --plan app_label` output with a single app_label.
  568. """
  569. # Single app with no dependencies on other apps.
  570. out = io.StringIO()
  571. call_command('showmigrations', 'mutate_state_b', format='plan', stdout=out)
  572. self.assertEqual(
  573. '[ ] mutate_state_b.0001_initial\n'
  574. '[ ] mutate_state_b.0002_add_field\n',
  575. out.getvalue()
  576. )
  577. # Single app with dependencies.
  578. out = io.StringIO()
  579. call_command('showmigrations', 'author_app', format='plan', stdout=out)
  580. self.assertEqual(
  581. '[ ] author_app.0001_initial\n'
  582. '[ ] book_app.0001_initial\n'
  583. '[ ] author_app.0002_alter_id\n',
  584. out.getvalue()
  585. )
  586. # Some migrations already applied.
  587. call_command('migrate', 'author_app', '0001', verbosity=0)
  588. out = io.StringIO()
  589. call_command('showmigrations', 'author_app', format='plan', stdout=out)
  590. self.assertEqual(
  591. '[X] author_app.0001_initial\n'
  592. '[ ] book_app.0001_initial\n'
  593. '[ ] author_app.0002_alter_id\n',
  594. out.getvalue()
  595. )
  596. # Cleanup by unmigrating author_app.
  597. call_command('migrate', 'author_app', 'zero', verbosity=0)
  598. @override_settings(INSTALLED_APPS=[
  599. 'migrations.migrations_test_apps.mutate_state_b',
  600. 'migrations.migrations_test_apps.alter_fk.author_app',
  601. 'migrations.migrations_test_apps.alter_fk.book_app',
  602. ])
  603. def test_showmigrations_plan_multiple_app_labels(self):
  604. """
  605. `showmigrations --plan app_label` output with multiple app_labels.
  606. """
  607. # Multiple apps: author_app depends on book_app; mutate_state_b doesn't
  608. # depend on other apps.
  609. out = io.StringIO()
  610. call_command('showmigrations', 'mutate_state_b', 'author_app', format='plan', stdout=out)
  611. self.assertEqual(
  612. '[ ] author_app.0001_initial\n'
  613. '[ ] book_app.0001_initial\n'
  614. '[ ] author_app.0002_alter_id\n'
  615. '[ ] mutate_state_b.0001_initial\n'
  616. '[ ] mutate_state_b.0002_add_field\n',
  617. out.getvalue()
  618. )
  619. # Multiple apps: args order shouldn't matter (the same result is
  620. # expected as above).
  621. out = io.StringIO()
  622. call_command('showmigrations', 'author_app', 'mutate_state_b', format='plan', stdout=out)
  623. self.assertEqual(
  624. '[ ] author_app.0001_initial\n'
  625. '[ ] book_app.0001_initial\n'
  626. '[ ] author_app.0002_alter_id\n'
  627. '[ ] mutate_state_b.0001_initial\n'
  628. '[ ] mutate_state_b.0002_add_field\n',
  629. out.getvalue()
  630. )
  631. @override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
  632. def test_showmigrations_plan_app_label_no_migrations(self):
  633. out = io.StringIO()
  634. call_command('showmigrations', 'unmigrated_app', format='plan', stdout=out, no_color=True)
  635. try:
  636. self.assertEqual('(no migrations)\n', out.getvalue())
  637. finally:
  638. # unmigrated_app.SillyModel has a foreign key to
  639. # 'migrations.Tribble', but that model is only defined in a
  640. # migration, so the global app registry never sees it and the
  641. # reference is left dangling. Remove it to avoid problems in
  642. # subsequent tests.
  643. apps._pending_operations.pop(('migrations', 'tribble'), None)
  644. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  645. def test_sqlmigrate_forwards(self):
  646. """
  647. sqlmigrate outputs forward looking SQL.
  648. """
  649. out = io.StringIO()
  650. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  651. output = out.getvalue().lower()
  652. index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
  653. index_op_desc_author = output.find('-- create model author')
  654. index_create_table = output.find('create table')
  655. index_op_desc_tribble = output.find('-- create model tribble')
  656. index_op_desc_unique_together = output.find('-- alter unique_together')
  657. index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
  658. if connection.features.can_rollback_ddl:
  659. self.assertGreater(index_tx_start, -1, "Transaction start not found")
  660. self.assertGreater(
  661. index_tx_end, index_op_desc_unique_together,
  662. "Transaction end not found or found before operation description (unique_together)"
  663. )
  664. self.assertGreater(
  665. index_op_desc_author, index_tx_start,
  666. "Operation description (author) not found or found before transaction start"
  667. )
  668. self.assertGreater(
  669. index_create_table, index_op_desc_author,
  670. "CREATE TABLE not found or found before operation description (author)"
  671. )
  672. self.assertGreater(
  673. index_op_desc_tribble, index_create_table,
  674. "Operation description (tribble) not found or found before CREATE TABLE (author)"
  675. )
  676. self.assertGreater(
  677. index_op_desc_unique_together, index_op_desc_tribble,
  678. "Operation description (unique_together) not found or found before operation description (tribble)"
  679. )
  680. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  681. def test_sqlmigrate_backwards(self):
  682. """
  683. sqlmigrate outputs reverse looking SQL.
  684. """
  685. # Cannot generate the reverse SQL unless we've applied the migration.
  686. call_command("migrate", "migrations", verbosity=0)
  687. out = io.StringIO()
  688. call_command("sqlmigrate", "migrations", "0001", stdout=out, backwards=True)
  689. output = out.getvalue().lower()
  690. index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
  691. index_op_desc_unique_together = output.find('-- alter unique_together')
  692. index_op_desc_tribble = output.find('-- create model tribble')
  693. index_op_desc_author = output.find('-- create model author')
  694. index_drop_table = output.rfind('drop table')
  695. index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
  696. if connection.features.can_rollback_ddl:
  697. self.assertGreater(index_tx_start, -1, "Transaction start not found")
  698. self.assertGreater(
  699. index_tx_end, index_op_desc_unique_together,
  700. "Transaction end not found or found before DROP TABLE"
  701. )
  702. self.assertGreater(
  703. index_op_desc_unique_together, index_tx_start,
  704. "Operation description (unique_together) not found or found before transaction start"
  705. )
  706. self.assertGreater(
  707. index_op_desc_tribble, index_op_desc_unique_together,
  708. "Operation description (tribble) not found or found before operation description (unique_together)"
  709. )
  710. self.assertGreater(
  711. index_op_desc_author, index_op_desc_tribble,
  712. "Operation description (author) not found or found before operation description (tribble)"
  713. )
  714. self.assertGreater(
  715. index_drop_table, index_op_desc_author,
  716. "DROP TABLE not found or found before operation description (author)"
  717. )
  718. # Cleanup by unmigrating everything
  719. call_command("migrate", "migrations", "zero", verbosity=0)
  720. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"})
  721. def test_sqlmigrate_for_non_atomic_migration(self):
  722. """
  723. Transaction wrappers aren't shown for non-atomic migrations.
  724. """
  725. out = io.StringIO()
  726. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  727. output = out.getvalue().lower()
  728. queries = [q.strip() for q in output.splitlines()]
  729. if connection.ops.start_transaction_sql():
  730. self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)
  731. self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
  732. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
  733. def test_sqlmigrate_for_non_transactional_databases(self):
  734. """
  735. Transaction wrappers aren't shown for databases that don't support
  736. transactional DDL.
  737. """
  738. out = io.StringIO()
  739. with mock.patch.object(connection.features, 'can_rollback_ddl', False):
  740. call_command('sqlmigrate', 'migrations', '0001', stdout=out)
  741. output = out.getvalue().lower()
  742. queries = [q.strip() for q in output.splitlines()]
  743. start_transaction_sql = connection.ops.start_transaction_sql()
  744. if start_transaction_sql:
  745. self.assertNotIn(start_transaction_sql.lower(), queries)
  746. self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
  747. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
  748. def test_sqlmigrate_ambiguous_prefix_squashed_migrations(self):
  749. msg = (
  750. "More than one migration matches '0001' in app 'migrations'. "
  751. "Please be more specific."
  752. )
  753. with self.assertRaisesMessage(CommandError, msg):
  754. call_command('sqlmigrate', 'migrations', '0001')
  755. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
  756. def test_sqlmigrate_squashed_migration(self):
  757. out = io.StringIO()
  758. call_command('sqlmigrate', 'migrations', '0001_squashed_0002', stdout=out)
  759. output = out.getvalue().lower()
  760. self.assertIn('-- create model author', output)
  761. self.assertIn('-- create model book', output)
  762. self.assertNotIn('-- create model tribble', output)
  763. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
  764. def test_sqlmigrate_replaced_migration(self):
  765. out = io.StringIO()
  766. call_command('sqlmigrate', 'migrations', '0001_initial', stdout=out)
  767. output = out.getvalue().lower()
  768. self.assertIn('-- create model author', output)
  769. self.assertIn('-- create model tribble', output)
  770. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_no_operations'})
  771. def test_migrations_no_operations(self):
  772. err = io.StringIO()
  773. call_command('sqlmigrate', 'migrations', '0001_initial', stderr=err)
  774. self.assertEqual(err.getvalue(), 'No operations found.\n')
  775. @override_settings(
  776. INSTALLED_APPS=[
  777. "migrations.migrations_test_apps.migrated_app",
  778. "migrations.migrations_test_apps.migrated_unapplied_app",
  779. "migrations.migrations_test_apps.unmigrated_app",
  780. ],
  781. )
  782. def test_regression_22823_unmigrated_fk_to_migrated_model(self):
  783. """
  784. Assuming you have 3 apps, `A`, `B`, and `C`, such that:
  785. * `A` has migrations
  786. * `B` has a migration we want to apply
  787. * `C` has no migrations, but has an FK to `A`
  788. When we try to migrate "B", an exception occurs because the
  789. "B" was not included in the ProjectState that is used to detect
  790. soft-applied migrations (#22823).
  791. """
  792. call_command('migrate', 'migrated_unapplied_app', verbosity=0)
  793. # unmigrated_app.SillyModel has a foreign key to 'migrations.Tribble',
  794. # but that model is only defined in a migration, so the global app
  795. # registry never sees it and the reference is left dangling. Remove it
  796. # to avoid problems in subsequent tests.
  797. apps._pending_operations.pop(('migrations', 'tribble'), None)
  798. @override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app_syncdb'])
  799. def test_migrate_syncdb_deferred_sql_executed_with_schemaeditor(self):
  800. """
  801. For an app without migrations, editor.execute() is used for executing
  802. the syncdb deferred SQL.
  803. """
  804. stdout = io.StringIO()
  805. with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
  806. call_command('migrate', run_syncdb=True, verbosity=1, stdout=stdout, no_color=True)
  807. create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
  808. self.assertEqual(create_table_count, 2)
  809. # There's at least one deferred SQL for creating the foreign key
  810. # index.
  811. self.assertGreater(len(execute.mock_calls), 2)
  812. stdout = stdout.getvalue()
  813. self.assertIn('Synchronize unmigrated apps: unmigrated_app_syncdb', stdout)
  814. self.assertIn('Creating tables...', stdout)
  815. table_name = truncate_name('unmigrated_app_syncdb_classroom', connection.ops.max_name_length())
  816. self.assertIn('Creating table %s' % table_name, stdout)
  817. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
  818. def test_migrate_syncdb_app_with_migrations(self):
  819. msg = "Can't use run_syncdb with app 'migrations' as it has migrations."
  820. with self.assertRaisesMessage(CommandError, msg):
  821. call_command('migrate', 'migrations', run_syncdb=True, verbosity=0)
  822. @override_settings(INSTALLED_APPS=[
  823. 'migrations.migrations_test_apps.unmigrated_app_syncdb',
  824. 'migrations.migrations_test_apps.unmigrated_app_simple',
  825. ])
  826. def test_migrate_syncdb_app_label(self):
  827. """
  828. Running migrate --run-syncdb with an app_label only creates tables for
  829. the specified app.
  830. """
  831. stdout = io.StringIO()
  832. with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
  833. call_command('migrate', 'unmigrated_app_syncdb', run_syncdb=True, stdout=stdout)
  834. create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
  835. self.assertEqual(create_table_count, 2)
  836. self.assertGreater(len(execute.mock_calls), 2)
  837. self.assertIn('Synchronize unmigrated app: unmigrated_app_syncdb', stdout.getvalue())
  838. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
  839. def test_migrate_record_replaced(self):
  840. """
  841. Running a single squashed migration should record all of the original
  842. replaced migrations as run.
  843. """
  844. recorder = MigrationRecorder(connection)
  845. out = io.StringIO()
  846. call_command("migrate", "migrations", verbosity=0)
  847. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  848. self.assertEqual(
  849. 'migrations\n'
  850. ' [x] 0001_squashed_0002 (2 squashed migrations)\n',
  851. out.getvalue().lower()
  852. )
  853. applied_migrations = recorder.applied_migrations()
  854. self.assertIn(("migrations", "0001_initial"), applied_migrations)
  855. self.assertIn(("migrations", "0002_second"), applied_migrations)
  856. self.assertIn(("migrations", "0001_squashed_0002"), applied_migrations)
  857. # Rollback changes
  858. call_command("migrate", "migrations", "zero", verbosity=0)
  859. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
  860. def test_migrate_record_squashed(self):
  861. """
  862. Running migrate for a squashed migration should record as run
  863. if all of the replaced migrations have been run (#25231).
  864. """
  865. recorder = MigrationRecorder(connection)
  866. recorder.record_applied("migrations", "0001_initial")
  867. recorder.record_applied("migrations", "0002_second")
  868. out = io.StringIO()
  869. call_command('showmigrations', 'migrations', stdout=out, no_color=True)
  870. self.assertEqual(
  871. "migrations\n"
  872. " [-] 0001_squashed_0002 (2 squashed migrations) "
  873. "run 'manage.py migrate' to finish recording.\n",
  874. out.getvalue().lower(),
  875. )
  876. out = io.StringIO()
  877. call_command("migrate", "migrations", verbosity=0)
  878. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  879. self.assertEqual(
  880. 'migrations\n'
  881. ' [x] 0001_squashed_0002 (2 squashed migrations)\n',
  882. out.getvalue().lower()
  883. )
  884. self.assertIn(
  885. ("migrations", "0001_squashed_0002"),
  886. recorder.applied_migrations()
  887. )
  888. # No changes were actually applied so there is nothing to rollback
  889. def test_migrate_partially_applied_squashed_migration(self):
  890. """
  891. Migrating to a squashed migration specified by name should succeed
  892. even if it is partially applied.
  893. """
  894. with self.temporary_migration_module(module='migrations.test_migrations'):
  895. recorder = MigrationRecorder(connection)
  896. try:
  897. call_command('migrate', 'migrations', '0001_initial', verbosity=0)
  898. call_command(
  899. 'squashmigrations',
  900. 'migrations',
  901. '0002',
  902. interactive=False,
  903. verbosity=0,
  904. )
  905. call_command(
  906. 'migrate',
  907. 'migrations',
  908. '0001_squashed_0002_second',
  909. verbosity=0,
  910. )
  911. applied_migrations = recorder.applied_migrations()
  912. self.assertIn(('migrations', '0002_second'), applied_migrations)
  913. finally:
  914. # Unmigrate everything.
  915. call_command('migrate', 'migrations', 'zero', verbosity=0)
  916. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
  917. def test_migrate_backward_to_squashed_migration(self):
  918. try:
  919. call_command('migrate', 'migrations', '0001_squashed_0002', verbosity=0)
  920. self.assertTableExists('migrations_author')
  921. self.assertTableExists('migrations_book')
  922. call_command('migrate', 'migrations', '0001_initial', verbosity=0)
  923. self.assertTableExists('migrations_author')
  924. self.assertTableNotExists('migrations_book')
  925. finally:
  926. # Unmigrate everything.
  927. call_command('migrate', 'migrations', 'zero', verbosity=0)
  928. @override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
  929. def test_migrate_inconsistent_history(self):
  930. """
  931. Running migrate with some migrations applied before their dependencies
  932. should not be allowed.
  933. """
  934. recorder = MigrationRecorder(connection)
  935. recorder.record_applied("migrations", "0002_second")
  936. msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
  937. with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
  938. call_command("migrate")
  939. applied_migrations = recorder.applied_migrations()
  940. self.assertNotIn(("migrations", "0001_initial"), applied_migrations)
  941. @override_settings(INSTALLED_APPS=[
  942. 'migrations.migrations_test_apps.migrated_unapplied_app',
  943. 'migrations.migrations_test_apps.migrated_app',
  944. ])
  945. def test_migrate_not_reflected_changes(self):
  946. class NewModel1(models.Model):
  947. class Meta():
  948. app_label = 'migrated_app'
  949. class NewModel2(models.Model):
  950. class Meta():
  951. app_label = 'migrated_unapplied_app'
  952. out = io.StringIO()
  953. try:
  954. call_command('migrate', verbosity=0)
  955. call_command('migrate', stdout=out, no_color=True)
  956. self.assertEqual(
  957. "operations to perform:\n"
  958. " apply all migrations: migrated_app, migrated_unapplied_app\n"
  959. "running migrations:\n"
  960. " no migrations to apply.\n"
  961. " your models in app(s): 'migrated_app', "
  962. "'migrated_unapplied_app' have changes that are not yet "
  963. "reflected in a migration, and so won't be applied.\n"
  964. " run 'manage.py makemigrations' to make new migrations, and "
  965. "then re-run 'manage.py migrate' to apply them.\n",
  966. out.getvalue().lower(),
  967. )
  968. finally:
  969. # Unmigrate everything.
  970. call_command('migrate', 'migrated_app', 'zero', verbosity=0)
  971. call_command('migrate', 'migrated_unapplied_app', 'zero', verbosity=0)
  972. class MakeMigrationsTests(MigrationTestBase):
  973. """
  974. Tests running the makemigrations command.
  975. """
  976. def setUp(self):
  977. super().setUp()
  978. self._old_models = apps.app_configs['migrations'].models.copy()
  979. def tearDown(self):
  980. apps.app_configs['migrations'].models = self._old_models
  981. apps.all_models['migrations'] = self._old_models
  982. apps.clear_cache()
  983. super().tearDown()
  984. def test_files_content(self):
  985. self.assertTableNotExists("migrations_unicodemodel")
  986. apps.register_model('migrations', UnicodeModel)
  987. with self.temporary_migration_module() as migration_dir:
  988. call_command("makemigrations", "migrations", verbosity=0)
  989. # Check for empty __init__.py file in migrations folder
  990. init_file = os.path.join(migration_dir, "__init__.py")
  991. self.assertTrue(os.path.exists(init_file))
  992. with open(init_file) as fp:
  993. content = fp.read()
  994. self.assertEqual(content, '')
  995. # Check for existing 0001_initial.py file in migration folder
  996. initial_file = os.path.join(migration_dir, "0001_initial.py")
  997. self.assertTrue(os.path.exists(initial_file))
  998. with open(initial_file, encoding='utf-8') as fp:
  999. content = fp.read()
  1000. self.assertIn('migrations.CreateModel', content)
  1001. self.assertIn('initial = True', content)
  1002. self.assertIn('úñí©óðé µóðéø', content) # Meta.verbose_name
  1003. self.assertIn('úñí©óðé µóðéøß', content) # Meta.verbose_name_plural
  1004. self.assertIn('ÚÑÍ¢ÓÐÉ', content) # title.verbose_name
  1005. self.assertIn('“Ðjáñgó”', content) # title.default
  1006. def test_makemigrations_order(self):
  1007. """
  1008. makemigrations should recognize number-only migrations (0001.py).
  1009. """
  1010. module = 'migrations.test_migrations_order'
  1011. with self.temporary_migration_module(module=module) as migration_dir:
  1012. if hasattr(importlib, 'invalidate_caches'):
  1013. # importlib caches os.listdir() on some platforms like macOS
  1014. # (#23850).
  1015. importlib.invalidate_caches()
  1016. call_command('makemigrations', 'migrations', '--empty', '-n', 'a', '-v', '0')
  1017. self.assertTrue(os.path.exists(os.path.join(migration_dir, '0002_a.py')))
  1018. def test_makemigrations_empty_connections(self):
  1019. empty_connections = ConnectionHandler({'default': {}})
  1020. with mock.patch('django.core.management.commands.makemigrations.connections', new=empty_connections):
  1021. # with no apps
  1022. out = io.StringIO()
  1023. call_command('makemigrations', stdout=out)
  1024. self.assertIn('No changes detected', out.getvalue())
  1025. # with an app
  1026. with self.temporary_migration_module() as migration_dir:
  1027. call_command('makemigrations', 'migrations', verbosity=0)
  1028. init_file = os.path.join(migration_dir, '__init__.py')
  1029. self.assertTrue(os.path.exists(init_file))
  1030. @override_settings(INSTALLED_APPS=['migrations', 'migrations2'])
  1031. def test_makemigrations_consistency_checks_respect_routers(self):
  1032. """
  1033. The history consistency checks in makemigrations respect
  1034. settings.DATABASE_ROUTERS.
  1035. """
  1036. def patched_has_table(migration_recorder):
  1037. if migration_recorder.connection is connections['other']:
  1038. raise Exception('Other connection')
  1039. else:
  1040. return mock.DEFAULT
  1041. self.assertTableNotExists('migrations_unicodemodel')
  1042. apps.register_model('migrations', UnicodeModel)
  1043. with mock.patch.object(
  1044. MigrationRecorder, 'has_table',
  1045. autospec=True, side_effect=patched_has_table) as has_table:
  1046. with self.temporary_migration_module() as migration_dir:
  1047. call_command("makemigrations", "migrations", verbosity=0)
  1048. initial_file = os.path.join(migration_dir, "0001_initial.py")
  1049. self.assertTrue(os.path.exists(initial_file))
  1050. self.assertEqual(has_table.call_count, 1) # 'default' is checked
  1051. # Router says not to migrate 'other' so consistency shouldn't
  1052. # be checked.
  1053. with self.settings(DATABASE_ROUTERS=['migrations.routers.TestRouter']):
  1054. call_command('makemigrations', 'migrations', verbosity=0)
  1055. self.assertEqual(has_table.call_count, 2) # 'default' again
  1056. # With a router that doesn't prohibit migrating 'other',
  1057. # consistency is checked.
  1058. with self.settings(DATABASE_ROUTERS=['migrations.routers.DefaultOtherRouter']):
  1059. with self.assertRaisesMessage(Exception, 'Other connection'):
  1060. call_command('makemigrations', 'migrations', verbosity=0)
  1061. self.assertEqual(has_table.call_count, 4) # 'default' and 'other'
  1062. # With a router that doesn't allow migrating on any database,
  1063. # no consistency checks are made.
  1064. with self.settings(DATABASE_ROUTERS=['migrations.routers.TestRouter']):
  1065. with mock.patch.object(TestRouter, 'allow_migrate', return_value=False) as allow_migrate:
  1066. call_command('makemigrations', 'migrations', verbosity=0)
  1067. allow_migrate.assert_any_call('other', 'migrations', model_name='UnicodeModel')
  1068. # allow_migrate() is called with the correct arguments.
  1069. self.assertGreater(len(allow_migrate.mock_calls), 0)
  1070. called_aliases = set()
  1071. for mock_call in allow_migrate.mock_calls:
  1072. _, call_args, call_kwargs = mock_call
  1073. connection_alias, app_name = call_args
  1074. called_aliases.add(connection_alias)
  1075. # Raises an error if invalid app_name/model_name occurs.
  1076. apps.get_app_config(app_name).get_model(call_kwargs['model_name'])
  1077. self.assertEqual(called_aliases, set(connections))
  1078. self.assertEqual(has_table.call_count, 4)
  1079. def test_failing_migration(self):
  1080. # If a migration fails to serialize, it shouldn't generate an empty file. #21280
  1081. apps.register_model('migrations', UnserializableModel)
  1082. with self.temporary_migration_module() as migration_dir:
  1083. with self.assertRaisesMessage(ValueError, 'Cannot serialize'):
  1084. call_command("makemigrations", "migrations", verbosity=0)
  1085. initial_file = os.path.join(migration_dir, "0001_initial.py")
  1086. self.assertFalse(os.path.exists(initial_file))
  1087. def test_makemigrations_conflict_exit(self):
  1088. """
  1089. makemigrations exits if it detects a conflict.
  1090. """
  1091. with self.temporary_migration_module(module="migrations.test_migrations_conflict"):
  1092. with self.assertRaises(CommandError) as context:
  1093. call_command("makemigrations")
  1094. self.assertEqual(
  1095. str(context.exception),
  1096. "Conflicting migrations detected; multiple leaf nodes in the "
  1097. "migration graph: (0002_conflicting_second, 0002_second in "
  1098. "migrations).\n"
  1099. "To fix them run 'python manage.py makemigrations --merge'"
  1100. )
  1101. def test_makemigrations_merge_no_conflict(self):
  1102. """
  1103. makemigrations exits if in merge mode with no conflicts.
  1104. """
  1105. out = io.StringIO()
  1106. with self.temporary_migration_module(module="migrations.test_migrations"):
  1107. call_command("makemigrations", merge=True, stdout=out)
  1108. self.assertIn("No conflicts detected to merge.", out.getvalue())
  1109. def test_makemigrations_empty_no_app_specified(self):
  1110. """
  1111. makemigrations exits if no app is specified with 'empty' mode.
  1112. """
  1113. msg = 'You must supply at least one app label when using --empty.'
  1114. with self.assertRaisesMessage(CommandError, msg):
  1115. call_command("makemigrations", empty=True)
  1116. def test_makemigrations_empty_migration(self):
  1117. """
  1118. makemigrations properly constructs an empty migration.
  1119. """
  1120. with self.temporary_migration_module() as migration_dir:
  1121. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  1122. # Check for existing 0001_initial.py file in migration folder
  1123. initial_file = os.path.join(migration_dir, "0001_initial.py")
  1124. self.assertTrue(os.path.exists(initial_file))
  1125. with open(initial_file, encoding='utf-8') as fp:
  1126. content = fp.read()
  1127. # Remove all whitespace to check for empty dependencies and operations
  1128. content = content.replace(' ', '')
  1129. self.assertIn('dependencies=[\n]', content)
  1130. self.assertIn('operations=[\n]', content)
  1131. @override_settings(MIGRATION_MODULES={"migrations": None})
  1132. def test_makemigrations_disabled_migrations_for_app(self):
  1133. """
  1134. makemigrations raises a nice error when migrations are disabled for an
  1135. app.
  1136. """
  1137. msg = (
  1138. "Django can't create migrations for app 'migrations' because migrations "
  1139. "have been disabled via the MIGRATION_MODULES setting."
  1140. )
  1141. with self.assertRaisesMessage(ValueError, msg):
  1142. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  1143. def test_makemigrations_no_changes_no_apps(self):
  1144. """
  1145. makemigrations exits when there are no changes and no apps are specified.
  1146. """
  1147. out = io.StringIO()
  1148. call_command("makemigrations", stdout=out)
  1149. self.assertIn("No changes detected", out.getvalue())
  1150. def test_makemigrations_no_changes(self):
  1151. """
  1152. makemigrations exits when there are no changes to an app.
  1153. """
  1154. out = io.StringIO()
  1155. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  1156. call_command("makemigrations", "migrations", stdout=out)
  1157. self.assertIn("No changes detected in app 'migrations'", out.getvalue())
  1158. def test_makemigrations_no_apps_initial(self):
  1159. """
  1160. makemigrations should detect initial is needed on empty migration
  1161. modules if no app provided.
  1162. """
  1163. out = io.StringIO()
  1164. with self.temporary_migration_module(module="migrations.test_migrations_empty"):
  1165. call_command("makemigrations", stdout=out)
  1166. self.assertIn("0001_initial.py", out.getvalue())
  1167. def test_makemigrations_no_init(self):
  1168. """Migration directories without an __init__.py file are allowed."""
  1169. out = io.StringIO()
  1170. with self.temporary_migration_module(module='migrations.test_migrations_no_init'):
  1171. call_command('makemigrations', stdout=out)
  1172. self.assertIn('0001_initial.py', out.getvalue())
  1173. def test_makemigrations_migrations_announce(self):
  1174. """
  1175. makemigrations announces the migration at the default verbosity level.
  1176. """
  1177. out = io.StringIO()
  1178. with self.temporary_migration_module():
  1179. call_command("makemigrations", "migrations", stdout=out)
  1180. self.assertIn("Migrations for 'migrations'", out.getvalue())
  1181. def test_makemigrations_no_common_ancestor(self):
  1182. """
  1183. makemigrations fails to merge migrations with no common ancestor.
  1184. """
  1185. with self.assertRaises(ValueError) as context:
  1186. with self.temporary_migration_module(module="migrations.test_migrations_no_ancestor"):
  1187. call_command("makemigrations", "migrations", merge=True)
  1188. exception_message = str(context.exception)
  1189. self.assertIn("Could not find common ancestor of", exception_message)
  1190. self.assertIn("0002_second", exception_message)
  1191. self.assertIn("0002_conflicting_second", exception_message)
  1192. def test_makemigrations_interactive_reject(self):
  1193. """
  1194. makemigrations enters and exits interactive mode properly.
  1195. """
  1196. # Monkeypatch interactive questioner to auto reject
  1197. with mock.patch('builtins.input', mock.Mock(return_value='N')):
  1198. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  1199. call_command("makemigrations", "migrations", name="merge", merge=True, interactive=True, verbosity=0)
  1200. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1201. self.assertFalse(os.path.exists(merge_file))
  1202. def test_makemigrations_interactive_accept(self):
  1203. """
  1204. makemigrations enters interactive mode and merges properly.
  1205. """
  1206. # Monkeypatch interactive questioner to auto accept
  1207. with mock.patch('builtins.input', mock.Mock(return_value='y')):
  1208. out = io.StringIO()
  1209. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  1210. call_command("makemigrations", "migrations", name="merge", merge=True, interactive=True, stdout=out)
  1211. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1212. self.assertTrue(os.path.exists(merge_file))
  1213. self.assertIn("Created new merge migration", out.getvalue())
  1214. def test_makemigrations_default_merge_name(self):
  1215. out = io.StringIO()
  1216. with self.temporary_migration_module(
  1217. module='migrations.test_migrations_conflict'
  1218. ) as migration_dir:
  1219. call_command('makemigrations', 'migrations', merge=True, interactive=False, stdout=out)
  1220. merge_file = os.path.join(
  1221. migration_dir,
  1222. '0003_merge_0002_conflicting_second_0002_second.py',
  1223. )
  1224. self.assertIs(os.path.exists(merge_file), True)
  1225. self.assertIn('Created new merge migration %s' % merge_file, out.getvalue())
  1226. @mock.patch('django.db.migrations.utils.datetime')
  1227. def test_makemigrations_auto_merge_name(self, mock_datetime):
  1228. mock_datetime.datetime.now.return_value = datetime.datetime(2016, 1, 2, 3, 4)
  1229. with mock.patch('builtins.input', mock.Mock(return_value='y')):
  1230. out = io.StringIO()
  1231. with self.temporary_migration_module(
  1232. module='migrations.test_migrations_conflict_long_name'
  1233. ) as migration_dir:
  1234. call_command("makemigrations", "migrations", merge=True, interactive=True, stdout=out)
  1235. merge_file = os.path.join(migration_dir, '0003_merge_20160102_0304.py')
  1236. self.assertTrue(os.path.exists(merge_file))
  1237. self.assertIn("Created new merge migration", out.getvalue())
  1238. def test_makemigrations_non_interactive_not_null_addition(self):
  1239. """
  1240. Non-interactive makemigrations fails when a default is missing on a
  1241. new not-null field.
  1242. """
  1243. class SillyModel(models.Model):
  1244. silly_field = models.BooleanField(default=False)
  1245. silly_int = models.IntegerField()
  1246. class Meta:
  1247. app_label = "migrations"
  1248. with self.assertRaises(SystemExit):
  1249. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  1250. with captured_stdout() as out:
  1251. call_command('makemigrations', 'migrations', interactive=False)
  1252. self.assertIn(
  1253. "Field 'silly_int' on model 'sillymodel' not migrated: it is "
  1254. "impossible to add a non-nullable field without specifying a "
  1255. "default.",
  1256. out.getvalue(),
  1257. )
  1258. def test_makemigrations_interactive_not_null_addition(self):
  1259. """
  1260. makemigrations messages when adding a NOT NULL field in interactive
  1261. mode.
  1262. """
  1263. class Author(models.Model):
  1264. silly_field = models.BooleanField(null=False)
  1265. class Meta:
  1266. app_label = 'migrations'
  1267. input_msg = (
  1268. "It is impossible to add a non-nullable field 'silly_field' to "
  1269. "author without specifying a default. This is because the "
  1270. "database needs something to populate existing rows.\n"
  1271. "Please select a fix:\n"
  1272. " 1) Provide a one-off default now (will be set on all existing "
  1273. "rows with a null value for this column)\n"
  1274. " 2) Quit and manually define a default value in models.py."
  1275. )
  1276. with self.temporary_migration_module(module='migrations.test_migrations'):
  1277. # 2 - quit.
  1278. with mock.patch('builtins.input', return_value='2'):
  1279. with captured_stdout() as out, self.assertRaises(SystemExit):
  1280. call_command('makemigrations', 'migrations', interactive=True)
  1281. self.assertIn(input_msg, out.getvalue())
  1282. # 1 - provide a default.
  1283. with mock.patch('builtins.input', return_value='1'):
  1284. with captured_stdout() as out:
  1285. call_command('makemigrations', 'migrations', interactive=True)
  1286. output = out.getvalue()
  1287. self.assertIn(input_msg, output)
  1288. self.assertIn('Please enter the default value as valid Python.', output)
  1289. self.assertIn(
  1290. 'The datetime and django.utils.timezone modules are '
  1291. 'available, so it is possible to provide e.g. timezone.now as '
  1292. 'a value',
  1293. output,
  1294. )
  1295. self.assertIn("Type 'exit' to exit this prompt", output)
  1296. def test_makemigrations_non_interactive_not_null_alteration(self):
  1297. """
  1298. Non-interactive makemigrations fails when a default is missing on a
  1299. field changed to not-null.
  1300. """
  1301. class Author(models.Model):
  1302. name = models.CharField(max_length=255)
  1303. slug = models.SlugField()
  1304. age = models.IntegerField(default=0)
  1305. class Meta:
  1306. app_label = "migrations"
  1307. with self.temporary_migration_module(module="migrations.test_migrations"):
  1308. with captured_stdout() as out:
  1309. call_command('makemigrations', 'migrations', interactive=False)
  1310. self.assertIn("Alter field slug on author", out.getvalue())
  1311. self.assertIn(
  1312. "Field 'slug' on model 'author' given a default of NOT PROVIDED "
  1313. "and must be corrected.",
  1314. out.getvalue(),
  1315. )
  1316. def test_makemigrations_interactive_not_null_alteration(self):
  1317. """
  1318. makemigrations messages when changing a NULL field to NOT NULL in
  1319. interactive mode.
  1320. """
  1321. class Author(models.Model):
  1322. slug = models.SlugField(null=False)
  1323. class Meta:
  1324. app_label = 'migrations'
  1325. input_msg = (
  1326. "It is impossible to change a nullable field 'slug' on author to "
  1327. "non-nullable without providing a default. This is because the "
  1328. "database needs something to populate existing rows.\n"
  1329. "Please select a fix:\n"
  1330. " 1) Provide a one-off default now (will be set on all existing "
  1331. "rows with a null value for this column)\n"
  1332. " 2) Ignore for now. Existing rows that contain NULL values will "
  1333. "have to be handled manually, for example with a RunPython or "
  1334. "RunSQL operation.\n"
  1335. " 3) Quit and manually define a default value in models.py."
  1336. )
  1337. with self.temporary_migration_module(module='migrations.test_migrations'):
  1338. # 3 - quit.
  1339. with mock.patch('builtins.input', return_value='3'):
  1340. with captured_stdout() as out, self.assertRaises(SystemExit):
  1341. call_command('makemigrations', 'migrations', interactive=True)
  1342. self.assertIn(input_msg, out.getvalue())
  1343. # 1 - provide a default.
  1344. with mock.patch('builtins.input', return_value='1'):
  1345. with captured_stdout() as out:
  1346. call_command('makemigrations', 'migrations', interactive=True)
  1347. output = out.getvalue()
  1348. self.assertIn(input_msg, output)
  1349. self.assertIn('Please enter the default value as valid Python.', output)
  1350. self.assertIn(
  1351. 'The datetime and django.utils.timezone modules are '
  1352. 'available, so it is possible to provide e.g. timezone.now as '
  1353. 'a value',
  1354. output,
  1355. )
  1356. self.assertIn("Type 'exit' to exit this prompt", output)
  1357. def test_makemigrations_non_interactive_no_model_rename(self):
  1358. """
  1359. makemigrations adds and removes a possible model rename in
  1360. non-interactive mode.
  1361. """
  1362. class RenamedModel(models.Model):
  1363. silly_field = models.BooleanField(default=False)
  1364. class Meta:
  1365. app_label = "migrations"
  1366. out = io.StringIO()
  1367. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  1368. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  1369. self.assertIn("Delete model SillyModel", out.getvalue())
  1370. self.assertIn("Create model RenamedModel", out.getvalue())
  1371. def test_makemigrations_non_interactive_no_field_rename(self):
  1372. """
  1373. makemigrations adds and removes a possible field rename in
  1374. non-interactive mode.
  1375. """
  1376. class SillyModel(models.Model):
  1377. silly_rename = models.BooleanField(default=False)
  1378. class Meta:
  1379. app_label = "migrations"
  1380. out = io.StringIO()
  1381. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  1382. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  1383. self.assertIn("Remove field silly_field from sillymodel", out.getvalue())
  1384. self.assertIn("Add field silly_rename to sillymodel", out.getvalue())
  1385. def test_makemigrations_handle_merge(self):
  1386. """
  1387. makemigrations properly merges the conflicting migrations with --noinput.
  1388. """
  1389. out = io.StringIO()
  1390. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  1391. call_command("makemigrations", "migrations", name="merge", merge=True, interactive=False, stdout=out)
  1392. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1393. self.assertTrue(os.path.exists(merge_file))
  1394. output = out.getvalue()
  1395. self.assertIn("Merging migrations", output)
  1396. self.assertIn("Branch 0002_second", output)
  1397. self.assertIn("Branch 0002_conflicting_second", output)
  1398. self.assertIn("Created new merge migration", output)
  1399. def test_makemigration_merge_dry_run(self):
  1400. """
  1401. makemigrations respects --dry-run option when fixing migration
  1402. conflicts (#24427).
  1403. """
  1404. out = io.StringIO()
  1405. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  1406. call_command(
  1407. "makemigrations", "migrations", name="merge", dry_run=True,
  1408. merge=True, interactive=False, stdout=out,
  1409. )
  1410. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1411. self.assertFalse(os.path.exists(merge_file))
  1412. output = out.getvalue()
  1413. self.assertIn("Merging migrations", output)
  1414. self.assertIn("Branch 0002_second", output)
  1415. self.assertIn("Branch 0002_conflicting_second", output)
  1416. self.assertNotIn("Created new merge migration", output)
  1417. def test_makemigration_merge_dry_run_verbosity_3(self):
  1418. """
  1419. `makemigrations --merge --dry-run` writes the merge migration file to
  1420. stdout with `verbosity == 3` (#24427).
  1421. """
  1422. out = io.StringIO()
  1423. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  1424. call_command(
  1425. "makemigrations", "migrations", name="merge", dry_run=True,
  1426. merge=True, interactive=False, stdout=out, verbosity=3,
  1427. )
  1428. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1429. self.assertFalse(os.path.exists(merge_file))
  1430. output = out.getvalue()
  1431. self.assertIn("Merging migrations", output)
  1432. self.assertIn("Branch 0002_second", output)
  1433. self.assertIn("Branch 0002_conflicting_second", output)
  1434. self.assertNotIn("Created new merge migration", output)
  1435. # Additional output caused by verbosity 3
  1436. # The complete merge migration file that would be written
  1437. self.assertIn("class Migration(migrations.Migration):", output)
  1438. self.assertIn("dependencies = [", output)
  1439. self.assertIn("('migrations', '0002_second')", output)
  1440. self.assertIn("('migrations', '0002_conflicting_second')", output)
  1441. self.assertIn("operations = [", output)
  1442. self.assertIn("]", output)
  1443. def test_makemigrations_dry_run(self):
  1444. """
  1445. `makemigrations --dry-run` should not ask for defaults.
  1446. """
  1447. class SillyModel(models.Model):
  1448. silly_field = models.BooleanField(default=False)
  1449. silly_date = models.DateField() # Added field without a default
  1450. class Meta:
  1451. app_label = "migrations"
  1452. out = io.StringIO()
  1453. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  1454. call_command("makemigrations", "migrations", dry_run=True, stdout=out)
  1455. # Output the expected changes directly, without asking for defaults
  1456. self.assertIn("Add field silly_date to sillymodel", out.getvalue())
  1457. def test_makemigrations_dry_run_verbosity_3(self):
  1458. """
  1459. Allow `makemigrations --dry-run` to output the migrations file to
  1460. stdout (with verbosity == 3).
  1461. """
  1462. class SillyModel(models.Model):
  1463. silly_field = models.BooleanField(default=False)
  1464. silly_char = models.CharField(default="")
  1465. class Meta:
  1466. app_label = "migrations"
  1467. out = io.StringIO()
  1468. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  1469. call_command("makemigrations", "migrations", dry_run=True, stdout=out, verbosity=3)
  1470. # Normal --dry-run output
  1471. self.assertIn("- Add field silly_char to sillymodel", out.getvalue())
  1472. # Additional output caused by verbosity 3
  1473. # The complete migrations file that would be written
  1474. self.assertIn("class Migration(migrations.Migration):", out.getvalue())
  1475. self.assertIn("dependencies = [", out.getvalue())
  1476. self.assertIn("('migrations', '0001_initial'),", out.getvalue())
  1477. self.assertIn("migrations.AddField(", out.getvalue())
  1478. self.assertIn("model_name='sillymodel',", out.getvalue())
  1479. self.assertIn("name='silly_char',", out.getvalue())
  1480. def test_makemigrations_migrations_modules_path_not_exist(self):
  1481. """
  1482. makemigrations creates migrations when specifying a custom location
  1483. for migration files using MIGRATION_MODULES if the custom path
  1484. doesn't already exist.
  1485. """
  1486. class SillyModel(models.Model):
  1487. silly_field = models.BooleanField(default=False)
  1488. class Meta:
  1489. app_label = "migrations"
  1490. out = io.StringIO()
  1491. migration_module = "migrations.test_migrations_path_doesnt_exist.foo.bar"
  1492. with self.temporary_migration_module(module=migration_module) as migration_dir:
  1493. call_command("makemigrations", "migrations", stdout=out)
  1494. # Migrations file is actually created in the expected path.
  1495. initial_file = os.path.join(migration_dir, "0001_initial.py")
  1496. self.assertTrue(os.path.exists(initial_file))
  1497. # Command output indicates the migration is created.
  1498. self.assertIn(" - Create model SillyModel", out.getvalue())
  1499. @override_settings(MIGRATION_MODULES={'migrations': 'some.nonexistent.path'})
  1500. def test_makemigrations_migrations_modules_nonexistent_toplevel_package(self):
  1501. msg = (
  1502. 'Could not locate an appropriate location to create migrations '
  1503. 'package some.nonexistent.path. Make sure the toplevel package '
  1504. 'exists and can be imported.'
  1505. )
  1506. with self.assertRaisesMessage(ValueError, msg):
  1507. call_command('makemigrations', 'migrations', empty=True, verbosity=0)
  1508. def test_makemigrations_interactive_by_default(self):
  1509. """
  1510. The user is prompted to merge by default if there are conflicts and
  1511. merge is True. Answer negative to differentiate it from behavior when
  1512. --noinput is specified.
  1513. """
  1514. # Monkeypatch interactive questioner to auto reject
  1515. out = io.StringIO()
  1516. with mock.patch('builtins.input', mock.Mock(return_value='N')):
  1517. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  1518. call_command("makemigrations", "migrations", name="merge", merge=True, stdout=out)
  1519. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1520. # This will fail if interactive is False by default
  1521. self.assertFalse(os.path.exists(merge_file))
  1522. self.assertNotIn("Created new merge migration", out.getvalue())
  1523. @override_settings(
  1524. INSTALLED_APPS=[
  1525. "migrations",
  1526. "migrations.migrations_test_apps.unspecified_app_with_conflict"])
  1527. def test_makemigrations_unspecified_app_with_conflict_no_merge(self):
  1528. """
  1529. makemigrations does not raise a CommandError when an unspecified app
  1530. has conflicting migrations.
  1531. """
  1532. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  1533. call_command("makemigrations", "migrations", merge=False, verbosity=0)
  1534. @override_settings(
  1535. INSTALLED_APPS=[
  1536. "migrations.migrations_test_apps.migrated_app",
  1537. "migrations.migrations_test_apps.unspecified_app_with_conflict"])
  1538. def test_makemigrations_unspecified_app_with_conflict_merge(self):
  1539. """
  1540. makemigrations does not create a merge for an unspecified app even if
  1541. it has conflicting migrations.
  1542. """
  1543. # Monkeypatch interactive questioner to auto accept
  1544. with mock.patch('builtins.input', mock.Mock(return_value='y')):
  1545. out = io.StringIO()
  1546. with self.temporary_migration_module(app_label="migrated_app") as migration_dir:
  1547. call_command("makemigrations", "migrated_app", name="merge", merge=True, interactive=True, stdout=out)
  1548. merge_file = os.path.join(migration_dir, '0003_merge.py')
  1549. self.assertFalse(os.path.exists(merge_file))
  1550. self.assertIn("No conflicts detected to merge.", out.getvalue())
  1551. @override_settings(
  1552. INSTALLED_APPS=[
  1553. "migrations.migrations_test_apps.migrated_app",
  1554. "migrations.migrations_test_apps.conflicting_app_with_dependencies"])
  1555. def test_makemigrations_merge_dont_output_dependency_operations(self):
  1556. """
  1557. makemigrations --merge does not output any operations from apps that
  1558. don't belong to a given app.
  1559. """
  1560. # Monkeypatch interactive questioner to auto accept
  1561. with mock.patch('builtins.input', mock.Mock(return_value='N')):
  1562. out = io.StringIO()
  1563. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  1564. call_command(
  1565. "makemigrations", "conflicting_app_with_dependencies",
  1566. merge=True, interactive=True, stdout=out
  1567. )
  1568. self.assertEqual(
  1569. out.getvalue().lower(),
  1570. 'merging conflicting_app_with_dependencies\n'
  1571. ' branch 0002_conflicting_second\n'
  1572. ' - create model something\n'
  1573. ' branch 0002_second\n'
  1574. ' - delete model tribble\n'
  1575. ' - remove field silly_field from author\n'
  1576. ' - add field rating to author\n'
  1577. ' - create model book\n'
  1578. )
  1579. def test_makemigrations_with_custom_name(self):
  1580. """
  1581. makemigrations --name generate a custom migration name.
  1582. """
  1583. with self.temporary_migration_module() as migration_dir:
  1584. def cmd(migration_count, migration_name, *args):
  1585. call_command("makemigrations", "migrations", "--verbosity", "0", "--name", migration_name, *args)
  1586. migration_file = os.path.join(migration_dir, "%s_%s.py" % (migration_count, migration_name))
  1587. # Check for existing migration file in migration folder
  1588. self.assertTrue(os.path.exists(migration_file))
  1589. with open(migration_file, encoding='utf-8') as fp:
  1590. content = fp.read()
  1591. content = content.replace(" ", "")
  1592. return content
  1593. # generate an initial migration
  1594. migration_name_0001 = "my_initial_migration"
  1595. content = cmd("0001", migration_name_0001)
  1596. self.assertIn("dependencies=[\n]", content)
  1597. # importlib caches os.listdir() on some platforms like macOS
  1598. # (#23850).
  1599. if hasattr(importlib, 'invalidate_caches'):
  1600. importlib.invalidate_caches()
  1601. # generate an empty migration
  1602. migration_name_0002 = "my_custom_migration"
  1603. content = cmd("0002", migration_name_0002, "--empty")
  1604. self.assertIn("dependencies=[\n('migrations','0001_%s'),\n]" % migration_name_0001, content)
  1605. self.assertIn("operations=[\n]", content)
  1606. def test_makemigrations_with_invalid_custom_name(self):
  1607. msg = 'The migration name must be a valid Python identifier.'
  1608. with self.assertRaisesMessage(CommandError, msg):
  1609. call_command('makemigrations', 'migrations', '--name', 'invalid name', '--empty')
  1610. def test_makemigrations_check(self):
  1611. """
  1612. makemigrations --check should exit with a non-zero status when
  1613. there are changes to an app requiring migrations.
  1614. """
  1615. with self.temporary_migration_module():
  1616. with self.assertRaises(SystemExit):
  1617. call_command("makemigrations", "--check", "migrations", verbosity=0)
  1618. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  1619. call_command("makemigrations", "--check", "migrations", verbosity=0)
  1620. def test_makemigrations_migration_path_output(self):
  1621. """
  1622. makemigrations should print the relative paths to the migrations unless
  1623. they are outside of the current tree, in which case the absolute path
  1624. should be shown.
  1625. """
  1626. out = io.StringIO()
  1627. apps.register_model('migrations', UnicodeModel)
  1628. with self.temporary_migration_module() as migration_dir:
  1629. call_command("makemigrations", "migrations", stdout=out)
  1630. self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
  1631. def test_makemigrations_migration_path_output_valueerror(self):
  1632. """
  1633. makemigrations prints the absolute path if os.path.relpath() raises a
  1634. ValueError when it's impossible to obtain a relative path, e.g. on
  1635. Windows if Django is installed on a different drive than where the
  1636. migration files are created.
  1637. """
  1638. out = io.StringIO()
  1639. with self.temporary_migration_module() as migration_dir:
  1640. with mock.patch('os.path.relpath', side_effect=ValueError):
  1641. call_command('makemigrations', 'migrations', stdout=out)
  1642. self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
  1643. def test_makemigrations_inconsistent_history(self):
  1644. """
  1645. makemigrations should raise InconsistentMigrationHistory exception if
  1646. there are some migrations applied before their dependencies.
  1647. """
  1648. recorder = MigrationRecorder(connection)
  1649. recorder.record_applied('migrations', '0002_second')
  1650. msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
  1651. with self.temporary_migration_module(module="migrations.test_migrations"):
  1652. with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
  1653. call_command("makemigrations")
  1654. def test_makemigrations_inconsistent_history_db_failure(self):
  1655. msg = (
  1656. "Got an error checking a consistent migration history performed "
  1657. "for database connection 'default': could not connect to server"
  1658. )
  1659. with mock.patch(
  1660. 'django.db.migrations.loader.MigrationLoader.check_consistent_history',
  1661. side_effect=OperationalError('could not connect to server'),
  1662. ):
  1663. with self.temporary_migration_module():
  1664. with self.assertWarns(RuntimeWarning) as cm:
  1665. call_command('makemigrations', verbosity=0)
  1666. self.assertEqual(str(cm.warning), msg)
  1667. @mock.patch('builtins.input', return_value='1')
  1668. @mock.patch('django.db.migrations.questioner.sys.stdin', mock.MagicMock(encoding=sys.getdefaultencoding()))
  1669. def test_makemigrations_auto_now_add_interactive(self, *args):
  1670. """
  1671. makemigrations prompts the user when adding auto_now_add to an existing
  1672. model.
  1673. """
  1674. class Entry(models.Model):
  1675. title = models.CharField(max_length=255)
  1676. creation_date = models.DateTimeField(auto_now_add=True)
  1677. class Meta:
  1678. app_label = 'migrations'
  1679. input_msg = (
  1680. "It is impossible to add the field 'creation_date' with "
  1681. "'auto_now_add=True' to entry without providing a default. This "
  1682. "is because the database needs something to populate existing "
  1683. "rows.\n\n"
  1684. " 1) Provide a one-off default now which will be set on all "
  1685. "existing rows\n"
  1686. " 2) Quit and manually define a default value in models.py."
  1687. )
  1688. # Monkeypatch interactive questioner to auto accept
  1689. with mock.patch('django.db.migrations.questioner.sys.stdout', new_callable=io.StringIO) as prompt_stdout:
  1690. out = io.StringIO()
  1691. with self.temporary_migration_module(module='migrations.test_auto_now_add'):
  1692. call_command('makemigrations', 'migrations', interactive=True, stdout=out)
  1693. output = out.getvalue()
  1694. prompt_output = prompt_stdout.getvalue()
  1695. self.assertIn(input_msg, prompt_output)
  1696. self.assertIn(
  1697. 'Please enter the default value as valid Python.',
  1698. prompt_output,
  1699. )
  1700. self.assertIn(
  1701. "Accept the default 'timezone.now' by pressing 'Enter' or "
  1702. "provide another value.",
  1703. prompt_output,
  1704. )
  1705. self.assertIn("Type 'exit' to exit this prompt", prompt_output)
  1706. self.assertIn("Add field creation_date to entry", output)
  1707. @mock.patch('builtins.input', return_value='2')
  1708. def test_makemigrations_auto_now_add_interactive_quit(self, mock_input):
  1709. class Author(models.Model):
  1710. publishing_date = models.DateField(auto_now_add=True)
  1711. class Meta:
  1712. app_label = 'migrations'
  1713. with self.temporary_migration_module(module='migrations.test_migrations'):
  1714. with captured_stdout():
  1715. with self.assertRaises(SystemExit):
  1716. call_command('makemigrations', 'migrations', interactive=True)
  1717. def test_makemigrations_non_interactive_auto_now_add_addition(self):
  1718. """
  1719. Non-interactive makemigrations fails when a default is missing on a
  1720. new field when auto_now_add=True.
  1721. """
  1722. class Entry(models.Model):
  1723. creation_date = models.DateTimeField(auto_now_add=True)
  1724. class Meta:
  1725. app_label = 'migrations'
  1726. with self.temporary_migration_module(module='migrations.test_auto_now_add'):
  1727. with self.assertRaises(SystemExit), captured_stdout() as out:
  1728. call_command('makemigrations', 'migrations', interactive=False)
  1729. self.assertIn(
  1730. "Field 'creation_date' on model 'entry' not migrated: it is "
  1731. "impossible to add a field with 'auto_now_add=True' without "
  1732. "specifying a default.",
  1733. out.getvalue(),
  1734. )
  1735. def test_makemigrations_interactive_unique_callable_default_addition(self):
  1736. """
  1737. makemigrations prompts the user when adding a unique field with
  1738. a callable default.
  1739. """
  1740. class Book(models.Model):
  1741. created = models.DateTimeField(unique=True, default=timezone.now)
  1742. class Meta:
  1743. app_label = 'migrations'
  1744. version = get_docs_version()
  1745. input_msg = (
  1746. f'Callable default on unique field book.created will not generate '
  1747. f'unique values upon migrating.\n'
  1748. f'Please choose how to proceed:\n\n'
  1749. f' 1) Continue making this migration as the first step in writing '
  1750. f'a manual migration to generate unique values described here: '
  1751. f'https://docs.djangoproject.com/en/{version}/howto/'
  1752. f'writing-migrations/#migrations-that-add-unique-fields.\n'
  1753. f' 2) Quit and edit field options in models.py.\n'
  1754. )
  1755. with self.temporary_migration_module(module='migrations.test_migrations'):
  1756. # 2 - quit.
  1757. with mock.patch('builtins.input', return_value='2'):
  1758. with captured_stdout() as out, self.assertRaises(SystemExit):
  1759. call_command('makemigrations', 'migrations', interactive=True)
  1760. out_value = out.getvalue()
  1761. self.assertIn(input_msg, out_value)
  1762. self.assertNotIn('Add field created to book', out_value)
  1763. # 1 - continue.
  1764. with mock.patch('builtins.input', return_value='1'):
  1765. with captured_stdout() as out:
  1766. call_command('makemigrations', 'migrations', interactive=True)
  1767. out_value = out.getvalue()
  1768. self.assertIn(input_msg, out_value)
  1769. self.assertIn('Add field created to book', out_value)
  1770. def test_makemigrations_non_interactive_unique_callable_default_addition(self):
  1771. class Book(models.Model):
  1772. created = models.DateTimeField(unique=True, default=timezone.now)
  1773. class Meta:
  1774. app_label = 'migrations'
  1775. with self.temporary_migration_module(module='migrations.test_migrations'):
  1776. with captured_stdout() as out:
  1777. call_command('makemigrations', 'migrations', interactive=False)
  1778. out_value = out.getvalue()
  1779. self.assertIn('Add field created to book', out_value)
  1780. class SquashMigrationsTests(MigrationTestBase):
  1781. """
  1782. Tests running the squashmigrations command.
  1783. """
  1784. def test_squashmigrations_squashes(self):
  1785. """
  1786. squashmigrations squashes migrations.
  1787. """
  1788. out = io.StringIO()
  1789. with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
  1790. call_command('squashmigrations', 'migrations', '0002', interactive=False, stdout=out, no_color=True)
  1791. squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
  1792. self.assertTrue(os.path.exists(squashed_migration_file))
  1793. self.assertEqual(
  1794. out.getvalue(),
  1795. 'Will squash the following migrations:\n'
  1796. ' - 0001_initial\n'
  1797. ' - 0002_second\n'
  1798. 'Optimizing...\n'
  1799. ' Optimized from 8 operations to 2 operations.\n'
  1800. 'Created new squashed migration %s\n'
  1801. ' You should commit this migration but leave the old ones in place;\n'
  1802. ' the new migration will be used for new installs. Once you are sure\n'
  1803. ' all instances of the codebase have applied the migrations you squashed,\n'
  1804. ' you can delete them.\n' % squashed_migration_file
  1805. )
  1806. def test_squashmigrations_initial_attribute(self):
  1807. with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
  1808. call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
  1809. squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
  1810. with open(squashed_migration_file, encoding='utf-8') as fp:
  1811. content = fp.read()
  1812. self.assertIn("initial = True", content)
  1813. def test_squashmigrations_optimizes(self):
  1814. """
  1815. squashmigrations optimizes operations.
  1816. """
  1817. out = io.StringIO()
  1818. with self.temporary_migration_module(module="migrations.test_migrations"):
  1819. call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=1, stdout=out)
  1820. self.assertIn("Optimized from 8 operations to 2 operations.", out.getvalue())
  1821. def test_ticket_23799_squashmigrations_no_optimize(self):
  1822. """
  1823. squashmigrations --no-optimize doesn't optimize operations.
  1824. """
  1825. out = io.StringIO()
  1826. with self.temporary_migration_module(module="migrations.test_migrations"):
  1827. call_command("squashmigrations", "migrations", "0002",
  1828. interactive=False, verbosity=1, no_optimize=True, stdout=out)
  1829. self.assertIn("Skipping optimization", out.getvalue())
  1830. def test_squashmigrations_valid_start(self):
  1831. """
  1832. squashmigrations accepts a starting migration.
  1833. """
  1834. out = io.StringIO()
  1835. with self.temporary_migration_module(module="migrations.test_migrations_no_changes") as migration_dir:
  1836. call_command("squashmigrations", "migrations", "0002", "0003",
  1837. interactive=False, verbosity=1, stdout=out)
  1838. squashed_migration_file = os.path.join(migration_dir, "0002_second_squashed_0003_third.py")
  1839. with open(squashed_migration_file, encoding='utf-8') as fp:
  1840. content = fp.read()
  1841. self.assertIn(" ('migrations', '0001_initial')", content)
  1842. self.assertNotIn("initial = True", content)
  1843. out = out.getvalue()
  1844. self.assertNotIn(" - 0001_initial", out)
  1845. self.assertIn(" - 0002_second", out)
  1846. self.assertIn(" - 0003_third", out)
  1847. def test_squashmigrations_invalid_start(self):
  1848. """
  1849. squashmigrations doesn't accept a starting migration after the ending migration.
  1850. """
  1851. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  1852. msg = (
  1853. "The migration 'migrations.0003_third' cannot be found. Maybe "
  1854. "it comes after the migration 'migrations.0002_second'"
  1855. )
  1856. with self.assertRaisesMessage(CommandError, msg):
  1857. call_command("squashmigrations", "migrations", "0003", "0002", interactive=False, verbosity=0)
  1858. def test_squashed_name_with_start_migration_name(self):
  1859. """--squashed-name specifies the new migration's name."""
  1860. squashed_name = 'squashed_name'
  1861. with self.temporary_migration_module(module='migrations.test_migrations') as migration_dir:
  1862. call_command(
  1863. 'squashmigrations', 'migrations', '0001', '0002',
  1864. squashed_name=squashed_name, interactive=False, verbosity=0,
  1865. )
  1866. squashed_migration_file = os.path.join(migration_dir, '0001_%s.py' % squashed_name)
  1867. self.assertTrue(os.path.exists(squashed_migration_file))
  1868. def test_squashed_name_without_start_migration_name(self):
  1869. """--squashed-name also works if a start migration is omitted."""
  1870. squashed_name = 'squashed_name'
  1871. with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
  1872. call_command(
  1873. 'squashmigrations', 'migrations', '0001',
  1874. squashed_name=squashed_name, interactive=False, verbosity=0,
  1875. )
  1876. squashed_migration_file = os.path.join(migration_dir, '0001_%s.py' % squashed_name)
  1877. self.assertTrue(os.path.exists(squashed_migration_file))
  1878. class AppLabelErrorTests(TestCase):
  1879. """
  1880. This class inherits TestCase because MigrationTestBase uses
  1881. `available_apps = ['migrations']` which means that it's the only installed
  1882. app. 'django.contrib.auth' must be in INSTALLED_APPS for some of these
  1883. tests.
  1884. """
  1885. nonexistent_app_error = "No installed app with label 'nonexistent_app'."
  1886. did_you_mean_auth_error = (
  1887. "No installed app with label 'django.contrib.auth'. Did you mean "
  1888. "'auth'?"
  1889. )
  1890. def test_makemigrations_nonexistent_app_label(self):
  1891. err = io.StringIO()
  1892. with self.assertRaises(SystemExit):
  1893. call_command('makemigrations', 'nonexistent_app', stderr=err)
  1894. self.assertIn(self.nonexistent_app_error, err.getvalue())
  1895. def test_makemigrations_app_name_specified_as_label(self):
  1896. err = io.StringIO()
  1897. with self.assertRaises(SystemExit):
  1898. call_command('makemigrations', 'django.contrib.auth', stderr=err)
  1899. self.assertIn(self.did_you_mean_auth_error, err.getvalue())
  1900. def test_migrate_nonexistent_app_label(self):
  1901. with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
  1902. call_command('migrate', 'nonexistent_app')
  1903. def test_migrate_app_name_specified_as_label(self):
  1904. with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
  1905. call_command('migrate', 'django.contrib.auth')
  1906. def test_showmigrations_nonexistent_app_label(self):
  1907. err = io.StringIO()
  1908. with self.assertRaises(SystemExit):
  1909. call_command('showmigrations', 'nonexistent_app', stderr=err)
  1910. self.assertIn(self.nonexistent_app_error, err.getvalue())
  1911. def test_showmigrations_app_name_specified_as_label(self):
  1912. err = io.StringIO()
  1913. with self.assertRaises(SystemExit):
  1914. call_command('showmigrations', 'django.contrib.auth', stderr=err)
  1915. self.assertIn(self.did_you_mean_auth_error, err.getvalue())
  1916. def test_sqlmigrate_nonexistent_app_label(self):
  1917. with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
  1918. call_command('sqlmigrate', 'nonexistent_app', '0002')
  1919. def test_sqlmigrate_app_name_specified_as_label(self):
  1920. with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
  1921. call_command('sqlmigrate', 'django.contrib.auth', '0002')
  1922. def test_squashmigrations_nonexistent_app_label(self):
  1923. with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
  1924. call_command('squashmigrations', 'nonexistent_app', '0002')
  1925. def test_squashmigrations_app_name_specified_as_label(self):
  1926. with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
  1927. call_command('squashmigrations', 'django.contrib.auth', '0002')