test_commands.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import codecs
  4. import importlib
  5. import os
  6. from django.apps import apps
  7. from django.core.management import CommandError, call_command
  8. from django.db import DatabaseError, connection, models
  9. from django.db.migrations.recorder import MigrationRecorder
  10. from django.test import ignore_warnings, mock, override_settings
  11. from django.utils import six
  12. from django.utils.deprecation import RemovedInDjango20Warning
  13. from django.utils.encoding import force_text
  14. from .models import UnicodeModel, UnserializableModel
  15. from .test_base import MigrationTestBase
  16. class MigrateTests(MigrationTestBase):
  17. """
  18. Tests running the migrate command.
  19. """
  20. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  21. def test_migrate(self):
  22. """
  23. Tests basic usage of the migrate command.
  24. """
  25. # Make sure no tables are created
  26. self.assertTableNotExists("migrations_author")
  27. self.assertTableNotExists("migrations_tribble")
  28. self.assertTableNotExists("migrations_book")
  29. # Run the migrations to 0001 only
  30. call_command("migrate", "migrations", "0001", verbosity=0)
  31. # Make sure the right tables exist
  32. self.assertTableExists("migrations_author")
  33. self.assertTableExists("migrations_tribble")
  34. self.assertTableNotExists("migrations_book")
  35. # Run migrations all the way
  36. call_command("migrate", verbosity=0)
  37. # Make sure the right tables exist
  38. self.assertTableExists("migrations_author")
  39. self.assertTableNotExists("migrations_tribble")
  40. self.assertTableExists("migrations_book")
  41. # Unmigrate everything
  42. call_command("migrate", "migrations", "zero", verbosity=0)
  43. # Make sure it's all gone
  44. self.assertTableNotExists("migrations_author")
  45. self.assertTableNotExists("migrations_tribble")
  46. self.assertTableNotExists("migrations_book")
  47. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"})
  48. def test_migrate_initial_false(self):
  49. """
  50. `Migration.initial = False` skips fake-initial detection.
  51. """
  52. # Make sure no tables are created
  53. self.assertTableNotExists("migrations_author")
  54. self.assertTableNotExists("migrations_tribble")
  55. # Run the migrations to 0001 only
  56. call_command("migrate", "migrations", "0001", verbosity=0)
  57. # Fake rollback
  58. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  59. # Make sure fake-initial detection does not run
  60. with self.assertRaises(DatabaseError):
  61. call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0)
  62. call_command("migrate", "migrations", "0001", fake=True, verbosity=0)
  63. # Real rollback
  64. call_command("migrate", "migrations", "zero", verbosity=0)
  65. # Make sure it's all gone
  66. self.assertTableNotExists("migrations_author")
  67. self.assertTableNotExists("migrations_tribble")
  68. self.assertTableNotExists("migrations_book")
  69. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  70. def test_migrate_fake_initial(self):
  71. """
  72. #24184 - Tests that --fake-initial only works if all tables created in
  73. the initial migration of an app exists
  74. """
  75. # Make sure no tables are created
  76. self.assertTableNotExists("migrations_author")
  77. self.assertTableNotExists("migrations_tribble")
  78. # Run the migrations to 0001 only
  79. call_command("migrate", "migrations", "0001", verbosity=0)
  80. # Make sure the right tables exist
  81. self.assertTableExists("migrations_author")
  82. self.assertTableExists("migrations_tribble")
  83. # Fake a roll-back
  84. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  85. # Make sure the tables still exist
  86. self.assertTableExists("migrations_author")
  87. self.assertTableExists("migrations_tribble")
  88. # Try to run initial migration
  89. with self.assertRaises(DatabaseError):
  90. call_command("migrate", "migrations", "0001", verbosity=0)
  91. # Run initial migration with an explicit --fake-initial
  92. out = six.StringIO()
  93. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  94. call_command("migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1)
  95. self.assertIn(
  96. "migrations.0001_initial... faked",
  97. out.getvalue().lower()
  98. )
  99. # Run migrations all the way
  100. call_command("migrate", verbosity=0)
  101. # Make sure the right tables exist
  102. self.assertTableExists("migrations_author")
  103. self.assertTableNotExists("migrations_tribble")
  104. self.assertTableExists("migrations_book")
  105. # Fake a roll-back
  106. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  107. # Make sure the tables still exist
  108. self.assertTableExists("migrations_author")
  109. self.assertTableNotExists("migrations_tribble")
  110. self.assertTableExists("migrations_book")
  111. # Try to run initial migration
  112. with self.assertRaises(DatabaseError):
  113. call_command("migrate", "migrations", verbosity=0)
  114. # Run initial migration with an explicit --fake-initial
  115. with self.assertRaises(DatabaseError):
  116. # Fails because "migrations_tribble" does not exist but needs to in
  117. # order to make --fake-initial work.
  118. call_command("migrate", "migrations", fake_initial=True, verbosity=0)
  119. # Fake a apply
  120. call_command("migrate", "migrations", fake=True, verbosity=0)
  121. # Unmigrate everything
  122. call_command("migrate", "migrations", "zero", verbosity=0)
  123. # Make sure it's all gone
  124. self.assertTableNotExists("migrations_author")
  125. self.assertTableNotExists("migrations_tribble")
  126. self.assertTableNotExists("migrations_book")
  127. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_fake_split_initial"})
  128. def test_migrate_fake_split_initial(self):
  129. """
  130. Split initial migrations can be faked with --fake-initial.
  131. """
  132. call_command("migrate", "migrations", "0002", verbosity=0)
  133. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  134. out = six.StringIO()
  135. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  136. call_command("migrate", "migrations", "0002", fake_initial=True, stdout=out, verbosity=1)
  137. value = out.getvalue().lower()
  138. self.assertIn("migrations.0001_initial... faked", value)
  139. self.assertIn("migrations.0002_second... faked", value)
  140. # Fake an apply
  141. call_command("migrate", "migrations", fake=True, verbosity=0)
  142. # Unmigrate everything
  143. call_command("migrate", "migrations", "zero", verbosity=0)
  144. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"})
  145. def test_migrate_conflict_exit(self):
  146. """
  147. Makes sure that migrate exits if it detects a conflict.
  148. """
  149. with self.assertRaisesMessage(CommandError, "Conflicting migrations detected"):
  150. call_command("migrate", "migrations")
  151. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  152. def test_showmigrations_list(self):
  153. """
  154. Tests --list output of showmigrations command
  155. """
  156. out = six.StringIO()
  157. with mock.patch('django.core.management.color.supports_color', lambda *args: True):
  158. call_command("showmigrations", format='list', stdout=out, verbosity=0, no_color=False)
  159. self.assertEqual(
  160. '\x1b[1mmigrations\n\x1b[0m'
  161. ' [ ] 0001_initial\n'
  162. ' [ ] 0002_second\n',
  163. out.getvalue().lower()
  164. )
  165. call_command("migrate", "migrations", "0001", verbosity=0)
  166. out = six.StringIO()
  167. # Giving the explicit app_label tests for selective `show_list` in the command
  168. call_command("showmigrations", "migrations", format='list', stdout=out, verbosity=0, no_color=True)
  169. self.assertEqual(
  170. 'migrations\n'
  171. ' [x] 0001_initial\n'
  172. ' [ ] 0002_second\n',
  173. out.getvalue().lower()
  174. )
  175. # Cleanup by unmigrating everything
  176. call_command("migrate", "migrations", "zero", verbosity=0)
  177. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"})
  178. def test_showmigrations_plan(self):
  179. """
  180. Tests --plan output of showmigrations command
  181. """
  182. out = six.StringIO()
  183. call_command("showmigrations", format='plan', stdout=out)
  184. self.assertIn(
  185. "[ ] migrations.0001_initial\n"
  186. "[ ] migrations.0003_third\n"
  187. "[ ] migrations.0002_second",
  188. out.getvalue().lower()
  189. )
  190. out = six.StringIO()
  191. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  192. self.assertIn(
  193. "[ ] migrations.0001_initial\n"
  194. "[ ] migrations.0003_third ... (migrations.0001_initial)\n"
  195. "[ ] migrations.0002_second ... (migrations.0001_initial)",
  196. out.getvalue().lower()
  197. )
  198. call_command("migrate", "migrations", "0003", verbosity=0)
  199. out = six.StringIO()
  200. call_command("showmigrations", format='plan', stdout=out)
  201. self.assertIn(
  202. "[x] migrations.0001_initial\n"
  203. "[x] migrations.0003_third\n"
  204. "[ ] migrations.0002_second",
  205. out.getvalue().lower()
  206. )
  207. out = six.StringIO()
  208. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  209. self.assertIn(
  210. "[x] migrations.0001_initial\n"
  211. "[x] migrations.0003_third ... (migrations.0001_initial)\n"
  212. "[ ] migrations.0002_second ... (migrations.0001_initial)",
  213. out.getvalue().lower()
  214. )
  215. # Cleanup by unmigrating everything
  216. call_command("migrate", "migrations", "zero", verbosity=0)
  217. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"})
  218. def test_showmigrations_plan_no_migrations(self):
  219. """
  220. Tests --plan output of showmigrations command without migrations
  221. """
  222. out = six.StringIO()
  223. call_command("showmigrations", format='plan', stdout=out)
  224. self.assertEqual("", out.getvalue().lower())
  225. out = six.StringIO()
  226. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  227. self.assertEqual("", out.getvalue().lower())
  228. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"})
  229. def test_showmigrations_plan_squashed(self):
  230. """
  231. Tests --plan output of showmigrations command with squashed migrations.
  232. """
  233. out = six.StringIO()
  234. call_command("showmigrations", format='plan', stdout=out)
  235. self.assertEqual(
  236. "[ ] migrations.1_auto\n"
  237. "[ ] migrations.2_auto\n"
  238. "[ ] migrations.3_squashed_5\n"
  239. "[ ] migrations.6_auto\n"
  240. "[ ] migrations.7_auto\n",
  241. out.getvalue().lower()
  242. )
  243. out = six.StringIO()
  244. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  245. self.assertEqual(
  246. "[ ] migrations.1_auto\n"
  247. "[ ] migrations.2_auto ... (migrations.1_auto)\n"
  248. "[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n"
  249. "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
  250. "[ ] migrations.7_auto ... (migrations.6_auto)\n",
  251. out.getvalue().lower()
  252. )
  253. call_command("migrate", "migrations", "3_squashed_5", verbosity=0)
  254. out = six.StringIO()
  255. call_command("showmigrations", format='plan', stdout=out)
  256. self.assertEqual(
  257. "[x] migrations.1_auto\n"
  258. "[x] migrations.2_auto\n"
  259. "[x] migrations.3_squashed_5\n"
  260. "[ ] migrations.6_auto\n"
  261. "[ ] migrations.7_auto\n",
  262. out.getvalue().lower()
  263. )
  264. out = six.StringIO()
  265. call_command("showmigrations", format='plan', stdout=out, verbosity=2)
  266. self.assertEqual(
  267. "[x] migrations.1_auto\n"
  268. "[x] migrations.2_auto ... (migrations.1_auto)\n"
  269. "[x] migrations.3_squashed_5 ... (migrations.2_auto)\n"
  270. "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
  271. "[ ] migrations.7_auto ... (migrations.6_auto)\n",
  272. out.getvalue().lower()
  273. )
  274. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  275. def test_sqlmigrate_forwards(self):
  276. """
  277. Makes sure that sqlmigrate does something.
  278. """
  279. out = six.StringIO()
  280. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  281. output = out.getvalue().lower()
  282. index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
  283. index_op_desc_author = output.find('-- create model author')
  284. index_create_table = output.find('create table')
  285. index_op_desc_tribble = output.find('-- create model tribble')
  286. index_op_desc_unique_together = output.find('-- alter unique_together')
  287. index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
  288. self.assertGreater(index_tx_start, -1, "Transaction start not found")
  289. self.assertGreater(index_op_desc_author, index_tx_start,
  290. "Operation description (author) not found or found before transaction start")
  291. self.assertGreater(index_create_table, index_op_desc_author,
  292. "CREATE TABLE not found or found before operation description (author)")
  293. self.assertGreater(index_op_desc_tribble, index_create_table,
  294. "Operation description (tribble) not found or found before CREATE TABLE (author)")
  295. self.assertGreater(index_op_desc_unique_together, index_op_desc_tribble,
  296. "Operation description (unique_together) not found or found before operation description (tribble)")
  297. self.assertGreater(index_tx_end, index_op_desc_unique_together,
  298. "Transaction end not found or found before operation description (unique_together)")
  299. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  300. def test_sqlmigrate_backwards(self):
  301. """
  302. Makes sure that sqlmigrate does something.
  303. """
  304. # Cannot generate the reverse SQL unless we've applied the migration.
  305. call_command("migrate", "migrations", verbosity=0)
  306. out = six.StringIO()
  307. call_command("sqlmigrate", "migrations", "0001", stdout=out, backwards=True)
  308. output = out.getvalue().lower()
  309. index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
  310. index_op_desc_unique_together = output.find('-- alter unique_together')
  311. index_op_desc_tribble = output.find('-- create model tribble')
  312. index_op_desc_author = output.find('-- create model author')
  313. index_drop_table = output.rfind('drop table')
  314. index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
  315. self.assertGreater(index_tx_start, -1, "Transaction start not found")
  316. self.assertGreater(index_op_desc_unique_together, index_tx_start,
  317. "Operation description (unique_together) not found or found before transaction start")
  318. self.assertGreater(index_op_desc_tribble, index_op_desc_unique_together,
  319. "Operation description (tribble) not found or found before operation description (unique_together)")
  320. self.assertGreater(index_op_desc_author, index_op_desc_tribble,
  321. "Operation description (author) not found or found before operation description (tribble)")
  322. self.assertGreater(index_drop_table, index_op_desc_author,
  323. "DROP TABLE not found or found before operation description (author)")
  324. self.assertGreater(index_tx_end, index_op_desc_unique_together,
  325. "Transaction end not found or found before DROP TABLE")
  326. # Cleanup by unmigrating everything
  327. call_command("migrate", "migrations", "zero", verbosity=0)
  328. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"})
  329. def test_sqlmigrate_for_non_atomic_migration(self):
  330. """
  331. Transaction wrappers aren't shown for non-atomic migrations.
  332. """
  333. out = six.StringIO()
  334. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  335. output = out.getvalue().lower()
  336. queries = [q.strip() for q in output.splitlines()]
  337. if connection.ops.start_transaction_sql():
  338. self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)
  339. self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
  340. @override_settings(
  341. INSTALLED_APPS=[
  342. "migrations.migrations_test_apps.migrated_app",
  343. "migrations.migrations_test_apps.migrated_unapplied_app",
  344. "migrations.migrations_test_apps.unmigrated_app"])
  345. def test_regression_22823_unmigrated_fk_to_migrated_model(self):
  346. """
  347. https://code.djangoproject.com/ticket/22823
  348. Assuming you have 3 apps, `A`, `B`, and `C`, such that:
  349. * `A` has migrations
  350. * `B` has a migration we want to apply
  351. * `C` has no migrations, but has an FK to `A`
  352. When we try to migrate "B", an exception occurs because the
  353. "B" was not included in the ProjectState that is used to detect
  354. soft-applied migrations.
  355. """
  356. call_command("migrate", "migrated_unapplied_app", stdout=six.StringIO())
  357. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
  358. def test_migrate_record_replaced(self):
  359. """
  360. Running a single squashed migration should record all of the original
  361. replaced migrations as run.
  362. """
  363. recorder = MigrationRecorder(connection)
  364. out = six.StringIO()
  365. call_command("migrate", "migrations", verbosity=0)
  366. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  367. self.assertEqual(
  368. 'migrations\n'
  369. ' [x] 0001_squashed_0002 (2 squashed migrations)\n',
  370. out.getvalue().lower()
  371. )
  372. applied_migrations = recorder.applied_migrations()
  373. self.assertIn(("migrations", "0001_initial"), applied_migrations)
  374. self.assertIn(("migrations", "0002_second"), applied_migrations)
  375. self.assertIn(("migrations", "0001_squashed_0002"), applied_migrations)
  376. # Rollback changes
  377. call_command("migrate", "migrations", "zero", verbosity=0)
  378. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
  379. def test_migrate_record_squashed(self):
  380. """
  381. Running migrate for a squashed migration should record as run
  382. if all of the replaced migrations have been run (#25231).
  383. """
  384. recorder = MigrationRecorder(connection)
  385. recorder.record_applied("migrations", "0001_initial")
  386. recorder.record_applied("migrations", "0002_second")
  387. out = six.StringIO()
  388. call_command("migrate", "migrations", verbosity=0)
  389. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  390. self.assertEqual(
  391. 'migrations\n'
  392. ' [x] 0001_squashed_0002 (2 squashed migrations)\n',
  393. out.getvalue().lower()
  394. )
  395. self.assertIn(
  396. ("migrations", "0001_squashed_0002"),
  397. recorder.applied_migrations()
  398. )
  399. # No changes were actually applied so there is nothing to rollback
  400. class MakeMigrationsTests(MigrationTestBase):
  401. """
  402. Tests running the makemigrations command.
  403. """
  404. def setUp(self):
  405. super(MigrationTestBase, self).setUp()
  406. self._old_models = apps.app_configs['migrations'].models.copy()
  407. def tearDown(self):
  408. apps.app_configs['migrations'].models = self._old_models
  409. apps.all_models['migrations'] = self._old_models
  410. apps.clear_cache()
  411. super(MigrationTestBase, self).tearDown()
  412. def test_files_content(self):
  413. self.assertTableNotExists("migrations_unicodemodel")
  414. apps.register_model('migrations', UnicodeModel)
  415. with self.temporary_migration_module() as migration_dir:
  416. call_command("makemigrations", "migrations", verbosity=0)
  417. # Check for empty __init__.py file in migrations folder
  418. init_file = os.path.join(migration_dir, "__init__.py")
  419. self.assertTrue(os.path.exists(init_file))
  420. with open(init_file, 'r') as fp:
  421. content = force_text(fp.read())
  422. self.assertEqual(content, '')
  423. # Check for existing 0001_initial.py file in migration folder
  424. initial_file = os.path.join(migration_dir, "0001_initial.py")
  425. self.assertTrue(os.path.exists(initial_file))
  426. with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
  427. content = fp.read()
  428. self.assertIn('# -*- coding: utf-8 -*-', content)
  429. self.assertIn('migrations.CreateModel', content)
  430. self.assertIn('initial = True', content)
  431. if six.PY3:
  432. self.assertIn('úñí©óðé µóðéø', content) # Meta.verbose_name
  433. self.assertIn('úñí©óðé µóðéøß', content) # Meta.verbose_name_plural
  434. self.assertIn('ÚÑÍ¢ÓÐÉ', content) # title.verbose_name
  435. self.assertIn('“Ðjáñgó”', content) # title.default
  436. else:
  437. # Meta.verbose_name
  438. self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8', content)
  439. # Meta.verbose_name_plural
  440. self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf', content)
  441. self.assertIn('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9', content) # title.verbose_name
  442. self.assertIn('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d', content) # title.default
  443. def test_makemigrations_order(self):
  444. """
  445. makemigrations should recognize number-only migrations (0001.py).
  446. """
  447. module = 'migrations.test_migrations_order'
  448. with self.temporary_migration_module(module=module) as migration_dir:
  449. if hasattr(importlib, 'invalidate_caches'):
  450. # Python 3 importlib caches os.listdir() on some platforms like
  451. # Mac OS X (#23850).
  452. importlib.invalidate_caches()
  453. call_command('makemigrations', 'migrations', '--empty', '-n', 'a', '-v', '0')
  454. self.assertTrue(os.path.exists(os.path.join(migration_dir, '0002_a.py')))
  455. def test_failing_migration(self):
  456. # If a migration fails to serialize, it shouldn't generate an empty file. #21280
  457. apps.register_model('migrations', UnserializableModel)
  458. with self.temporary_migration_module() as migration_dir:
  459. with self.assertRaisesMessage(ValueError, 'Cannot serialize'):
  460. call_command("makemigrations", "migrations", verbosity=0)
  461. initial_file = os.path.join(migration_dir, "0001_initial.py")
  462. self.assertFalse(os.path.exists(initial_file))
  463. def test_makemigrations_conflict_exit(self):
  464. """
  465. Makes sure that makemigrations exits if it detects a conflict.
  466. """
  467. with self.temporary_migration_module(module="migrations.test_migrations_conflict"):
  468. with self.assertRaises(CommandError):
  469. call_command("makemigrations")
  470. def test_makemigrations_merge_no_conflict(self):
  471. """
  472. Makes sure that makemigrations exits if in merge mode with no conflicts.
  473. """
  474. out = six.StringIO()
  475. with self.temporary_migration_module(module="migrations.test_migrations"):
  476. try:
  477. call_command("makemigrations", merge=True, stdout=out)
  478. except CommandError:
  479. self.fail("Makemigrations errored in merge mode with no conflicts")
  480. self.assertIn("No conflicts detected to merge.", out.getvalue())
  481. def test_makemigrations_no_app_sys_exit(self):
  482. """
  483. Makes sure that makemigrations exits if a non-existent app is specified.
  484. """
  485. err = six.StringIO()
  486. with self.assertRaises(SystemExit):
  487. call_command("makemigrations", "this_app_does_not_exist", stderr=err)
  488. self.assertIn("'this_app_does_not_exist' could not be found.", err.getvalue())
  489. def test_makemigrations_empty_no_app_specified(self):
  490. """
  491. Makes sure that makemigrations exits if no app is specified with 'empty' mode.
  492. """
  493. with self.assertRaises(CommandError):
  494. call_command("makemigrations", empty=True)
  495. def test_makemigrations_empty_migration(self):
  496. """
  497. Makes sure that makemigrations properly constructs an empty migration.
  498. """
  499. with self.temporary_migration_module() as migration_dir:
  500. try:
  501. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  502. except CommandError:
  503. self.fail("Makemigrations errored in creating empty migration for a proper app.")
  504. # Check for existing 0001_initial.py file in migration folder
  505. initial_file = os.path.join(migration_dir, "0001_initial.py")
  506. self.assertTrue(os.path.exists(initial_file))
  507. with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
  508. content = fp.read()
  509. self.assertIn('# -*- coding: utf-8 -*-', content)
  510. # Remove all whitespace to check for empty dependencies and operations
  511. content = content.replace(' ', '')
  512. self.assertIn('dependencies=[\n]', content)
  513. self.assertIn('operations=[\n]', content)
  514. @override_settings(MIGRATION_MODULES={"migrations": None})
  515. def test_makemigrations_disabled_migrations_for_app(self):
  516. """
  517. makemigrations raises a nice error when migrations are disabled for an
  518. app.
  519. """
  520. msg = (
  521. "Django can't create migrations for app 'migrations' because migrations "
  522. "have been disabled via the MIGRATION_MODULES setting."
  523. )
  524. with self.assertRaisesMessage(ValueError, msg):
  525. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  526. def test_makemigrations_no_changes_no_apps(self):
  527. """
  528. Makes sure that makemigrations exits when there are no changes and no apps are specified.
  529. """
  530. out = six.StringIO()
  531. call_command("makemigrations", stdout=out)
  532. self.assertIn("No changes detected", out.getvalue())
  533. def test_makemigrations_no_changes(self):
  534. """
  535. Makes sure that makemigrations exits when there are no changes to an app.
  536. """
  537. out = six.StringIO()
  538. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  539. call_command("makemigrations", "migrations", stdout=out)
  540. self.assertIn("No changes detected in app 'migrations'", out.getvalue())
  541. def test_makemigrations_no_apps_initial(self):
  542. """
  543. makemigrations should detect initial is needed on empty migration
  544. modules if no app provided.
  545. """
  546. out = six.StringIO()
  547. with self.temporary_migration_module(module="migrations.test_migrations_empty"):
  548. call_command("makemigrations", stdout=out)
  549. self.assertIn("0001_initial.py", out.getvalue())
  550. def test_makemigrations_migrations_announce(self):
  551. """
  552. Makes sure that makemigrations announces the migration at the default verbosity level.
  553. """
  554. out = six.StringIO()
  555. with self.temporary_migration_module():
  556. call_command("makemigrations", "migrations", stdout=out)
  557. self.assertIn("Migrations for 'migrations'", out.getvalue())
  558. def test_makemigrations_no_common_ancestor(self):
  559. """
  560. Makes sure that makemigrations fails to merge migrations with no common ancestor.
  561. """
  562. with self.assertRaises(ValueError) as context:
  563. with self.temporary_migration_module(module="migrations.test_migrations_no_ancestor"):
  564. call_command("makemigrations", "migrations", merge=True)
  565. exception_message = str(context.exception)
  566. self.assertIn("Could not find common ancestor of", exception_message)
  567. self.assertIn("0002_second", exception_message)
  568. self.assertIn("0002_conflicting_second", exception_message)
  569. def test_makemigrations_interactive_reject(self):
  570. """
  571. Makes sure that makemigrations enters and exits interactive mode properly.
  572. """
  573. # Monkeypatch interactive questioner to auto reject
  574. with mock.patch('django.db.migrations.questioner.input', mock.Mock(return_value='N')):
  575. try:
  576. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  577. call_command("makemigrations", "migrations", merge=True, interactive=True, verbosity=0)
  578. merge_file = os.path.join(migration_dir, '0003_merge.py')
  579. self.assertFalse(os.path.exists(merge_file))
  580. except CommandError:
  581. self.fail("Makemigrations failed while running interactive questioner")
  582. def test_makemigrations_interactive_accept(self):
  583. """
  584. Makes sure that makemigrations enters interactive mode and merges properly.
  585. """
  586. # Monkeypatch interactive questioner to auto accept
  587. with mock.patch('django.db.migrations.questioner.input', mock.Mock(return_value='y')):
  588. out = six.StringIO()
  589. try:
  590. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  591. call_command("makemigrations", "migrations", merge=True, interactive=True, stdout=out)
  592. merge_file = os.path.join(migration_dir, '0003_merge.py')
  593. self.assertTrue(os.path.exists(merge_file))
  594. except CommandError:
  595. self.fail("Makemigrations failed while running interactive questioner")
  596. self.assertIn("Created new merge migration", force_text(out.getvalue()))
  597. def test_makemigrations_non_interactive_not_null_addition(self):
  598. """
  599. Tests that non-interactive makemigrations fails when a default is missing on a new not-null field.
  600. """
  601. class SillyModel(models.Model):
  602. silly_field = models.BooleanField(default=False)
  603. silly_int = models.IntegerField()
  604. class Meta:
  605. app_label = "migrations"
  606. out = six.StringIO()
  607. with self.assertRaises(SystemExit):
  608. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  609. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  610. def test_makemigrations_non_interactive_not_null_alteration(self):
  611. """
  612. Tests that non-interactive makemigrations fails when a default is missing on a field changed to not-null.
  613. """
  614. class Author(models.Model):
  615. name = models.CharField(max_length=255)
  616. slug = models.SlugField()
  617. age = models.IntegerField(default=0)
  618. class Meta:
  619. app_label = "migrations"
  620. out = six.StringIO()
  621. try:
  622. with self.temporary_migration_module(module="migrations.test_migrations"):
  623. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  624. except CommandError:
  625. self.fail("Makemigrations failed while running non-interactive questioner.")
  626. self.assertIn("Alter field slug on author", force_text(out.getvalue()))
  627. def test_makemigrations_non_interactive_no_model_rename(self):
  628. """
  629. Makes sure that makemigrations adds and removes a possible model rename in non-interactive mode.
  630. """
  631. class RenamedModel(models.Model):
  632. silly_field = models.BooleanField(default=False)
  633. class Meta:
  634. app_label = "migrations"
  635. out = six.StringIO()
  636. try:
  637. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  638. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  639. except CommandError:
  640. self.fail("Makemigrations failed while running non-interactive questioner")
  641. self.assertIn("Delete model SillyModel", force_text(out.getvalue()))
  642. self.assertIn("Create model RenamedModel", force_text(out.getvalue()))
  643. def test_makemigrations_non_interactive_no_field_rename(self):
  644. """
  645. Makes sure that makemigrations adds and removes a possible field rename in non-interactive mode.
  646. """
  647. class SillyModel(models.Model):
  648. silly_rename = models.BooleanField(default=False)
  649. class Meta:
  650. app_label = "migrations"
  651. out = six.StringIO()
  652. try:
  653. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  654. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  655. except CommandError:
  656. self.fail("Makemigrations failed while running non-interactive questioner")
  657. self.assertIn("Remove field silly_field from sillymodel", force_text(out.getvalue()))
  658. self.assertIn("Add field silly_rename to sillymodel", force_text(out.getvalue()))
  659. def test_makemigrations_handle_merge(self):
  660. """
  661. Makes sure that makemigrations properly merges the conflicting migrations with --noinput.
  662. """
  663. out = six.StringIO()
  664. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  665. call_command("makemigrations", "migrations", merge=True, interactive=False, stdout=out)
  666. merge_file = os.path.join(migration_dir, '0003_merge.py')
  667. self.assertTrue(os.path.exists(merge_file))
  668. output = force_text(out.getvalue())
  669. self.assertIn("Merging migrations", output)
  670. self.assertIn("Branch 0002_second", output)
  671. self.assertIn("Branch 0002_conflicting_second", output)
  672. self.assertIn("Created new merge migration", output)
  673. def test_makemigration_merge_dry_run(self):
  674. """
  675. Makes sure that makemigrations respects --dry-run option when fixing
  676. migration conflicts (#24427).
  677. """
  678. out = six.StringIO()
  679. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  680. call_command("makemigrations", "migrations", dry_run=True, merge=True, interactive=False, stdout=out)
  681. merge_file = os.path.join(migration_dir, '0003_merge.py')
  682. self.assertFalse(os.path.exists(merge_file))
  683. output = force_text(out.getvalue())
  684. self.assertIn("Merging migrations", output)
  685. self.assertIn("Branch 0002_second", output)
  686. self.assertIn("Branch 0002_conflicting_second", output)
  687. self.assertNotIn("Created new merge migration", output)
  688. def test_makemigration_merge_dry_run_verbosity_3(self):
  689. """
  690. Makes sure that `makemigrations --merge --dry-run` writes the merge
  691. migration file to stdout with `verbosity == 3` (#24427).
  692. """
  693. out = six.StringIO()
  694. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  695. call_command("makemigrations", "migrations", dry_run=True, merge=True, interactive=False,
  696. stdout=out, verbosity=3)
  697. merge_file = os.path.join(migration_dir, '0003_merge.py')
  698. self.assertFalse(os.path.exists(merge_file))
  699. output = force_text(out.getvalue())
  700. self.assertIn("Merging migrations", output)
  701. self.assertIn("Branch 0002_second", output)
  702. self.assertIn("Branch 0002_conflicting_second", output)
  703. self.assertNotIn("Created new merge migration", output)
  704. # Additional output caused by verbosity 3
  705. # The complete merge migration file that would be written
  706. self.assertIn("# -*- coding: utf-8 -*-", output)
  707. self.assertIn("class Migration(migrations.Migration):", output)
  708. self.assertIn("dependencies = [", output)
  709. self.assertIn("('migrations', '0002_second')", output)
  710. self.assertIn("('migrations', '0002_conflicting_second')", output)
  711. self.assertIn("operations = [", output)
  712. self.assertIn("]", output)
  713. def test_makemigrations_dry_run(self):
  714. """
  715. Ticket #22676 -- `makemigrations --dry-run` should not ask for defaults.
  716. """
  717. class SillyModel(models.Model):
  718. silly_field = models.BooleanField(default=False)
  719. silly_date = models.DateField() # Added field without a default
  720. class Meta:
  721. app_label = "migrations"
  722. out = six.StringIO()
  723. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  724. call_command("makemigrations", "migrations", dry_run=True, stdout=out)
  725. # Output the expected changes directly, without asking for defaults
  726. self.assertIn("Add field silly_date to sillymodel", out.getvalue())
  727. def test_makemigrations_dry_run_verbosity_3(self):
  728. """
  729. Ticket #22675 -- Allow `makemigrations --dry-run` to output the
  730. migrations file to stdout (with verbosity == 3).
  731. """
  732. class SillyModel(models.Model):
  733. silly_field = models.BooleanField(default=False)
  734. silly_char = models.CharField(default="")
  735. class Meta:
  736. app_label = "migrations"
  737. out = six.StringIO()
  738. with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
  739. call_command("makemigrations", "migrations", dry_run=True, stdout=out, verbosity=3)
  740. # Normal --dry-run output
  741. self.assertIn("- Add field silly_char to sillymodel", out.getvalue())
  742. # Additional output caused by verbosity 3
  743. # The complete migrations file that would be written
  744. self.assertIn("# -*- coding: utf-8 -*-", out.getvalue())
  745. self.assertIn("class Migration(migrations.Migration):", out.getvalue())
  746. self.assertIn("dependencies = [", out.getvalue())
  747. self.assertIn("('migrations', '0001_initial'),", out.getvalue())
  748. self.assertIn("migrations.AddField(", out.getvalue())
  749. self.assertIn("model_name='sillymodel',", out.getvalue())
  750. self.assertIn("name='silly_char',", out.getvalue())
  751. def test_makemigrations_migrations_modules_path_not_exist(self):
  752. """
  753. Ticket #22682 -- Makemigrations fails when specifying custom location
  754. for migration files (using MIGRATION_MODULES) if the custom path
  755. doesn't already exist.
  756. """
  757. class SillyModel(models.Model):
  758. silly_field = models.BooleanField(default=False)
  759. class Meta:
  760. app_label = "migrations"
  761. out = six.StringIO()
  762. migration_module = "migrations.test_migrations_path_doesnt_exist.foo.bar"
  763. with self.temporary_migration_module(module=migration_module) as migration_dir:
  764. call_command("makemigrations", "migrations", stdout=out)
  765. # Migrations file is actually created in the expected path.
  766. initial_file = os.path.join(migration_dir, "0001_initial.py")
  767. self.assertTrue(os.path.exists(initial_file))
  768. # Command output indicates the migration is created.
  769. self.assertIn(" - Create model SillyModel", out.getvalue())
  770. def test_makemigrations_interactive_by_default(self):
  771. """
  772. Makes sure that the user is prompted to merge by default if there are
  773. conflicts and merge is True. Answer negative to differentiate it from
  774. behavior when --noinput is specified.
  775. """
  776. # Monkeypatch interactive questioner to auto reject
  777. out = six.StringIO()
  778. with mock.patch('django.db.migrations.questioner.input', mock.Mock(return_value='N')):
  779. try:
  780. with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
  781. call_command("makemigrations", "migrations", merge=True, stdout=out)
  782. merge_file = os.path.join(migration_dir, '0003_merge.py')
  783. # This will fail if interactive is False by default
  784. self.assertFalse(os.path.exists(merge_file))
  785. except CommandError:
  786. self.fail("Makemigrations failed while running interactive questioner")
  787. self.assertNotIn("Created new merge migration", out.getvalue())
  788. @override_settings(
  789. INSTALLED_APPS=[
  790. "migrations",
  791. "migrations.migrations_test_apps.unspecified_app_with_conflict"])
  792. def test_makemigrations_unspecified_app_with_conflict_no_merge(self):
  793. """
  794. Makes sure that makemigrations does not raise a CommandError when an
  795. unspecified app has conflicting migrations.
  796. """
  797. try:
  798. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  799. call_command("makemigrations", "migrations", merge=False, verbosity=0)
  800. except CommandError:
  801. self.fail("Makemigrations fails resolving conflicts in an unspecified app")
  802. @override_settings(
  803. INSTALLED_APPS=[
  804. "migrations.migrations_test_apps.migrated_app",
  805. "migrations.migrations_test_apps.unspecified_app_with_conflict"])
  806. def test_makemigrations_unspecified_app_with_conflict_merge(self):
  807. """
  808. Makes sure that makemigrations does not create a merge for an
  809. unspecified app even if it has conflicting migrations.
  810. """
  811. # Monkeypatch interactive questioner to auto accept
  812. with mock.patch('django.db.migrations.questioner.input', mock.Mock(return_value='y')):
  813. out = six.StringIO()
  814. try:
  815. with self.temporary_migration_module(app_label="migrated_app") as migration_dir:
  816. call_command("makemigrations", "migrated_app", merge=True, interactive=True, stdout=out)
  817. merge_file = os.path.join(migration_dir, '0003_merge.py')
  818. self.assertFalse(os.path.exists(merge_file))
  819. self.assertIn("No conflicts detected to merge.", out.getvalue())
  820. except CommandError:
  821. self.fail("Makemigrations fails resolving conflicts in an unspecified app")
  822. @override_settings(
  823. INSTALLED_APPS=[
  824. "migrations.migrations_test_apps.migrated_app",
  825. "migrations.migrations_test_apps.conflicting_app_with_dependencies"])
  826. def test_makemigrations_merge_dont_output_dependency_operations(self):
  827. """
  828. Makes sure that makemigrations --merge does not output any operations
  829. from apps that don't belong to a given app.
  830. """
  831. # Monkeypatch interactive questioner to auto accept
  832. with mock.patch('django.db.migrations.questioner.input', mock.Mock(return_value='N')):
  833. out = six.StringIO()
  834. with mock.patch('django.core.management.color.supports_color', lambda *args: False):
  835. call_command(
  836. "makemigrations", "conflicting_app_with_dependencies",
  837. merge=True, interactive=True, stdout=out
  838. )
  839. val = out.getvalue().lower()
  840. self.assertIn('merging conflicting_app_with_dependencies\n', val)
  841. self.assertIn(
  842. ' branch 0002_conflicting_second\n'
  843. ' - create model something\n',
  844. val
  845. )
  846. self.assertIn(
  847. ' branch 0002_second\n'
  848. ' - delete model tribble\n'
  849. ' - remove field silly_field from author\n'
  850. ' - add field rating to author\n'
  851. ' - create model book\n',
  852. val
  853. )
  854. def test_makemigrations_with_custom_name(self):
  855. """
  856. Makes sure that makemigrations generate a custom migration.
  857. """
  858. with self.temporary_migration_module() as migration_dir:
  859. def cmd(migration_count, migration_name, *args):
  860. try:
  861. call_command("makemigrations", "migrations", "--verbosity", "0", "--name", migration_name, *args)
  862. except CommandError:
  863. self.fail("Makemigrations errored in creating empty migration with custom name for a proper app.")
  864. migration_file = os.path.join(migration_dir, "%s_%s.py" % (migration_count, migration_name))
  865. # Check for existing migration file in migration folder
  866. self.assertTrue(os.path.exists(migration_file))
  867. with codecs.open(migration_file, "r", encoding="utf-8") as fp:
  868. content = fp.read()
  869. self.assertIn("# -*- coding: utf-8 -*-", content)
  870. content = content.replace(" ", "")
  871. return content
  872. # generate an initial migration
  873. migration_name_0001 = "my_initial_migration"
  874. content = cmd("0001", migration_name_0001)
  875. self.assertIn("dependencies=[\n]", content)
  876. # Python 3 importlib caches os.listdir() on some platforms like
  877. # Mac OS X (#23850).
  878. if hasattr(importlib, 'invalidate_caches'):
  879. importlib.invalidate_caches()
  880. # generate an empty migration
  881. migration_name_0002 = "my_custom_migration"
  882. content = cmd("0002", migration_name_0002, "--empty")
  883. self.assertIn("dependencies=[\n('migrations','0001_%s'),\n]" % migration_name_0001, content)
  884. self.assertIn("operations=[\n]", content)
  885. @ignore_warnings(category=RemovedInDjango20Warning)
  886. def test_makemigrations_exit(self):
  887. """
  888. makemigrations --exit should exit with sys.exit(1) when there are no
  889. changes to an app.
  890. """
  891. with self.temporary_migration_module():
  892. call_command("makemigrations", "--exit", "migrations", verbosity=0)
  893. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  894. with self.assertRaises(SystemExit):
  895. call_command("makemigrations", "--exit", "migrations", verbosity=0)
  896. def test_makemigrations_check(self):
  897. """
  898. makemigrations --check should exit with a non-zero status when
  899. there are changes to an app requiring migrations.
  900. """
  901. with self.temporary_migration_module():
  902. with self.assertRaises(SystemExit):
  903. call_command("makemigrations", "--check", "migrations", verbosity=0)
  904. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  905. call_command("makemigrations", "--check", "migrations", verbosity=0)
  906. def test_makemigrations_migration_path_output(self):
  907. """
  908. makemigrations should print the relative paths to the migrations unless
  909. they are outside of the current tree, in which case the absolute path
  910. should be shown.
  911. """
  912. out = six.StringIO()
  913. apps.register_model('migrations', UnicodeModel)
  914. with self.temporary_migration_module() as migration_dir:
  915. call_command("makemigrations", "migrations", stdout=out)
  916. self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
  917. class SquashMigrationsTests(MigrationTestBase):
  918. """
  919. Tests running the squashmigrations command.
  920. """
  921. def test_squashmigrations_squashes(self):
  922. """
  923. Tests that squashmigrations squashes migrations.
  924. """
  925. with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
  926. call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
  927. squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
  928. self.assertTrue(os.path.exists(squashed_migration_file))
  929. def test_squashmigrations_initial_attribute(self):
  930. with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
  931. call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
  932. squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
  933. with codecs.open(squashed_migration_file, "r", encoding="utf-8") as fp:
  934. content = fp.read()
  935. self.assertIn("initial = True", content)
  936. def test_squashmigrations_optimizes(self):
  937. """
  938. Tests that squashmigrations optimizes operations.
  939. """
  940. out = six.StringIO()
  941. with self.temporary_migration_module(module="migrations.test_migrations"):
  942. call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=1, stdout=out)
  943. self.assertIn("Optimized from 7 operations to 3 operations.", force_text(out.getvalue()))
  944. def test_ticket_23799_squashmigrations_no_optimize(self):
  945. """
  946. Makes sure that squashmigrations --no-optimize really doesn't optimize operations.
  947. """
  948. out = six.StringIO()
  949. with self.temporary_migration_module(module="migrations.test_migrations"):
  950. call_command("squashmigrations", "migrations", "0002",
  951. interactive=False, verbosity=1, no_optimize=True, stdout=out)
  952. self.assertIn("Skipping optimization", force_text(out.getvalue()))
  953. def test_squashmigrations_valid_start(self):
  954. """
  955. squashmigrations accepts a starting migration.
  956. """
  957. out = six.StringIO()
  958. with self.temporary_migration_module(module="migrations.test_migrations_no_changes") as migration_dir:
  959. call_command("squashmigrations", "migrations", "0002", "0003",
  960. interactive=False, verbosity=1, stdout=out)
  961. squashed_migration_file = os.path.join(migration_dir, "0002_second_squashed_0003_third.py")
  962. with codecs.open(squashed_migration_file, "r", encoding="utf-8") as fp:
  963. content = fp.read()
  964. self.assertIn(" ('migrations', '0001_initial')", content)
  965. self.assertNotIn("initial = True", content)
  966. out = force_text(out.getvalue())
  967. self.assertNotIn(" - 0001_initial", out)
  968. self.assertIn(" - 0002_second", out)
  969. self.assertIn(" - 0003_third", out)
  970. def test_squashmigrations_invalid_start(self):
  971. """
  972. squashmigrations doesn't accept a starting migration after the ending migration.
  973. """
  974. with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
  975. msg = (
  976. "The migration 'migrations.0003_third' cannot be found. Maybe "
  977. "it comes after the migration 'migrations.0002_second'"
  978. )
  979. with self.assertRaisesMessage(CommandError, msg):
  980. call_command("squashmigrations", "migrations", "0003", "0002", interactive=False, verbosity=0)