test_commands.py 72 KB

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