test_commands.py 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616
  1. import datetime
  2. import importlib
  3. import io
  4. import os
  5. import re
  6. import shutil
  7. import sys
  8. from pathlib import Path
  9. from unittest import mock
  10. from django.apps import apps
  11. from django.core.checks import Error, Tags, register
  12. from django.core.checks.registry import registry
  13. from django.core.management import CommandError, call_command
  14. from django.core.management.base import SystemCheckError
  15. from django.core.management.commands.makemigrations import (
  16. Command as MakeMigrationsCommand,
  17. )
  18. from django.core.management.commands.migrate import Command as MigrateCommand
  19. from django.db import (
  20. ConnectionHandler,
  21. DatabaseError,
  22. OperationalError,
  23. connection,
  24. connections,
  25. models,
  26. )
  27. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  28. from django.db.backends.utils import truncate_name
  29. from django.db.migrations.autodetector import MigrationAutodetector
  30. from django.db.migrations.exceptions import InconsistentMigrationHistory
  31. from django.db.migrations.loader import MigrationLoader
  32. from django.db.migrations.recorder import MigrationRecorder
  33. from django.db.migrations.writer import MigrationWriter
  34. from django.test import TestCase, override_settings, skipUnlessDBFeature
  35. from django.test.utils import captured_stdout, extend_sys_path, isolate_apps
  36. from django.utils import timezone
  37. from django.utils.version import get_docs_version
  38. from .models import UnicodeModel, UnserializableModel
  39. from .routers import TestRouter
  40. from .test_base import MigrationTestBase
  41. HAS_BLACK = shutil.which("black")
  42. class MigrateTests(MigrationTestBase):
  43. """
  44. Tests running the migrate command.
  45. """
  46. databases = {"default", "other"}
  47. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  48. def test_migrate(self):
  49. """
  50. Tests basic usage of the migrate command.
  51. """
  52. # No tables are created
  53. self.assertTableNotExists("migrations_author")
  54. self.assertTableNotExists("migrations_tribble")
  55. self.assertTableNotExists("migrations_book")
  56. # Run the migrations to 0001 only
  57. stdout = io.StringIO()
  58. call_command(
  59. "migrate", "migrations", "0001", verbosity=2, stdout=stdout, no_color=True
  60. )
  61. stdout = stdout.getvalue()
  62. self.assertIn(
  63. "Target specific migration: 0001_initial, from migrations", stdout
  64. )
  65. self.assertIn("Applying migrations.0001_initial... OK", stdout)
  66. self.assertIn("Running pre-migrate handlers for application migrations", stdout)
  67. self.assertIn(
  68. "Running post-migrate handlers for application migrations", stdout
  69. )
  70. # The correct tables exist
  71. self.assertTableExists("migrations_author")
  72. self.assertTableExists("migrations_tribble")
  73. self.assertTableNotExists("migrations_book")
  74. # Run migrations all the way
  75. call_command("migrate", verbosity=0)
  76. # The correct tables exist
  77. self.assertTableExists("migrations_author")
  78. self.assertTableNotExists("migrations_tribble")
  79. self.assertTableExists("migrations_book")
  80. # Unmigrate everything
  81. stdout = io.StringIO()
  82. call_command(
  83. "migrate", "migrations", "zero", verbosity=2, stdout=stdout, no_color=True
  84. )
  85. stdout = stdout.getvalue()
  86. self.assertIn("Unapply all migrations: migrations", stdout)
  87. self.assertIn("Unapplying migrations.0002_second... OK", stdout)
  88. self.assertIn("Running pre-migrate handlers for application migrations", stdout)
  89. self.assertIn(
  90. "Running post-migrate handlers for application migrations", stdout
  91. )
  92. # Tables are gone
  93. self.assertTableNotExists("migrations_author")
  94. self.assertTableNotExists("migrations_tribble")
  95. self.assertTableNotExists("migrations_book")
  96. @mock.patch("django.core.management.base.BaseCommand.check")
  97. @override_settings(
  98. INSTALLED_APPS=[
  99. "django.contrib.auth",
  100. "django.contrib.contenttypes",
  101. "migrations.migrations_test_apps.migrated_app",
  102. ]
  103. )
  104. def test_migrate_with_system_checks(self, mocked_check):
  105. out = io.StringIO()
  106. call_command("migrate", skip_checks=False, no_color=True, stdout=out)
  107. self.assertIn("Apply all migrations: migrated_app", out.getvalue())
  108. mocked_check.assert_called_once()
  109. def test_migrate_with_custom_system_checks(self):
  110. original_checks = registry.registered_checks.copy()
  111. @register(Tags.signals)
  112. def my_check(app_configs, **kwargs):
  113. return [Error("my error")]
  114. self.addCleanup(setattr, registry, "registered_checks", original_checks)
  115. class CustomMigrateCommandWithSignalsChecks(MigrateCommand):
  116. requires_system_checks = [Tags.signals]
  117. command = CustomMigrateCommandWithSignalsChecks()
  118. with self.assertRaises(SystemCheckError):
  119. call_command(command, skip_checks=False, stderr=io.StringIO())
  120. class CustomMigrateCommandWithSecurityChecks(MigrateCommand):
  121. requires_system_checks = [Tags.security]
  122. command = CustomMigrateCommandWithSecurityChecks()
  123. call_command(command, skip_checks=False, stdout=io.StringIO())
  124. @override_settings(
  125. INSTALLED_APPS=[
  126. "migrations",
  127. "migrations.migrations_test_apps.unmigrated_app_syncdb",
  128. ]
  129. )
  130. def test_app_without_migrations(self):
  131. msg = "App 'unmigrated_app_syncdb' does not have migrations."
  132. with self.assertRaisesMessage(CommandError, msg):
  133. call_command("migrate", app_label="unmigrated_app_syncdb")
  134. @override_settings(
  135. MIGRATION_MODULES={"migrations": "migrations.test_migrations_clashing_prefix"}
  136. )
  137. def test_ambiguous_prefix(self):
  138. msg = (
  139. "More than one migration matches 'a' in app 'migrations'. Please "
  140. "be more specific."
  141. )
  142. with self.assertRaisesMessage(CommandError, msg):
  143. call_command("migrate", app_label="migrations", migration_name="a")
  144. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  145. def test_unknown_prefix(self):
  146. msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'."
  147. with self.assertRaisesMessage(CommandError, msg):
  148. call_command(
  149. "migrate", app_label="migrations", migration_name="nonexistent"
  150. )
  151. @override_settings(
  152. MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"}
  153. )
  154. def test_migrate_initial_false(self):
  155. """
  156. `Migration.initial = False` skips fake-initial detection.
  157. """
  158. # Make sure no tables are created
  159. self.assertTableNotExists("migrations_author")
  160. self.assertTableNotExists("migrations_tribble")
  161. # Run the migrations to 0001 only
  162. call_command("migrate", "migrations", "0001", verbosity=0)
  163. # Fake rollback
  164. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  165. # Make sure fake-initial detection does not run
  166. with self.assertRaises(DatabaseError):
  167. call_command(
  168. "migrate", "migrations", "0001", fake_initial=True, verbosity=0
  169. )
  170. call_command("migrate", "migrations", "0001", fake=True, verbosity=0)
  171. # Real rollback
  172. call_command("migrate", "migrations", "zero", verbosity=0)
  173. # Make sure it's all gone
  174. self.assertTableNotExists("migrations_author")
  175. self.assertTableNotExists("migrations_tribble")
  176. self.assertTableNotExists("migrations_book")
  177. @override_settings(
  178. MIGRATION_MODULES={"migrations": "migrations.test_migrations"},
  179. DATABASE_ROUTERS=["migrations.routers.TestRouter"],
  180. )
  181. def test_migrate_fake_initial(self):
  182. """
  183. --fake-initial only works if all tables created in the initial
  184. migration of an app exists. Database routers must be obeyed when doing
  185. that check.
  186. """
  187. # Make sure no tables are created
  188. for db in self.databases:
  189. self.assertTableNotExists("migrations_author", using=db)
  190. self.assertTableNotExists("migrations_tribble", using=db)
  191. try:
  192. # Run the migrations to 0001 only
  193. call_command("migrate", "migrations", "0001", verbosity=0)
  194. call_command("migrate", "migrations", "0001", verbosity=0, database="other")
  195. # Make sure the right tables exist
  196. self.assertTableExists("migrations_author")
  197. self.assertTableNotExists("migrations_tribble")
  198. # Also check the "other" database
  199. self.assertTableNotExists("migrations_author", using="other")
  200. self.assertTableExists("migrations_tribble", using="other")
  201. # Fake a roll-back
  202. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  203. call_command(
  204. "migrate",
  205. "migrations",
  206. "zero",
  207. fake=True,
  208. verbosity=0,
  209. database="other",
  210. )
  211. # Make sure the tables still exist
  212. self.assertTableExists("migrations_author")
  213. self.assertTableExists("migrations_tribble", using="other")
  214. # Try to run initial migration
  215. with self.assertRaises(DatabaseError):
  216. call_command("migrate", "migrations", "0001", verbosity=0)
  217. # Run initial migration with an explicit --fake-initial
  218. out = io.StringIO()
  219. with mock.patch(
  220. "django.core.management.color.supports_color", lambda *args: False
  221. ):
  222. call_command(
  223. "migrate",
  224. "migrations",
  225. "0001",
  226. fake_initial=True,
  227. stdout=out,
  228. verbosity=1,
  229. )
  230. call_command(
  231. "migrate",
  232. "migrations",
  233. "0001",
  234. fake_initial=True,
  235. verbosity=0,
  236. database="other",
  237. )
  238. self.assertIn("migrations.0001_initial... faked", out.getvalue().lower())
  239. # Run migrations all the way.
  240. call_command("migrate", verbosity=0)
  241. call_command("migrate", verbosity=0, database="other")
  242. self.assertTableExists("migrations_author")
  243. self.assertTableNotExists("migrations_tribble")
  244. self.assertTableExists("migrations_book")
  245. self.assertTableNotExists("migrations_author", using="other")
  246. self.assertTableNotExists("migrations_tribble", using="other")
  247. self.assertTableNotExists("migrations_book", using="other")
  248. # Fake a roll-back.
  249. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  250. call_command(
  251. "migrate",
  252. "migrations",
  253. "zero",
  254. fake=True,
  255. verbosity=0,
  256. database="other",
  257. )
  258. self.assertTableExists("migrations_author")
  259. self.assertTableNotExists("migrations_tribble")
  260. self.assertTableExists("migrations_book")
  261. # Run initial migration.
  262. with self.assertRaises(DatabaseError):
  263. call_command("migrate", "migrations", verbosity=0)
  264. # Run initial migration with an explicit --fake-initial.
  265. with self.assertRaises(DatabaseError):
  266. # Fails because "migrations_tribble" does not exist but needs
  267. # to in order to make --fake-initial work.
  268. call_command("migrate", "migrations", fake_initial=True, verbosity=0)
  269. # Fake an apply.
  270. call_command("migrate", "migrations", fake=True, verbosity=0)
  271. call_command(
  272. "migrate", "migrations", fake=True, verbosity=0, database="other"
  273. )
  274. finally:
  275. # Unmigrate everything.
  276. call_command("migrate", "migrations", "zero", verbosity=0)
  277. call_command("migrate", "migrations", "zero", verbosity=0, database="other")
  278. # Make sure it's all gone
  279. for db in self.databases:
  280. self.assertTableNotExists("migrations_author", using=db)
  281. self.assertTableNotExists("migrations_tribble", using=db)
  282. self.assertTableNotExists("migrations_book", using=db)
  283. @skipUnlessDBFeature("ignores_table_name_case")
  284. def test_migrate_fake_initial_case_insensitive(self):
  285. with override_settings(
  286. MIGRATION_MODULES={
  287. "migrations": "migrations.test_fake_initial_case_insensitive.initial",
  288. }
  289. ):
  290. call_command("migrate", "migrations", "0001", verbosity=0)
  291. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  292. with override_settings(
  293. MIGRATION_MODULES={
  294. "migrations": (
  295. "migrations.test_fake_initial_case_insensitive.fake_initial"
  296. ),
  297. }
  298. ):
  299. out = io.StringIO()
  300. call_command(
  301. "migrate",
  302. "migrations",
  303. "0001",
  304. fake_initial=True,
  305. stdout=out,
  306. verbosity=1,
  307. no_color=True,
  308. )
  309. self.assertIn(
  310. "migrations.0001_initial... faked",
  311. out.getvalue().lower(),
  312. )
  313. @override_settings(
  314. MIGRATION_MODULES={
  315. "migrations": "migrations.test_migrations_fake_split_initial"
  316. }
  317. )
  318. def test_migrate_fake_split_initial(self):
  319. """
  320. Split initial migrations can be faked with --fake-initial.
  321. """
  322. try:
  323. call_command("migrate", "migrations", "0002", verbosity=0)
  324. call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
  325. out = io.StringIO()
  326. with mock.patch(
  327. "django.core.management.color.supports_color", lambda *args: False
  328. ):
  329. call_command(
  330. "migrate",
  331. "migrations",
  332. "0002",
  333. fake_initial=True,
  334. stdout=out,
  335. verbosity=1,
  336. )
  337. value = out.getvalue().lower()
  338. self.assertIn("migrations.0001_initial... faked", value)
  339. self.assertIn("migrations.0002_second... faked", value)
  340. finally:
  341. # Fake an apply.
  342. call_command("migrate", "migrations", fake=True, verbosity=0)
  343. # Unmigrate everything.
  344. call_command("migrate", "migrations", "zero", verbosity=0)
  345. @override_settings(
  346. MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"}
  347. )
  348. def test_migrate_conflict_exit(self):
  349. """
  350. migrate exits if it detects a conflict.
  351. """
  352. msg = (
  353. "Conflicting migrations detected; multiple leaf nodes in the "
  354. "migration graph: (0002_conflicting_second, 0002_second in "
  355. "migrations).\n"
  356. "To fix them run 'python manage.py makemigrations --merge'"
  357. )
  358. with self.assertRaisesMessage(CommandError, msg):
  359. call_command("migrate", "migrations")
  360. @override_settings(
  361. MIGRATION_MODULES={
  362. "migrations": "migrations.test_migrations",
  363. }
  364. )
  365. def test_migrate_check(self):
  366. with self.assertRaises(SystemExit):
  367. call_command("migrate", "migrations", "0001", check_unapplied=True)
  368. self.assertTableNotExists("migrations_author")
  369. self.assertTableNotExists("migrations_tribble")
  370. self.assertTableNotExists("migrations_book")
  371. @override_settings(
  372. INSTALLED_APPS=[
  373. "migrations.migrations_test_apps.migrated_app",
  374. ]
  375. )
  376. def test_migrate_check_migrated_app(self):
  377. out = io.StringIO()
  378. try:
  379. call_command("migrate", "migrated_app", verbosity=0)
  380. call_command(
  381. "migrate",
  382. "migrated_app",
  383. stdout=out,
  384. check_unapplied=True,
  385. )
  386. self.assertEqual(out.getvalue(), "")
  387. finally:
  388. # Unmigrate everything.
  389. call_command("migrate", "migrated_app", "zero", verbosity=0)
  390. @override_settings(
  391. MIGRATION_MODULES={
  392. "migrations": "migrations.test_migrations_plan",
  393. }
  394. )
  395. def test_migrate_check_plan(self):
  396. out = io.StringIO()
  397. with self.assertRaises(SystemExit):
  398. call_command(
  399. "migrate",
  400. "migrations",
  401. "0001",
  402. check_unapplied=True,
  403. plan=True,
  404. stdout=out,
  405. no_color=True,
  406. )
  407. self.assertEqual(
  408. "Planned operations:\n"
  409. "migrations.0001_initial\n"
  410. " Create model Salamander\n"
  411. " Raw Python operation -> Grow salamander tail.\n",
  412. out.getvalue(),
  413. )
  414. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  415. def test_showmigrations_list(self):
  416. """
  417. showmigrations --list displays migrations and whether or not they're
  418. applied.
  419. """
  420. out = io.StringIO()
  421. with mock.patch(
  422. "django.core.management.color.supports_color", lambda *args: True
  423. ):
  424. call_command(
  425. "showmigrations", format="list", stdout=out, verbosity=0, no_color=False
  426. )
  427. self.assertEqual(
  428. "\x1b[1mmigrations\n\x1b[0m [ ] 0001_initial\n [ ] 0002_second\n",
  429. out.getvalue().lower(),
  430. )
  431. call_command("migrate", "migrations", "0001", verbosity=0)
  432. out = io.StringIO()
  433. # Giving the explicit app_label tests for selective `show_list` in the command
  434. call_command(
  435. "showmigrations",
  436. "migrations",
  437. format="list",
  438. stdout=out,
  439. verbosity=0,
  440. no_color=True,
  441. )
  442. self.assertEqual(
  443. "migrations\n [x] 0001_initial\n [ ] 0002_second\n", out.getvalue().lower()
  444. )
  445. out = io.StringIO()
  446. # Applied datetimes are displayed at verbosity 2+.
  447. call_command(
  448. "showmigrations", "migrations", stdout=out, verbosity=2, no_color=True
  449. )
  450. migration1 = MigrationRecorder(connection).migration_qs.get(
  451. app="migrations", name="0001_initial"
  452. )
  453. self.assertEqual(
  454. "migrations\n"
  455. " [x] 0001_initial (applied at %s)\n"
  456. " [ ] 0002_second\n" % migration1.applied.strftime("%Y-%m-%d %H:%M:%S"),
  457. out.getvalue().lower(),
  458. )
  459. # Cleanup by unmigrating everything
  460. call_command("migrate", "migrations", "zero", verbosity=0)
  461. @override_settings(
  462. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  463. )
  464. def test_showmigrations_list_squashed(self):
  465. out = io.StringIO()
  466. call_command(
  467. "showmigrations", format="list", stdout=out, verbosity=2, no_color=True
  468. )
  469. self.assertEqual(
  470. "migrations\n [ ] 0001_squashed_0002 (2 squashed migrations)\n",
  471. out.getvalue().lower(),
  472. )
  473. out = io.StringIO()
  474. call_command(
  475. "migrate",
  476. "migrations",
  477. "0001_squashed_0002",
  478. stdout=out,
  479. verbosity=2,
  480. no_color=True,
  481. )
  482. try:
  483. self.assertIn(
  484. "operations to perform:\n"
  485. " target specific migration: 0001_squashed_0002, from migrations\n"
  486. "running pre-migrate handlers for application migrations\n"
  487. "running migrations:\n"
  488. " applying migrations.0001_squashed_0002... ok (",
  489. out.getvalue().lower(),
  490. )
  491. out = io.StringIO()
  492. call_command(
  493. "showmigrations", format="list", stdout=out, verbosity=2, no_color=True
  494. )
  495. self.assertEqual(
  496. "migrations\n [x] 0001_squashed_0002 (2 squashed migrations)\n",
  497. out.getvalue().lower(),
  498. )
  499. finally:
  500. # Unmigrate everything.
  501. call_command("migrate", "migrations", "zero", verbosity=0)
  502. @override_settings(
  503. MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"}
  504. )
  505. def test_showmigrations_plan(self):
  506. """
  507. Tests --plan output of showmigrations command
  508. """
  509. out = io.StringIO()
  510. call_command("showmigrations", format="plan", stdout=out)
  511. self.assertEqual(
  512. "[ ] migrations.0001_initial\n"
  513. "[ ] migrations.0003_third\n"
  514. "[ ] migrations.0002_second\n",
  515. out.getvalue().lower(),
  516. )
  517. out = io.StringIO()
  518. call_command("showmigrations", format="plan", stdout=out, verbosity=2)
  519. self.assertEqual(
  520. "[ ] migrations.0001_initial\n"
  521. "[ ] migrations.0003_third ... (migrations.0001_initial)\n"
  522. "[ ] migrations.0002_second ... (migrations.0001_initial, "
  523. "migrations.0003_third)\n",
  524. out.getvalue().lower(),
  525. )
  526. call_command("migrate", "migrations", "0003", verbosity=0)
  527. out = io.StringIO()
  528. call_command("showmigrations", format="plan", stdout=out)
  529. self.assertEqual(
  530. "[x] migrations.0001_initial\n"
  531. "[x] migrations.0003_third\n"
  532. "[ ] migrations.0002_second\n",
  533. out.getvalue().lower(),
  534. )
  535. out = io.StringIO()
  536. call_command("showmigrations", format="plan", stdout=out, verbosity=2)
  537. self.assertEqual(
  538. "[x] migrations.0001_initial\n"
  539. "[x] migrations.0003_third ... (migrations.0001_initial)\n"
  540. "[ ] migrations.0002_second ... (migrations.0001_initial, "
  541. "migrations.0003_third)\n",
  542. out.getvalue().lower(),
  543. )
  544. # Cleanup by unmigrating everything
  545. call_command("migrate", "migrations", "zero", verbosity=0)
  546. @override_settings(
  547. MIGRATION_MODULES={"migrations": "migrations.test_migrations_plan"}
  548. )
  549. def test_migrate_plan(self):
  550. """Tests migrate --plan output."""
  551. out = io.StringIO()
  552. # Show the plan up to the third migration.
  553. call_command(
  554. "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True
  555. )
  556. self.assertEqual(
  557. "Planned operations:\n"
  558. "migrations.0001_initial\n"
  559. " Create model Salamander\n"
  560. " Raw Python operation -> Grow salamander tail.\n"
  561. "migrations.0002_second\n"
  562. " Create model Book\n"
  563. " Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
  564. "migrations.0003_third\n"
  565. " Create model Author\n"
  566. " Raw SQL operation -> ['SELECT * FROM migrations_author']\n",
  567. out.getvalue(),
  568. )
  569. try:
  570. # Migrate to the third migration.
  571. call_command("migrate", "migrations", "0003", verbosity=0)
  572. out = io.StringIO()
  573. # Show the plan for when there is nothing to apply.
  574. call_command(
  575. "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True
  576. )
  577. self.assertEqual(
  578. "Planned operations:\n No planned migration operations.\n",
  579. out.getvalue(),
  580. )
  581. out = io.StringIO()
  582. # Show the plan for reverse migration back to 0001.
  583. call_command(
  584. "migrate", "migrations", "0001", plan=True, stdout=out, no_color=True
  585. )
  586. self.assertEqual(
  587. "Planned operations:\n"
  588. "migrations.0003_third\n"
  589. " Undo Create model Author\n"
  590. " Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
  591. "migrations.0002_second\n"
  592. " Undo Create model Book\n"
  593. " Raw SQL operation -> ['SELECT * FROM migrations_salamand…\n",
  594. out.getvalue(),
  595. )
  596. out = io.StringIO()
  597. # Show the migration plan to fourth, with truncated details.
  598. call_command(
  599. "migrate", "migrations", "0004", plan=True, stdout=out, no_color=True
  600. )
  601. self.assertEqual(
  602. "Planned operations:\n"
  603. "migrations.0004_fourth\n"
  604. " Raw SQL operation -> SELECT * FROM migrations_author WHE…\n",
  605. out.getvalue(),
  606. )
  607. # Show the plan when an operation is irreversible.
  608. # Migrate to the fourth migration.
  609. call_command("migrate", "migrations", "0004", verbosity=0)
  610. out = io.StringIO()
  611. call_command(
  612. "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True
  613. )
  614. self.assertEqual(
  615. "Planned operations:\n"
  616. "migrations.0004_fourth\n"
  617. " Raw SQL operation -> IRREVERSIBLE\n",
  618. out.getvalue(),
  619. )
  620. out = io.StringIO()
  621. call_command(
  622. "migrate", "migrations", "0005", plan=True, stdout=out, no_color=True
  623. )
  624. # Operation is marked as irreversible only in the revert plan.
  625. self.assertEqual(
  626. "Planned operations:\n"
  627. "migrations.0005_fifth\n"
  628. " Raw Python operation\n"
  629. " Raw Python operation\n"
  630. " Raw Python operation -> Feed salamander.\n",
  631. out.getvalue(),
  632. )
  633. call_command("migrate", "migrations", "0005", verbosity=0)
  634. out = io.StringIO()
  635. call_command(
  636. "migrate", "migrations", "0004", plan=True, stdout=out, no_color=True
  637. )
  638. self.assertEqual(
  639. "Planned operations:\n"
  640. "migrations.0005_fifth\n"
  641. " Raw Python operation -> IRREVERSIBLE\n"
  642. " Raw Python operation -> IRREVERSIBLE\n"
  643. " Raw Python operation\n",
  644. out.getvalue(),
  645. )
  646. finally:
  647. # Cleanup by unmigrating everything: fake the irreversible, then
  648. # migrate all to zero.
  649. call_command("migrate", "migrations", "0003", fake=True, verbosity=0)
  650. call_command("migrate", "migrations", "zero", verbosity=0)
  651. @override_settings(
  652. MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"}
  653. )
  654. def test_showmigrations_no_migrations(self):
  655. out = io.StringIO()
  656. call_command("showmigrations", stdout=out, no_color=True)
  657. self.assertEqual("migrations\n (no migrations)\n", out.getvalue().lower())
  658. @override_settings(
  659. INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app"]
  660. )
  661. def test_showmigrations_unmigrated_app(self):
  662. out = io.StringIO()
  663. call_command("showmigrations", "unmigrated_app", stdout=out, no_color=True)
  664. try:
  665. self.assertEqual(
  666. "unmigrated_app\n (no migrations)\n", out.getvalue().lower()
  667. )
  668. finally:
  669. # unmigrated_app.SillyModel has a foreign key to
  670. # 'migrations.Tribble', but that model is only defined in a
  671. # migration, so the global app registry never sees it and the
  672. # reference is left dangling. Remove it to avoid problems in
  673. # subsequent tests.
  674. apps._pending_operations.pop(("migrations", "tribble"), None)
  675. @override_settings(
  676. MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"}
  677. )
  678. def test_showmigrations_plan_no_migrations(self):
  679. """
  680. Tests --plan output of showmigrations command without migrations
  681. """
  682. out = io.StringIO()
  683. call_command("showmigrations", format="plan", stdout=out, no_color=True)
  684. self.assertEqual("(no migrations)\n", out.getvalue().lower())
  685. out = io.StringIO()
  686. call_command(
  687. "showmigrations", format="plan", stdout=out, verbosity=2, no_color=True
  688. )
  689. self.assertEqual("(no migrations)\n", out.getvalue().lower())
  690. @override_settings(
  691. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"}
  692. )
  693. def test_showmigrations_plan_squashed(self):
  694. """
  695. Tests --plan output of showmigrations command with squashed migrations.
  696. """
  697. out = io.StringIO()
  698. call_command("showmigrations", format="plan", stdout=out)
  699. self.assertEqual(
  700. "[ ] migrations.1_auto\n"
  701. "[ ] migrations.2_auto\n"
  702. "[ ] migrations.3_squashed_5\n"
  703. "[ ] migrations.6_auto\n"
  704. "[ ] migrations.7_auto\n",
  705. out.getvalue().lower(),
  706. )
  707. out = io.StringIO()
  708. call_command("showmigrations", format="plan", stdout=out, verbosity=2)
  709. self.assertEqual(
  710. "[ ] migrations.1_auto\n"
  711. "[ ] migrations.2_auto ... (migrations.1_auto)\n"
  712. "[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n"
  713. "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
  714. "[ ] migrations.7_auto ... (migrations.6_auto)\n",
  715. out.getvalue().lower(),
  716. )
  717. call_command("migrate", "migrations", "3_squashed_5", verbosity=0)
  718. out = io.StringIO()
  719. call_command("showmigrations", format="plan", stdout=out)
  720. self.assertEqual(
  721. "[x] migrations.1_auto\n"
  722. "[x] migrations.2_auto\n"
  723. "[x] migrations.3_squashed_5\n"
  724. "[ ] migrations.6_auto\n"
  725. "[ ] migrations.7_auto\n",
  726. out.getvalue().lower(),
  727. )
  728. out = io.StringIO()
  729. call_command("showmigrations", format="plan", stdout=out, verbosity=2)
  730. self.assertEqual(
  731. "[x] migrations.1_auto\n"
  732. "[x] migrations.2_auto ... (migrations.1_auto)\n"
  733. "[x] migrations.3_squashed_5 ... (migrations.2_auto)\n"
  734. "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
  735. "[ ] migrations.7_auto ... (migrations.6_auto)\n",
  736. out.getvalue().lower(),
  737. )
  738. @override_settings(
  739. INSTALLED_APPS=[
  740. "migrations.migrations_test_apps.mutate_state_b",
  741. "migrations.migrations_test_apps.alter_fk.author_app",
  742. "migrations.migrations_test_apps.alter_fk.book_app",
  743. ]
  744. )
  745. def test_showmigrations_plan_single_app_label(self):
  746. """
  747. `showmigrations --plan app_label` output with a single app_label.
  748. """
  749. # Single app with no dependencies on other apps.
  750. out = io.StringIO()
  751. call_command("showmigrations", "mutate_state_b", format="plan", stdout=out)
  752. self.assertEqual(
  753. "[ ] mutate_state_b.0001_initial\n[ ] mutate_state_b.0002_add_field\n",
  754. out.getvalue(),
  755. )
  756. # Single app with dependencies.
  757. out = io.StringIO()
  758. call_command("showmigrations", "author_app", format="plan", stdout=out)
  759. self.assertEqual(
  760. "[ ] author_app.0001_initial\n"
  761. "[ ] book_app.0001_initial\n"
  762. "[ ] author_app.0002_alter_id\n",
  763. out.getvalue(),
  764. )
  765. # Some migrations already applied.
  766. call_command("migrate", "author_app", "0001", verbosity=0)
  767. out = io.StringIO()
  768. call_command("showmigrations", "author_app", format="plan", stdout=out)
  769. self.assertEqual(
  770. "[X] author_app.0001_initial\n"
  771. "[ ] book_app.0001_initial\n"
  772. "[ ] author_app.0002_alter_id\n",
  773. out.getvalue(),
  774. )
  775. # Cleanup by unmigrating author_app.
  776. call_command("migrate", "author_app", "zero", verbosity=0)
  777. @override_settings(
  778. INSTALLED_APPS=[
  779. "migrations.migrations_test_apps.mutate_state_b",
  780. "migrations.migrations_test_apps.alter_fk.author_app",
  781. "migrations.migrations_test_apps.alter_fk.book_app",
  782. ]
  783. )
  784. def test_showmigrations_plan_multiple_app_labels(self):
  785. """
  786. `showmigrations --plan app_label` output with multiple app_labels.
  787. """
  788. # Multiple apps: author_app depends on book_app; mutate_state_b doesn't
  789. # depend on other apps.
  790. out = io.StringIO()
  791. call_command(
  792. "showmigrations", "mutate_state_b", "author_app", format="plan", stdout=out
  793. )
  794. self.assertEqual(
  795. "[ ] author_app.0001_initial\n"
  796. "[ ] book_app.0001_initial\n"
  797. "[ ] author_app.0002_alter_id\n"
  798. "[ ] mutate_state_b.0001_initial\n"
  799. "[ ] mutate_state_b.0002_add_field\n",
  800. out.getvalue(),
  801. )
  802. # Multiple apps: args order shouldn't matter (the same result is
  803. # expected as above).
  804. out = io.StringIO()
  805. call_command(
  806. "showmigrations", "author_app", "mutate_state_b", format="plan", stdout=out
  807. )
  808. self.assertEqual(
  809. "[ ] author_app.0001_initial\n"
  810. "[ ] book_app.0001_initial\n"
  811. "[ ] author_app.0002_alter_id\n"
  812. "[ ] mutate_state_b.0001_initial\n"
  813. "[ ] mutate_state_b.0002_add_field\n",
  814. out.getvalue(),
  815. )
  816. @override_settings(
  817. INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app"]
  818. )
  819. def test_showmigrations_plan_app_label_no_migrations(self):
  820. out = io.StringIO()
  821. call_command(
  822. "showmigrations", "unmigrated_app", format="plan", stdout=out, no_color=True
  823. )
  824. try:
  825. self.assertEqual("(no migrations)\n", out.getvalue())
  826. finally:
  827. # unmigrated_app.SillyModel has a foreign key to
  828. # 'migrations.Tribble', but that model is only defined in a
  829. # migration, so the global app registry never sees it and the
  830. # reference is left dangling. Remove it to avoid problems in
  831. # subsequent tests.
  832. apps._pending_operations.pop(("migrations", "tribble"), None)
  833. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  834. def test_sqlmigrate_forwards(self):
  835. """
  836. sqlmigrate outputs forward looking SQL.
  837. """
  838. out = io.StringIO()
  839. call_command("sqlmigrate", "migrations", "0001", stdout=out, no_color=True)
  840. lines = out.getvalue().splitlines()
  841. if connection.features.can_rollback_ddl:
  842. self.assertEqual(lines[0], connection.ops.start_transaction_sql())
  843. self.assertEqual(lines[-1], connection.ops.end_transaction_sql())
  844. lines = lines[1:-1]
  845. self.assertEqual(
  846. lines[:3],
  847. [
  848. "--",
  849. "-- Create model Author",
  850. "--",
  851. ],
  852. )
  853. self.assertIn(
  854. "create table %s" % connection.ops.quote_name("migrations_author").lower(),
  855. lines[3].lower(),
  856. )
  857. pos = lines.index("--", 3)
  858. self.assertEqual(
  859. lines[pos : pos + 3],
  860. [
  861. "--",
  862. "-- Create model Tribble",
  863. "--",
  864. ],
  865. )
  866. self.assertIn(
  867. "create table %s" % connection.ops.quote_name("migrations_tribble").lower(),
  868. lines[pos + 3].lower(),
  869. )
  870. pos = lines.index("--", pos + 3)
  871. self.assertEqual(
  872. lines[pos : pos + 3],
  873. [
  874. "--",
  875. "-- Add field bool to tribble",
  876. "--",
  877. ],
  878. )
  879. pos = lines.index("--", pos + 3)
  880. self.assertEqual(
  881. lines[pos : pos + 3],
  882. [
  883. "--",
  884. "-- Alter unique_together for author (1 constraint(s))",
  885. "--",
  886. ],
  887. )
  888. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  889. def test_sqlmigrate_backwards(self):
  890. """
  891. sqlmigrate outputs reverse looking SQL.
  892. """
  893. # Cannot generate the reverse SQL unless we've applied the migration.
  894. call_command("migrate", "migrations", verbosity=0)
  895. out = io.StringIO()
  896. call_command(
  897. "sqlmigrate",
  898. "migrations",
  899. "0001",
  900. stdout=out,
  901. backwards=True,
  902. no_color=True,
  903. )
  904. lines = out.getvalue().splitlines()
  905. try:
  906. if connection.features.can_rollback_ddl:
  907. self.assertEqual(lines[0], connection.ops.start_transaction_sql())
  908. self.assertEqual(lines[-1], connection.ops.end_transaction_sql())
  909. lines = lines[1:-1]
  910. self.assertEqual(
  911. lines[:3],
  912. [
  913. "--",
  914. "-- Alter unique_together for author (1 constraint(s))",
  915. "--",
  916. ],
  917. )
  918. pos = lines.index("--", 3)
  919. self.assertEqual(
  920. lines[pos : pos + 3],
  921. [
  922. "--",
  923. "-- Add field bool to tribble",
  924. "--",
  925. ],
  926. )
  927. pos = lines.index("--", pos + 3)
  928. self.assertEqual(
  929. lines[pos : pos + 3],
  930. [
  931. "--",
  932. "-- Create model Tribble",
  933. "--",
  934. ],
  935. )
  936. next_pos = lines.index("--", pos + 3)
  937. drop_table_sql = (
  938. "drop table %s"
  939. % connection.ops.quote_name("migrations_tribble").lower()
  940. )
  941. for line in lines[pos + 3 : next_pos]:
  942. if drop_table_sql in line.lower():
  943. break
  944. else:
  945. self.fail("DROP TABLE (tribble) not found.")
  946. pos = next_pos
  947. self.assertEqual(
  948. lines[pos : pos + 3],
  949. [
  950. "--",
  951. "-- Create model Author",
  952. "--",
  953. ],
  954. )
  955. drop_table_sql = (
  956. "drop table %s" % connection.ops.quote_name("migrations_author").lower()
  957. )
  958. for line in lines[pos + 3 :]:
  959. if drop_table_sql in line.lower():
  960. break
  961. else:
  962. self.fail("DROP TABLE (author) not found.")
  963. finally:
  964. # Unmigrate everything.
  965. call_command("migrate", "migrations", "zero", verbosity=0)
  966. @override_settings(
  967. MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"}
  968. )
  969. def test_sqlmigrate_for_non_atomic_migration(self):
  970. """
  971. Transaction wrappers aren't shown for non-atomic migrations.
  972. """
  973. out = io.StringIO()
  974. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  975. output = out.getvalue().lower()
  976. queries = [q.strip() for q in output.splitlines()]
  977. if connection.ops.start_transaction_sql():
  978. self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)
  979. self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
  980. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  981. def test_sqlmigrate_for_non_transactional_databases(self):
  982. """
  983. Transaction wrappers aren't shown for databases that don't support
  984. transactional DDL.
  985. """
  986. out = io.StringIO()
  987. with mock.patch.object(connection.features, "can_rollback_ddl", False):
  988. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  989. output = out.getvalue().lower()
  990. queries = [q.strip() for q in output.splitlines()]
  991. start_transaction_sql = connection.ops.start_transaction_sql()
  992. if start_transaction_sql:
  993. self.assertNotIn(start_transaction_sql.lower(), queries)
  994. self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
  995. @override_settings(
  996. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  997. )
  998. def test_sqlmigrate_ambiguous_prefix_squashed_migrations(self):
  999. msg = (
  1000. "More than one migration matches '0001' in app 'migrations'. "
  1001. "Please be more specific."
  1002. )
  1003. with self.assertRaisesMessage(CommandError, msg):
  1004. call_command("sqlmigrate", "migrations", "0001")
  1005. @override_settings(
  1006. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  1007. )
  1008. def test_sqlmigrate_squashed_migration(self):
  1009. out = io.StringIO()
  1010. call_command("sqlmigrate", "migrations", "0001_squashed_0002", stdout=out)
  1011. output = out.getvalue().lower()
  1012. self.assertIn("-- create model author", output)
  1013. self.assertIn("-- create model book", output)
  1014. self.assertNotIn("-- create model tribble", output)
  1015. @override_settings(
  1016. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  1017. )
  1018. def test_sqlmigrate_replaced_migration(self):
  1019. out = io.StringIO()
  1020. call_command("sqlmigrate", "migrations", "0001_initial", stdout=out)
  1021. output = out.getvalue().lower()
  1022. self.assertIn("-- create model author", output)
  1023. self.assertIn("-- create model tribble", output)
  1024. @override_settings(
  1025. MIGRATION_MODULES={"migrations": "migrations.test_migrations_no_operations"}
  1026. )
  1027. def test_sqlmigrate_no_operations(self):
  1028. err = io.StringIO()
  1029. call_command("sqlmigrate", "migrations", "0001_initial", stderr=err)
  1030. self.assertEqual(err.getvalue(), "No operations found.\n")
  1031. @override_settings(
  1032. MIGRATION_MODULES={"migrations": "migrations.test_migrations_noop"}
  1033. )
  1034. def test_sqlmigrate_noop(self):
  1035. out = io.StringIO()
  1036. call_command("sqlmigrate", "migrations", "0001", stdout=out)
  1037. lines = out.getvalue().splitlines()
  1038. if connection.features.can_rollback_ddl:
  1039. lines = lines[1:-1]
  1040. self.assertEqual(
  1041. lines,
  1042. [
  1043. "--",
  1044. "-- Raw SQL operation",
  1045. "--",
  1046. "-- (no-op)",
  1047. ],
  1048. )
  1049. @override_settings(
  1050. MIGRATION_MODULES={"migrations": "migrations.test_migrations_manual_porting"}
  1051. )
  1052. def test_sqlmigrate_unrepresentable(self):
  1053. out = io.StringIO()
  1054. call_command("sqlmigrate", "migrations", "0002", stdout=out)
  1055. lines = out.getvalue().splitlines()
  1056. if connection.features.can_rollback_ddl:
  1057. lines = lines[1:-1]
  1058. self.assertEqual(
  1059. lines,
  1060. [
  1061. "--",
  1062. "-- Raw Python operation",
  1063. "--",
  1064. "-- THIS OPERATION CANNOT BE WRITTEN AS SQL",
  1065. ],
  1066. )
  1067. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  1068. def test_sqlmigrate_transaction_keywords_not_colorized(self):
  1069. out = io.StringIO()
  1070. with mock.patch(
  1071. "django.core.management.color.supports_color", lambda *args: True
  1072. ):
  1073. call_command("sqlmigrate", "migrations", "0001", stdout=out, no_color=False)
  1074. self.assertNotIn("\x1b", out.getvalue())
  1075. @override_settings(
  1076. MIGRATION_MODULES={"migrations": "migrations.test_migrations_no_operations"},
  1077. INSTALLED_APPS=["django.contrib.auth"],
  1078. )
  1079. def test_sqlmigrate_system_checks_colorized(self):
  1080. with (
  1081. mock.patch(
  1082. "django.core.management.color.supports_color", lambda *args: True
  1083. ),
  1084. self.assertRaisesMessage(SystemCheckError, "\x1b"),
  1085. ):
  1086. call_command(
  1087. "sqlmigrate", "migrations", "0001", skip_checks=False, no_color=False
  1088. )
  1089. @override_settings(
  1090. INSTALLED_APPS=[
  1091. "migrations.migrations_test_apps.migrated_app",
  1092. "migrations.migrations_test_apps.migrated_unapplied_app",
  1093. "migrations.migrations_test_apps.unmigrated_app",
  1094. ],
  1095. )
  1096. def test_regression_22823_unmigrated_fk_to_migrated_model(self):
  1097. """
  1098. Assuming you have 3 apps, `A`, `B`, and `C`, such that:
  1099. * `A` has migrations
  1100. * `B` has a migration we want to apply
  1101. * `C` has no migrations, but has an FK to `A`
  1102. When we try to migrate "B", an exception occurs because the
  1103. "B" was not included in the ProjectState that is used to detect
  1104. soft-applied migrations (#22823).
  1105. """
  1106. call_command("migrate", "migrated_unapplied_app", verbosity=0)
  1107. # unmigrated_app.SillyModel has a foreign key to 'migrations.Tribble',
  1108. # but that model is only defined in a migration, so the global app
  1109. # registry never sees it and the reference is left dangling. Remove it
  1110. # to avoid problems in subsequent tests.
  1111. apps._pending_operations.pop(("migrations", "tribble"), None)
  1112. @override_settings(
  1113. INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app_syncdb"]
  1114. )
  1115. def test_migrate_syncdb_deferred_sql_executed_with_schemaeditor(self):
  1116. """
  1117. For an app without migrations, editor.execute() is used for executing
  1118. the syncdb deferred SQL.
  1119. """
  1120. stdout = io.StringIO()
  1121. with mock.patch.object(BaseDatabaseSchemaEditor, "execute") as execute:
  1122. call_command(
  1123. "migrate", run_syncdb=True, verbosity=1, stdout=stdout, no_color=True
  1124. )
  1125. create_table_count = len(
  1126. [call for call in execute.mock_calls if "CREATE TABLE" in str(call)]
  1127. )
  1128. self.assertEqual(create_table_count, 2)
  1129. # There's at least one deferred SQL for creating the foreign key
  1130. # index.
  1131. self.assertGreater(len(execute.mock_calls), 2)
  1132. stdout = stdout.getvalue()
  1133. self.assertIn("Synchronize unmigrated apps: unmigrated_app_syncdb", stdout)
  1134. self.assertIn("Creating tables...", stdout)
  1135. table_name = truncate_name(
  1136. "unmigrated_app_syncdb_classroom", connection.ops.max_name_length()
  1137. )
  1138. self.assertIn("Creating table %s" % table_name, stdout)
  1139. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  1140. def test_migrate_syncdb_app_with_migrations(self):
  1141. msg = "Can't use run_syncdb with app 'migrations' as it has migrations."
  1142. with self.assertRaisesMessage(CommandError, msg):
  1143. call_command("migrate", "migrations", run_syncdb=True, verbosity=0)
  1144. @override_settings(
  1145. INSTALLED_APPS=[
  1146. "migrations.migrations_test_apps.unmigrated_app_syncdb",
  1147. "migrations.migrations_test_apps.unmigrated_app_simple",
  1148. ]
  1149. )
  1150. def test_migrate_syncdb_app_label(self):
  1151. """
  1152. Running migrate --run-syncdb with an app_label only creates tables for
  1153. the specified app.
  1154. """
  1155. stdout = io.StringIO()
  1156. with mock.patch.object(BaseDatabaseSchemaEditor, "execute") as execute:
  1157. call_command(
  1158. "migrate", "unmigrated_app_syncdb", run_syncdb=True, stdout=stdout
  1159. )
  1160. create_table_count = len(
  1161. [call for call in execute.mock_calls if "CREATE TABLE" in str(call)]
  1162. )
  1163. self.assertEqual(create_table_count, 2)
  1164. self.assertGreater(len(execute.mock_calls), 2)
  1165. self.assertIn(
  1166. "Synchronize unmigrated app: unmigrated_app_syncdb", stdout.getvalue()
  1167. )
  1168. @override_settings(
  1169. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  1170. )
  1171. def test_migrate_record_replaced(self):
  1172. """
  1173. Running a single squashed migration should record all of the original
  1174. replaced migrations as run.
  1175. """
  1176. recorder = MigrationRecorder(connection)
  1177. out = io.StringIO()
  1178. call_command("migrate", "migrations", verbosity=0)
  1179. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  1180. self.assertEqual(
  1181. "migrations\n [x] 0001_squashed_0002 (2 squashed migrations)\n",
  1182. out.getvalue().lower(),
  1183. )
  1184. applied_migrations = recorder.applied_migrations()
  1185. self.assertIn(("migrations", "0001_initial"), applied_migrations)
  1186. self.assertIn(("migrations", "0002_second"), applied_migrations)
  1187. self.assertIn(("migrations", "0001_squashed_0002"), applied_migrations)
  1188. # Rollback changes
  1189. call_command("migrate", "migrations", "zero", verbosity=0)
  1190. @override_settings(
  1191. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  1192. )
  1193. def test_migrate_record_squashed(self):
  1194. """
  1195. Running migrate for a squashed migration should record as run
  1196. if all of the replaced migrations have been run (#25231).
  1197. """
  1198. recorder = MigrationRecorder(connection)
  1199. recorder.record_applied("migrations", "0001_initial")
  1200. recorder.record_applied("migrations", "0002_second")
  1201. out = io.StringIO()
  1202. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  1203. self.assertEqual(
  1204. "migrations\n"
  1205. " [-] 0001_squashed_0002 (2 squashed migrations) "
  1206. "run 'manage.py migrate' to finish recording.\n",
  1207. out.getvalue().lower(),
  1208. )
  1209. out = io.StringIO()
  1210. call_command("migrate", "migrations", verbosity=0)
  1211. call_command("showmigrations", "migrations", stdout=out, no_color=True)
  1212. self.assertEqual(
  1213. "migrations\n [x] 0001_squashed_0002 (2 squashed migrations)\n",
  1214. out.getvalue().lower(),
  1215. )
  1216. self.assertIn(
  1217. ("migrations", "0001_squashed_0002"), recorder.applied_migrations()
  1218. )
  1219. # No changes were actually applied so there is nothing to rollback
  1220. def test_migrate_partially_applied_squashed_migration(self):
  1221. """
  1222. Migrating to a squashed migration specified by name should succeed
  1223. even if it is partially applied.
  1224. """
  1225. with self.temporary_migration_module(module="migrations.test_migrations"):
  1226. recorder = MigrationRecorder(connection)
  1227. try:
  1228. call_command("migrate", "migrations", "0001_initial", verbosity=0)
  1229. call_command(
  1230. "squashmigrations",
  1231. "migrations",
  1232. "0002",
  1233. interactive=False,
  1234. verbosity=0,
  1235. )
  1236. call_command(
  1237. "migrate",
  1238. "migrations",
  1239. "0001_squashed_0002_second",
  1240. verbosity=0,
  1241. )
  1242. applied_migrations = recorder.applied_migrations()
  1243. self.assertIn(("migrations", "0002_second"), applied_migrations)
  1244. finally:
  1245. # Unmigrate everything.
  1246. call_command("migrate", "migrations", "zero", verbosity=0)
  1247. @override_settings(
  1248. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  1249. )
  1250. def test_migrate_backward_to_squashed_migration(self):
  1251. try:
  1252. call_command("migrate", "migrations", "0001_squashed_0002", verbosity=0)
  1253. self.assertTableExists("migrations_author")
  1254. self.assertTableExists("migrations_book")
  1255. call_command("migrate", "migrations", "0001_initial", verbosity=0)
  1256. self.assertTableExists("migrations_author")
  1257. self.assertTableNotExists("migrations_book")
  1258. finally:
  1259. # Unmigrate everything.
  1260. call_command("migrate", "migrations", "zero", verbosity=0)
  1261. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  1262. def test_migrate_inconsistent_history(self):
  1263. """
  1264. Running migrate with some migrations applied before their dependencies
  1265. should not be allowed.
  1266. """
  1267. recorder = MigrationRecorder(connection)
  1268. recorder.record_applied("migrations", "0002_second")
  1269. msg = (
  1270. "Migration migrations.0002_second is applied before its dependency "
  1271. "migrations.0001_initial"
  1272. )
  1273. with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
  1274. call_command("migrate")
  1275. applied_migrations = recorder.applied_migrations()
  1276. self.assertNotIn(("migrations", "0001_initial"), applied_migrations)
  1277. @override_settings(
  1278. INSTALLED_APPS=[
  1279. "migrations.migrations_test_apps.migrated_unapplied_app",
  1280. "migrations.migrations_test_apps.migrated_app",
  1281. ]
  1282. )
  1283. def test_migrate_not_reflected_changes(self):
  1284. class NewModel1(models.Model):
  1285. class Meta:
  1286. app_label = "migrated_app"
  1287. class NewModel2(models.Model):
  1288. class Meta:
  1289. app_label = "migrated_unapplied_app"
  1290. out = io.StringIO()
  1291. try:
  1292. call_command("migrate", verbosity=0)
  1293. call_command("migrate", stdout=out, no_color=True)
  1294. self.assertEqual(
  1295. "operations to perform:\n"
  1296. " apply all migrations: migrated_app, migrated_unapplied_app\n"
  1297. "running migrations:\n"
  1298. " no migrations to apply.\n"
  1299. " your models in app(s): 'migrated_app', "
  1300. "'migrated_unapplied_app' have changes that are not yet "
  1301. "reflected in a migration, and so won't be applied.\n"
  1302. " run 'manage.py makemigrations' to make new migrations, and "
  1303. "then re-run 'manage.py migrate' to apply them.\n",
  1304. out.getvalue().lower(),
  1305. )
  1306. finally:
  1307. # Unmigrate everything.
  1308. call_command("migrate", "migrated_app", "zero", verbosity=0)
  1309. call_command("migrate", "migrated_unapplied_app", "zero", verbosity=0)
  1310. @override_settings(
  1311. MIGRATION_MODULES={
  1312. "migrations": "migrations.test_migrations_squashed_no_replaces",
  1313. }
  1314. )
  1315. def test_migrate_prune(self):
  1316. """
  1317. With prune=True, references to migration files deleted from the
  1318. migrations module (such as after being squashed) are removed from the
  1319. django_migrations table.
  1320. """
  1321. recorder = MigrationRecorder(connection)
  1322. recorder.record_applied("migrations", "0001_initial")
  1323. recorder.record_applied("migrations", "0002_second")
  1324. recorder.record_applied("migrations", "0001_squashed_0002")
  1325. out = io.StringIO()
  1326. try:
  1327. call_command("migrate", "migrations", prune=True, stdout=out, no_color=True)
  1328. self.assertEqual(
  1329. out.getvalue(),
  1330. "Pruning migrations:\n"
  1331. " Pruning migrations.0001_initial OK\n"
  1332. " Pruning migrations.0002_second OK\n",
  1333. )
  1334. applied_migrations = [
  1335. migration
  1336. for migration in recorder.applied_migrations()
  1337. if migration[0] == "migrations"
  1338. ]
  1339. self.assertEqual(applied_migrations, [("migrations", "0001_squashed_0002")])
  1340. finally:
  1341. recorder.record_unapplied("migrations", "0001_initial")
  1342. recorder.record_unapplied("migrations", "0001_second")
  1343. recorder.record_unapplied("migrations", "0001_squashed_0002")
  1344. @override_settings(
  1345. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  1346. )
  1347. def test_prune_deleted_squashed_migrations_in_replaces(self):
  1348. out = io.StringIO()
  1349. with self.temporary_migration_module(
  1350. module="migrations.test_migrations_squashed"
  1351. ) as migration_dir:
  1352. try:
  1353. call_command("migrate", "migrations", verbosity=0)
  1354. # Delete the replaced migrations.
  1355. os.remove(os.path.join(migration_dir, "0001_initial.py"))
  1356. os.remove(os.path.join(migration_dir, "0002_second.py"))
  1357. # --prune cannot be used before removing the "replaces"
  1358. # attribute.
  1359. call_command(
  1360. "migrate",
  1361. "migrations",
  1362. prune=True,
  1363. stdout=out,
  1364. no_color=True,
  1365. )
  1366. self.assertEqual(
  1367. out.getvalue(),
  1368. "Pruning migrations:\n"
  1369. " Cannot use --prune because the following squashed "
  1370. "migrations have their 'replaces' attributes and may not "
  1371. "be recorded as applied:\n"
  1372. " migrations.0001_squashed_0002\n"
  1373. " Re-run 'manage.py migrate' if they are not marked as "
  1374. "applied, and remove 'replaces' attributes in their "
  1375. "Migration classes.\n",
  1376. )
  1377. finally:
  1378. # Unmigrate everything.
  1379. call_command("migrate", "migrations", "zero", verbosity=0)
  1380. @override_settings(
  1381. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}
  1382. )
  1383. def test_prune_no_migrations_to_prune(self):
  1384. out = io.StringIO()
  1385. call_command("migrate", "migrations", prune=True, stdout=out, no_color=True)
  1386. self.assertEqual(
  1387. out.getvalue(),
  1388. "Pruning migrations:\n No migrations to prune.\n",
  1389. )
  1390. out = io.StringIO()
  1391. call_command(
  1392. "migrate",
  1393. "migrations",
  1394. prune=True,
  1395. stdout=out,
  1396. no_color=True,
  1397. verbosity=0,
  1398. )
  1399. self.assertEqual(out.getvalue(), "")
  1400. def test_prune_no_app_label(self):
  1401. msg = "Migrations can be pruned only when an app is specified."
  1402. with self.assertRaisesMessage(CommandError, msg):
  1403. call_command("migrate", prune=True)
  1404. @override_settings(
  1405. MIGRATION_MODULES={
  1406. "migrations": "migrations.test_migrations_squashed_no_replaces",
  1407. "migrations2": "migrations2.test_migrations_2_squashed_with_replaces",
  1408. },
  1409. INSTALLED_APPS=["migrations", "migrations2"],
  1410. )
  1411. def test_prune_respect_app_label(self):
  1412. recorder = MigrationRecorder(connection)
  1413. recorder.record_applied("migrations", "0001_initial")
  1414. recorder.record_applied("migrations", "0002_second")
  1415. recorder.record_applied("migrations", "0001_squashed_0002")
  1416. # Second app has squashed migrations with replaces.
  1417. recorder.record_applied("migrations2", "0001_initial")
  1418. recorder.record_applied("migrations2", "0002_second")
  1419. recorder.record_applied("migrations2", "0001_squashed_0002")
  1420. out = io.StringIO()
  1421. try:
  1422. call_command("migrate", "migrations", prune=True, stdout=out, no_color=True)
  1423. self.assertEqual(
  1424. out.getvalue(),
  1425. "Pruning migrations:\n"
  1426. " Pruning migrations.0001_initial OK\n"
  1427. " Pruning migrations.0002_second OK\n",
  1428. )
  1429. applied_migrations = [
  1430. migration
  1431. for migration in recorder.applied_migrations()
  1432. if migration[0] in ["migrations", "migrations2"]
  1433. ]
  1434. self.assertEqual(
  1435. applied_migrations,
  1436. [
  1437. ("migrations", "0001_squashed_0002"),
  1438. ("migrations2", "0001_initial"),
  1439. ("migrations2", "0002_second"),
  1440. ("migrations2", "0001_squashed_0002"),
  1441. ],
  1442. )
  1443. finally:
  1444. recorder.record_unapplied("migrations", "0001_initial")
  1445. recorder.record_unapplied("migrations", "0001_second")
  1446. recorder.record_unapplied("migrations", "0001_squashed_0002")
  1447. recorder.record_unapplied("migrations2", "0001_initial")
  1448. recorder.record_unapplied("migrations2", "0002_second")
  1449. recorder.record_unapplied("migrations2", "0001_squashed_0002")
  1450. class MakeMigrationsTests(MigrationTestBase):
  1451. """
  1452. Tests running the makemigrations command.
  1453. """
  1454. def setUp(self):
  1455. super().setUp()
  1456. self._old_models = apps.app_configs["migrations"].models.copy()
  1457. def tearDown(self):
  1458. apps.app_configs["migrations"].models = self._old_models
  1459. apps.all_models["migrations"] = self._old_models
  1460. apps.clear_cache()
  1461. super().tearDown()
  1462. def test_files_content(self):
  1463. self.assertTableNotExists("migrations_unicodemodel")
  1464. apps.register_model("migrations", UnicodeModel)
  1465. with self.temporary_migration_module() as migration_dir:
  1466. call_command("makemigrations", "migrations", verbosity=0)
  1467. # Check for empty __init__.py file in migrations folder
  1468. init_file = os.path.join(migration_dir, "__init__.py")
  1469. self.assertTrue(os.path.exists(init_file))
  1470. with open(init_file) as fp:
  1471. content = fp.read()
  1472. self.assertEqual(content, "")
  1473. # Check for existing 0001_initial.py file in migration folder
  1474. initial_file = os.path.join(migration_dir, "0001_initial.py")
  1475. self.assertTrue(os.path.exists(initial_file))
  1476. with open(initial_file, encoding="utf-8") as fp:
  1477. content = fp.read()
  1478. self.assertIn("migrations.CreateModel", content)
  1479. self.assertIn("initial = True", content)
  1480. self.assertIn("úñí©óðé µóðéø", content) # Meta.verbose_name
  1481. self.assertIn("úñí©óðé µóðéøß", content) # Meta.verbose_name_plural
  1482. self.assertIn("ÚÑÍ¢ÓÐÉ", content) # title.verbose_name
  1483. self.assertIn("“Ðjáñgó”", content) # title.default
  1484. def test_makemigrations_order(self):
  1485. """
  1486. makemigrations should recognize number-only migrations (0001.py).
  1487. """
  1488. module = "migrations.test_migrations_order"
  1489. with self.temporary_migration_module(module=module) as migration_dir:
  1490. if hasattr(importlib, "invalidate_caches"):
  1491. # importlib caches os.listdir() on some platforms like macOS
  1492. # (#23850).
  1493. importlib.invalidate_caches()
  1494. call_command(
  1495. "makemigrations", "migrations", "--empty", "-n", "a", "-v", "0"
  1496. )
  1497. self.assertTrue(os.path.exists(os.path.join(migration_dir, "0002_a.py")))
  1498. def test_makemigrations_empty_connections(self):
  1499. empty_connections = ConnectionHandler({"default": {}})
  1500. with mock.patch(
  1501. "django.core.management.commands.makemigrations.connections",
  1502. new=empty_connections,
  1503. ):
  1504. # with no apps
  1505. out = io.StringIO()
  1506. call_command("makemigrations", stdout=out)
  1507. self.assertIn("No changes detected", out.getvalue())
  1508. # with an app
  1509. with self.temporary_migration_module() as migration_dir:
  1510. call_command("makemigrations", "migrations", verbosity=0)
  1511. init_file = os.path.join(migration_dir, "__init__.py")
  1512. self.assertTrue(os.path.exists(init_file))
  1513. @override_settings(INSTALLED_APPS=["migrations", "migrations2"])
  1514. def test_makemigrations_consistency_checks_respect_routers(self):
  1515. """
  1516. The history consistency checks in makemigrations respect
  1517. settings.DATABASE_ROUTERS.
  1518. """
  1519. def patched_has_table(migration_recorder):
  1520. if migration_recorder.connection is connections["other"]:
  1521. raise Exception("Other connection")
  1522. else:
  1523. return mock.DEFAULT
  1524. self.assertTableNotExists("migrations_unicodemodel")
  1525. apps.register_model("migrations", UnicodeModel)
  1526. with mock.patch.object(
  1527. MigrationRecorder, "has_table", autospec=True, side_effect=patched_has_table
  1528. ) as has_table:
  1529. with self.temporary_migration_module() as migration_dir:
  1530. call_command("makemigrations", "migrations", verbosity=0)
  1531. initial_file = os.path.join(migration_dir, "0001_initial.py")
  1532. self.assertTrue(os.path.exists(initial_file))
  1533. self.assertEqual(has_table.call_count, 1) # 'default' is checked
  1534. # Router says not to migrate 'other' so consistency shouldn't
  1535. # be checked.
  1536. with self.settings(DATABASE_ROUTERS=["migrations.routers.TestRouter"]):
  1537. call_command("makemigrations", "migrations", verbosity=0)
  1538. self.assertEqual(has_table.call_count, 2) # 'default' again
  1539. # With a router that doesn't prohibit migrating 'other',
  1540. # consistency is checked.
  1541. with self.settings(
  1542. DATABASE_ROUTERS=["migrations.routers.DefaultOtherRouter"]
  1543. ):
  1544. with self.assertRaisesMessage(Exception, "Other connection"):
  1545. call_command("makemigrations", "migrations", verbosity=0)
  1546. self.assertEqual(has_table.call_count, 4) # 'default' and 'other'
  1547. # With a router that doesn't allow migrating on any database,
  1548. # no consistency checks are made.
  1549. with self.settings(DATABASE_ROUTERS=["migrations.routers.TestRouter"]):
  1550. with mock.patch.object(
  1551. TestRouter, "allow_migrate", return_value=False
  1552. ) as allow_migrate:
  1553. call_command("makemigrations", "migrations", verbosity=0)
  1554. allow_migrate.assert_any_call(
  1555. "other", "migrations", model_name="UnicodeModel"
  1556. )
  1557. # allow_migrate() is called with the correct arguments.
  1558. self.assertGreater(len(allow_migrate.mock_calls), 0)
  1559. called_aliases = set()
  1560. for mock_call in allow_migrate.mock_calls:
  1561. _, call_args, call_kwargs = mock_call
  1562. connection_alias, app_name = call_args
  1563. called_aliases.add(connection_alias)
  1564. # Raises an error if invalid app_name/model_name occurs.
  1565. apps.get_app_config(app_name).get_model(call_kwargs["model_name"])
  1566. self.assertEqual(called_aliases, set(connections))
  1567. self.assertEqual(has_table.call_count, 4)
  1568. def test_failing_migration(self):
  1569. # If a migration fails to serialize, it shouldn't generate an empty file. #21280
  1570. apps.register_model("migrations", UnserializableModel)
  1571. with self.temporary_migration_module() as migration_dir:
  1572. with self.assertRaisesMessage(ValueError, "Cannot serialize"):
  1573. call_command("makemigrations", "migrations", verbosity=0)
  1574. initial_file = os.path.join(migration_dir, "0001_initial.py")
  1575. self.assertFalse(os.path.exists(initial_file))
  1576. def test_makemigrations_conflict_exit(self):
  1577. """
  1578. makemigrations exits if it detects a conflict.
  1579. """
  1580. with self.temporary_migration_module(
  1581. module="migrations.test_migrations_conflict"
  1582. ):
  1583. with self.assertRaises(CommandError) as context:
  1584. call_command("makemigrations")
  1585. self.assertEqual(
  1586. str(context.exception),
  1587. "Conflicting migrations detected; multiple leaf nodes in the "
  1588. "migration graph: (0002_conflicting_second, 0002_second in "
  1589. "migrations).\n"
  1590. "To fix them run 'python manage.py makemigrations --merge'",
  1591. )
  1592. def test_makemigrations_merge_no_conflict(self):
  1593. """
  1594. makemigrations exits if in merge mode with no conflicts.
  1595. """
  1596. out = io.StringIO()
  1597. with self.temporary_migration_module(module="migrations.test_migrations"):
  1598. call_command("makemigrations", merge=True, stdout=out)
  1599. self.assertIn("No conflicts detected to merge.", out.getvalue())
  1600. def test_makemigrations_empty_no_app_specified(self):
  1601. """
  1602. makemigrations exits if no app is specified with 'empty' mode.
  1603. """
  1604. msg = "You must supply at least one app label when using --empty."
  1605. with self.assertRaisesMessage(CommandError, msg):
  1606. call_command("makemigrations", empty=True)
  1607. def test_makemigrations_empty_migration(self):
  1608. """
  1609. makemigrations properly constructs an empty migration.
  1610. """
  1611. with self.temporary_migration_module() as migration_dir:
  1612. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  1613. # Check for existing 0001_initial.py file in migration folder
  1614. initial_file = os.path.join(migration_dir, "0001_initial.py")
  1615. self.assertTrue(os.path.exists(initial_file))
  1616. with open(initial_file, encoding="utf-8") as fp:
  1617. content = fp.read()
  1618. # Remove all whitespace to check for empty dependencies and operations
  1619. content = content.replace(" ", "")
  1620. self.assertIn(
  1621. "dependencies=[]" if HAS_BLACK else "dependencies=[\n]", content
  1622. )
  1623. self.assertIn(
  1624. "operations=[]" if HAS_BLACK else "operations=[\n]", content
  1625. )
  1626. @override_settings(MIGRATION_MODULES={"migrations": None})
  1627. def test_makemigrations_disabled_migrations_for_app(self):
  1628. """
  1629. makemigrations raises a nice error when migrations are disabled for an
  1630. app.
  1631. """
  1632. msg = (
  1633. "Django can't create migrations for app 'migrations' because migrations "
  1634. "have been disabled via the MIGRATION_MODULES setting."
  1635. )
  1636. with self.assertRaisesMessage(ValueError, msg):
  1637. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  1638. def test_makemigrations_no_changes_no_apps(self):
  1639. """
  1640. makemigrations exits when there are no changes and no apps are specified.
  1641. """
  1642. out = io.StringIO()
  1643. call_command("makemigrations", stdout=out)
  1644. self.assertIn("No changes detected", out.getvalue())
  1645. def test_makemigrations_no_changes(self):
  1646. """
  1647. makemigrations exits when there are no changes to an app.
  1648. """
  1649. out = io.StringIO()
  1650. with self.temporary_migration_module(
  1651. module="migrations.test_migrations_no_changes"
  1652. ):
  1653. call_command("makemigrations", "migrations", stdout=out)
  1654. self.assertIn("No changes detected in app 'migrations'", out.getvalue())
  1655. def test_makemigrations_no_apps_initial(self):
  1656. """
  1657. makemigrations should detect initial is needed on empty migration
  1658. modules if no app provided.
  1659. """
  1660. out = io.StringIO()
  1661. with self.temporary_migration_module(module="migrations.test_migrations_empty"):
  1662. call_command("makemigrations", stdout=out)
  1663. self.assertIn("0001_initial.py", out.getvalue())
  1664. def test_makemigrations_no_init(self):
  1665. """Migration directories without an __init__.py file are allowed."""
  1666. out = io.StringIO()
  1667. with self.temporary_migration_module(
  1668. module="migrations.test_migrations_no_init"
  1669. ):
  1670. call_command("makemigrations", stdout=out)
  1671. self.assertIn("0001_initial.py", out.getvalue())
  1672. def test_makemigrations_no_init_ambiguous(self):
  1673. """
  1674. Migration directories without an __init__.py file are not allowed if
  1675. there are multiple namespace search paths that resolve to them.
  1676. """
  1677. out = io.StringIO()
  1678. with self.temporary_migration_module(
  1679. module="migrations.test_migrations_no_init"
  1680. ) as migration_dir:
  1681. # Copy the project directory into another place under sys.path.
  1682. app_dir = Path(migration_dir).parent
  1683. os.remove(app_dir / "__init__.py")
  1684. project_dir = app_dir.parent
  1685. dest = project_dir.parent / "other_dir_in_path"
  1686. shutil.copytree(project_dir, dest)
  1687. with extend_sys_path(str(dest)):
  1688. call_command("makemigrations", stdout=out)
  1689. self.assertEqual("No changes detected\n", out.getvalue())
  1690. def test_makemigrations_migrations_announce(self):
  1691. """
  1692. makemigrations announces the migration at the default verbosity level.
  1693. """
  1694. out = io.StringIO()
  1695. with self.temporary_migration_module():
  1696. call_command("makemigrations", "migrations", stdout=out)
  1697. self.assertIn("Migrations for 'migrations'", out.getvalue())
  1698. def test_makemigrations_no_common_ancestor(self):
  1699. """
  1700. makemigrations fails to merge migrations with no common ancestor.
  1701. """
  1702. with self.assertRaises(ValueError) as context:
  1703. with self.temporary_migration_module(
  1704. module="migrations.test_migrations_no_ancestor"
  1705. ):
  1706. call_command("makemigrations", "migrations", merge=True)
  1707. exception_message = str(context.exception)
  1708. self.assertIn("Could not find common ancestor of", exception_message)
  1709. self.assertIn("0002_second", exception_message)
  1710. self.assertIn("0002_conflicting_second", exception_message)
  1711. def test_makemigrations_interactive_reject(self):
  1712. """
  1713. makemigrations enters and exits interactive mode properly.
  1714. """
  1715. # Monkeypatch interactive questioner to auto reject
  1716. with mock.patch("builtins.input", mock.Mock(return_value="N")):
  1717. with self.temporary_migration_module(
  1718. module="migrations.test_migrations_conflict"
  1719. ) as migration_dir:
  1720. with captured_stdout():
  1721. call_command(
  1722. "makemigrations",
  1723. "migrations",
  1724. name="merge",
  1725. merge=True,
  1726. interactive=True,
  1727. verbosity=0,
  1728. )
  1729. merge_file = os.path.join(migration_dir, "0003_merge.py")
  1730. self.assertFalse(os.path.exists(merge_file))
  1731. def test_makemigrations_interactive_accept(self):
  1732. """
  1733. makemigrations enters interactive mode and merges properly.
  1734. """
  1735. # Monkeypatch interactive questioner to auto accept
  1736. with mock.patch("builtins.input", mock.Mock(return_value="y")):
  1737. out = io.StringIO()
  1738. with self.temporary_migration_module(
  1739. module="migrations.test_migrations_conflict"
  1740. ) as migration_dir:
  1741. call_command(
  1742. "makemigrations",
  1743. "migrations",
  1744. name="merge",
  1745. merge=True,
  1746. interactive=True,
  1747. stdout=out,
  1748. )
  1749. merge_file = os.path.join(migration_dir, "0003_merge.py")
  1750. self.assertTrue(os.path.exists(merge_file))
  1751. self.assertIn("Created new merge migration", out.getvalue())
  1752. def test_makemigrations_default_merge_name(self):
  1753. out = io.StringIO()
  1754. with self.temporary_migration_module(
  1755. module="migrations.test_migrations_conflict"
  1756. ) as migration_dir:
  1757. call_command(
  1758. "makemigrations",
  1759. "migrations",
  1760. merge=True,
  1761. interactive=False,
  1762. stdout=out,
  1763. )
  1764. merge_file = os.path.join(
  1765. migration_dir,
  1766. "0003_merge_0002_conflicting_second_0002_second.py",
  1767. )
  1768. self.assertIs(os.path.exists(merge_file), True)
  1769. with open(merge_file, encoding="utf-8") as fp:
  1770. content = fp.read()
  1771. if HAS_BLACK:
  1772. target_str = '("migrations", "0002_conflicting_second")'
  1773. else:
  1774. target_str = "('migrations', '0002_conflicting_second')"
  1775. self.assertIn(target_str, content)
  1776. self.assertIn("Created new merge migration %s" % merge_file, out.getvalue())
  1777. @mock.patch("django.db.migrations.utils.datetime")
  1778. def test_makemigrations_auto_merge_name(self, mock_datetime):
  1779. mock_datetime.datetime.now.return_value = datetime.datetime(2016, 1, 2, 3, 4)
  1780. with mock.patch("builtins.input", mock.Mock(return_value="y")):
  1781. out = io.StringIO()
  1782. with self.temporary_migration_module(
  1783. module="migrations.test_migrations_conflict_long_name"
  1784. ) as migration_dir:
  1785. call_command(
  1786. "makemigrations",
  1787. "migrations",
  1788. merge=True,
  1789. interactive=True,
  1790. stdout=out,
  1791. )
  1792. merge_file = os.path.join(migration_dir, "0003_merge_20160102_0304.py")
  1793. self.assertTrue(os.path.exists(merge_file))
  1794. self.assertIn("Created new merge migration", out.getvalue())
  1795. def test_makemigrations_non_interactive_not_null_addition(self):
  1796. """
  1797. Non-interactive makemigrations fails when a default is missing on a
  1798. new not-null field.
  1799. """
  1800. class SillyModel(models.Model):
  1801. silly_field = models.BooleanField(default=False)
  1802. silly_int = models.IntegerField()
  1803. class Meta:
  1804. app_label = "migrations"
  1805. with self.assertRaises(SystemExit):
  1806. with self.temporary_migration_module(
  1807. module="migrations.test_migrations_no_default"
  1808. ):
  1809. with captured_stdout() as out:
  1810. call_command("makemigrations", "migrations", interactive=False)
  1811. self.assertIn(
  1812. "Field 'silly_int' on model 'sillymodel' not migrated: it is "
  1813. "impossible to add a non-nullable field without specifying a "
  1814. "default.",
  1815. out.getvalue(),
  1816. )
  1817. def test_makemigrations_interactive_not_null_addition(self):
  1818. """
  1819. makemigrations messages when adding a NOT NULL field in interactive
  1820. mode.
  1821. """
  1822. class Author(models.Model):
  1823. silly_field = models.BooleanField(null=False)
  1824. class Meta:
  1825. app_label = "migrations"
  1826. input_msg = (
  1827. "It is impossible to add a non-nullable field 'silly_field' to "
  1828. "author without specifying a default. This is because the "
  1829. "database needs something to populate existing rows.\n"
  1830. "Please select a fix:\n"
  1831. " 1) Provide a one-off default now (will be set on all existing "
  1832. "rows with a null value for this column)\n"
  1833. " 2) Quit and manually define a default value in models.py."
  1834. )
  1835. with self.temporary_migration_module(module="migrations.test_migrations"):
  1836. # 2 - quit.
  1837. with mock.patch("builtins.input", return_value="2"):
  1838. with captured_stdout() as out, self.assertRaises(SystemExit):
  1839. call_command("makemigrations", "migrations", interactive=True)
  1840. self.assertIn(input_msg, out.getvalue())
  1841. # 1 - provide a default.
  1842. with mock.patch("builtins.input", return_value="1"):
  1843. with captured_stdout() as out:
  1844. call_command("makemigrations", "migrations", interactive=True)
  1845. output = out.getvalue()
  1846. self.assertIn(input_msg, output)
  1847. self.assertIn("Please enter the default value as valid Python.", output)
  1848. self.assertIn(
  1849. "The datetime and django.utils.timezone modules are "
  1850. "available, so it is possible to provide e.g. timezone.now as "
  1851. "a value",
  1852. output,
  1853. )
  1854. self.assertIn("Type 'exit' to exit this prompt", output)
  1855. def test_makemigrations_non_interactive_not_null_alteration(self):
  1856. """
  1857. Non-interactive makemigrations fails when a default is missing on a
  1858. field changed to not-null.
  1859. """
  1860. class Author(models.Model):
  1861. name = models.CharField(max_length=255)
  1862. slug = models.SlugField()
  1863. age = models.IntegerField(default=0)
  1864. class Meta:
  1865. app_label = "migrations"
  1866. with self.temporary_migration_module(module="migrations.test_migrations"):
  1867. with captured_stdout() as out:
  1868. call_command("makemigrations", "migrations", interactive=False)
  1869. self.assertIn("Alter field slug on author", out.getvalue())
  1870. self.assertIn(
  1871. "Field 'slug' on model 'author' given a default of NOT PROVIDED "
  1872. "and must be corrected.",
  1873. out.getvalue(),
  1874. )
  1875. def test_makemigrations_interactive_not_null_alteration(self):
  1876. """
  1877. makemigrations messages when changing a NULL field to NOT NULL in
  1878. interactive mode.
  1879. """
  1880. class Author(models.Model):
  1881. slug = models.SlugField(null=False)
  1882. class Meta:
  1883. app_label = "migrations"
  1884. input_msg = (
  1885. "It is impossible to change a nullable field 'slug' on author to "
  1886. "non-nullable without providing a default. This is because the "
  1887. "database needs something to populate existing rows.\n"
  1888. "Please select a fix:\n"
  1889. " 1) Provide a one-off default now (will be set on all existing "
  1890. "rows with a null value for this column)\n"
  1891. " 2) Ignore for now. Existing rows that contain NULL values will "
  1892. "have to be handled manually, for example with a RunPython or "
  1893. "RunSQL operation.\n"
  1894. " 3) Quit and manually define a default value in models.py."
  1895. )
  1896. with self.temporary_migration_module(module="migrations.test_migrations"):
  1897. # No message appears if --dry-run.
  1898. with captured_stdout() as out:
  1899. call_command(
  1900. "makemigrations",
  1901. "migrations",
  1902. interactive=True,
  1903. dry_run=True,
  1904. )
  1905. self.assertNotIn(input_msg, out.getvalue())
  1906. # 3 - quit.
  1907. with mock.patch("builtins.input", return_value="3"):
  1908. with captured_stdout() as out, self.assertRaises(SystemExit):
  1909. call_command("makemigrations", "migrations", interactive=True)
  1910. self.assertIn(input_msg, out.getvalue())
  1911. # 1 - provide a default.
  1912. with mock.patch("builtins.input", return_value="1"):
  1913. with captured_stdout() as out:
  1914. call_command("makemigrations", "migrations", interactive=True)
  1915. output = out.getvalue()
  1916. self.assertIn(input_msg, output)
  1917. self.assertIn("Please enter the default value as valid Python.", output)
  1918. self.assertIn(
  1919. "The datetime and django.utils.timezone modules are "
  1920. "available, so it is possible to provide e.g. timezone.now as "
  1921. "a value",
  1922. output,
  1923. )
  1924. self.assertIn("Type 'exit' to exit this prompt", output)
  1925. def test_makemigrations_non_interactive_no_model_rename(self):
  1926. """
  1927. makemigrations adds and removes a possible model rename in
  1928. non-interactive mode.
  1929. """
  1930. class RenamedModel(models.Model):
  1931. silly_field = models.BooleanField(default=False)
  1932. class Meta:
  1933. app_label = "migrations"
  1934. out = io.StringIO()
  1935. with self.temporary_migration_module(
  1936. module="migrations.test_migrations_no_default"
  1937. ):
  1938. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  1939. self.assertIn("Delete model SillyModel", out.getvalue())
  1940. self.assertIn("Create model RenamedModel", out.getvalue())
  1941. def test_makemigrations_non_interactive_no_field_rename(self):
  1942. """
  1943. makemigrations adds and removes a possible field rename in
  1944. non-interactive mode.
  1945. """
  1946. class SillyModel(models.Model):
  1947. silly_rename = models.BooleanField(default=False)
  1948. class Meta:
  1949. app_label = "migrations"
  1950. out = io.StringIO()
  1951. with self.temporary_migration_module(
  1952. module="migrations.test_migrations_no_default"
  1953. ):
  1954. call_command("makemigrations", "migrations", interactive=False, stdout=out)
  1955. self.assertIn("Remove field silly_field from sillymodel", out.getvalue())
  1956. self.assertIn("Add field silly_rename to sillymodel", out.getvalue())
  1957. @mock.patch("builtins.input", return_value="Y")
  1958. def test_makemigrations_model_rename_interactive(self, mock_input):
  1959. class RenamedModel(models.Model):
  1960. silly_field = models.BooleanField(default=False)
  1961. class Meta:
  1962. app_label = "migrations"
  1963. with self.temporary_migration_module(
  1964. module="migrations.test_migrations_no_default",
  1965. ):
  1966. with captured_stdout() as out:
  1967. call_command("makemigrations", "migrations", interactive=True)
  1968. self.assertIn("Rename model SillyModel to RenamedModel", out.getvalue())
  1969. @mock.patch("builtins.input", return_value="Y")
  1970. def test_makemigrations_field_rename_interactive(self, mock_input):
  1971. class SillyModel(models.Model):
  1972. silly_rename = models.BooleanField(default=False)
  1973. class Meta:
  1974. app_label = "migrations"
  1975. with self.temporary_migration_module(
  1976. module="migrations.test_migrations_no_default",
  1977. ):
  1978. with captured_stdout() as out:
  1979. call_command("makemigrations", "migrations", interactive=True)
  1980. self.assertIn(
  1981. "Rename field silly_field on sillymodel to silly_rename",
  1982. out.getvalue(),
  1983. )
  1984. def test_makemigrations_handle_merge(self):
  1985. """
  1986. makemigrations properly merges the conflicting migrations with --noinput.
  1987. """
  1988. out = io.StringIO()
  1989. with self.temporary_migration_module(
  1990. module="migrations.test_migrations_conflict"
  1991. ) as migration_dir:
  1992. call_command(
  1993. "makemigrations",
  1994. "migrations",
  1995. name="merge",
  1996. merge=True,
  1997. interactive=False,
  1998. stdout=out,
  1999. )
  2000. merge_file = os.path.join(migration_dir, "0003_merge.py")
  2001. self.assertTrue(os.path.exists(merge_file))
  2002. output = out.getvalue()
  2003. self.assertIn("Merging migrations", output)
  2004. self.assertIn("Branch 0002_second", output)
  2005. self.assertIn("Branch 0002_conflicting_second", output)
  2006. self.assertIn("Created new merge migration", output)
  2007. def test_makemigration_merge_dry_run(self):
  2008. """
  2009. makemigrations respects --dry-run option when fixing migration
  2010. conflicts (#24427).
  2011. """
  2012. out = io.StringIO()
  2013. with self.temporary_migration_module(
  2014. module="migrations.test_migrations_conflict"
  2015. ) as migration_dir:
  2016. call_command(
  2017. "makemigrations",
  2018. "migrations",
  2019. name="merge",
  2020. dry_run=True,
  2021. merge=True,
  2022. interactive=False,
  2023. stdout=out,
  2024. )
  2025. merge_file = os.path.join(migration_dir, "0003_merge.py")
  2026. self.assertFalse(os.path.exists(merge_file))
  2027. output = out.getvalue()
  2028. self.assertIn("Merging migrations", output)
  2029. self.assertIn("Branch 0002_second", output)
  2030. self.assertIn("Branch 0002_conflicting_second", output)
  2031. self.assertNotIn("Created new merge migration", output)
  2032. def test_makemigration_merge_dry_run_verbosity_3(self):
  2033. """
  2034. `makemigrations --merge --dry-run` writes the merge migration file to
  2035. stdout with `verbosity == 3` (#24427).
  2036. """
  2037. out = io.StringIO()
  2038. with self.temporary_migration_module(
  2039. module="migrations.test_migrations_conflict"
  2040. ) as migration_dir:
  2041. call_command(
  2042. "makemigrations",
  2043. "migrations",
  2044. name="merge",
  2045. dry_run=True,
  2046. merge=True,
  2047. interactive=False,
  2048. stdout=out,
  2049. verbosity=3,
  2050. )
  2051. merge_file = os.path.join(migration_dir, "0003_merge.py")
  2052. self.assertFalse(os.path.exists(merge_file))
  2053. output = out.getvalue()
  2054. self.assertIn("Merging migrations", output)
  2055. self.assertIn("Branch 0002_second", output)
  2056. self.assertIn("Branch 0002_conflicting_second", output)
  2057. self.assertNotIn("Created new merge migration", output)
  2058. # Additional output caused by verbosity 3
  2059. # The complete merge migration file that would be written
  2060. self.assertIn("class Migration(migrations.Migration):", output)
  2061. self.assertIn("dependencies = [", output)
  2062. self.assertIn("('migrations', '0002_second')", output)
  2063. self.assertIn("('migrations', '0002_conflicting_second')", output)
  2064. self.assertIn("operations = [", output)
  2065. self.assertIn("]", output)
  2066. def test_makemigrations_dry_run(self):
  2067. """
  2068. `makemigrations --dry-run` should not ask for defaults.
  2069. """
  2070. class SillyModel(models.Model):
  2071. silly_field = models.BooleanField(default=False)
  2072. silly_date = models.DateField() # Added field without a default
  2073. silly_auto_now = models.DateTimeField(auto_now_add=True)
  2074. class Meta:
  2075. app_label = "migrations"
  2076. out = io.StringIO()
  2077. with self.temporary_migration_module(
  2078. module="migrations.test_migrations_no_default"
  2079. ):
  2080. call_command("makemigrations", "migrations", dry_run=True, stdout=out)
  2081. # Output the expected changes directly, without asking for defaults
  2082. self.assertIn("Add field silly_date to sillymodel", out.getvalue())
  2083. def test_makemigrations_dry_run_verbosity_3(self):
  2084. """
  2085. Allow `makemigrations --dry-run` to output the migrations file to
  2086. stdout (with verbosity == 3).
  2087. """
  2088. class SillyModel(models.Model):
  2089. silly_field = models.BooleanField(default=False)
  2090. silly_char = models.CharField(default="")
  2091. class Meta:
  2092. app_label = "migrations"
  2093. out = io.StringIO()
  2094. with self.temporary_migration_module(
  2095. module="migrations.test_migrations_no_default"
  2096. ):
  2097. call_command(
  2098. "makemigrations", "migrations", dry_run=True, stdout=out, verbosity=3
  2099. )
  2100. # Normal --dry-run output
  2101. self.assertIn("+ Add field silly_char to sillymodel", out.getvalue())
  2102. # Additional output caused by verbosity 3
  2103. # The complete migrations file that would be written
  2104. self.assertIn("class Migration(migrations.Migration):", out.getvalue())
  2105. self.assertIn("dependencies = [", out.getvalue())
  2106. self.assertIn("('migrations', '0001_initial'),", out.getvalue())
  2107. self.assertIn("migrations.AddField(", out.getvalue())
  2108. self.assertIn("model_name='sillymodel',", out.getvalue())
  2109. self.assertIn("name='silly_char',", out.getvalue())
  2110. def test_makemigrations_scriptable(self):
  2111. """
  2112. With scriptable=True, log output is diverted to stderr, and only the
  2113. paths of generated migration files are written to stdout.
  2114. """
  2115. out = io.StringIO()
  2116. err = io.StringIO()
  2117. with self.temporary_migration_module(
  2118. module="migrations.migrations.test_migrations",
  2119. ) as migration_dir:
  2120. call_command(
  2121. "makemigrations",
  2122. "migrations",
  2123. scriptable=True,
  2124. stdout=out,
  2125. stderr=err,
  2126. )
  2127. initial_file = os.path.join(migration_dir, "0001_initial.py")
  2128. self.assertEqual(out.getvalue(), f"{initial_file}\n")
  2129. self.assertIn(" + Create model ModelWithCustomBase\n", err.getvalue())
  2130. @mock.patch("builtins.input", return_value="Y")
  2131. def test_makemigrations_scriptable_merge(self, mock_input):
  2132. out = io.StringIO()
  2133. err = io.StringIO()
  2134. with self.temporary_migration_module(
  2135. module="migrations.test_migrations_conflict",
  2136. ) as migration_dir:
  2137. call_command(
  2138. "makemigrations",
  2139. "migrations",
  2140. merge=True,
  2141. name="merge",
  2142. scriptable=True,
  2143. stdout=out,
  2144. stderr=err,
  2145. )
  2146. merge_file = os.path.join(migration_dir, "0003_merge.py")
  2147. self.assertEqual(out.getvalue(), f"{merge_file}\n")
  2148. self.assertIn(f"Created new merge migration {merge_file}", err.getvalue())
  2149. def test_makemigrations_failure_to_format_code(self):
  2150. self.assertFormatterFailureCaught("makemigrations", "migrations")
  2151. def test_merge_makemigrations_failure_to_format_code(self):
  2152. self.assertFormatterFailureCaught("makemigrations", "migrations", empty=True)
  2153. self.assertFormatterFailureCaught(
  2154. "makemigrations",
  2155. "migrations",
  2156. merge=True,
  2157. interactive=False,
  2158. module="migrations.test_migrations_conflict",
  2159. )
  2160. def test_makemigrations_migrations_modules_path_not_exist(self):
  2161. """
  2162. makemigrations creates migrations when specifying a custom location
  2163. for migration files using MIGRATION_MODULES if the custom path
  2164. doesn't already exist.
  2165. """
  2166. class SillyModel(models.Model):
  2167. silly_field = models.BooleanField(default=False)
  2168. class Meta:
  2169. app_label = "migrations"
  2170. out = io.StringIO()
  2171. migration_module = "migrations.test_migrations_path_doesnt_exist.foo.bar"
  2172. with self.temporary_migration_module(module=migration_module) as migration_dir:
  2173. call_command("makemigrations", "migrations", stdout=out)
  2174. # Migrations file is actually created in the expected path.
  2175. initial_file = os.path.join(migration_dir, "0001_initial.py")
  2176. self.assertTrue(os.path.exists(initial_file))
  2177. # Command output indicates the migration is created.
  2178. self.assertIn(" + Create model SillyModel", out.getvalue())
  2179. @override_settings(MIGRATION_MODULES={"migrations": "some.nonexistent.path"})
  2180. def test_makemigrations_migrations_modules_nonexistent_toplevel_package(self):
  2181. msg = (
  2182. "Could not locate an appropriate location to create migrations "
  2183. "package some.nonexistent.path. Make sure the toplevel package "
  2184. "exists and can be imported."
  2185. )
  2186. with self.assertRaisesMessage(ValueError, msg):
  2187. call_command("makemigrations", "migrations", empty=True, verbosity=0)
  2188. def test_makemigrations_interactive_by_default(self):
  2189. """
  2190. The user is prompted to merge by default if there are conflicts and
  2191. merge is True. Answer negative to differentiate it from behavior when
  2192. --noinput is specified.
  2193. """
  2194. # Monkeypatch interactive questioner to auto reject
  2195. out = io.StringIO()
  2196. with mock.patch("builtins.input", mock.Mock(return_value="N")):
  2197. with self.temporary_migration_module(
  2198. module="migrations.test_migrations_conflict"
  2199. ) as migration_dir:
  2200. call_command(
  2201. "makemigrations", "migrations", name="merge", merge=True, stdout=out
  2202. )
  2203. merge_file = os.path.join(migration_dir, "0003_merge.py")
  2204. # This will fail if interactive is False by default
  2205. self.assertFalse(os.path.exists(merge_file))
  2206. self.assertNotIn("Created new merge migration", out.getvalue())
  2207. @override_settings(
  2208. INSTALLED_APPS=[
  2209. "migrations",
  2210. "migrations.migrations_test_apps.unspecified_app_with_conflict",
  2211. ]
  2212. )
  2213. def test_makemigrations_unspecified_app_with_conflict_no_merge(self):
  2214. """
  2215. makemigrations does not raise a CommandError when an unspecified app
  2216. has conflicting migrations.
  2217. """
  2218. with self.temporary_migration_module(
  2219. module="migrations.test_migrations_no_changes"
  2220. ):
  2221. call_command("makemigrations", "migrations", merge=False, verbosity=0)
  2222. @override_settings(
  2223. INSTALLED_APPS=[
  2224. "migrations.migrations_test_apps.migrated_app",
  2225. "migrations.migrations_test_apps.unspecified_app_with_conflict",
  2226. ]
  2227. )
  2228. def test_makemigrations_unspecified_app_with_conflict_merge(self):
  2229. """
  2230. makemigrations does not create a merge for an unspecified app even if
  2231. it has conflicting migrations.
  2232. """
  2233. # Monkeypatch interactive questioner to auto accept
  2234. with mock.patch("builtins.input", mock.Mock(return_value="y")):
  2235. out = io.StringIO()
  2236. with self.temporary_migration_module(
  2237. app_label="migrated_app"
  2238. ) as migration_dir:
  2239. call_command(
  2240. "makemigrations",
  2241. "migrated_app",
  2242. name="merge",
  2243. merge=True,
  2244. interactive=True,
  2245. stdout=out,
  2246. )
  2247. merge_file = os.path.join(migration_dir, "0003_merge.py")
  2248. self.assertFalse(os.path.exists(merge_file))
  2249. self.assertIn("No conflicts detected to merge.", out.getvalue())
  2250. @override_settings(
  2251. INSTALLED_APPS=[
  2252. "migrations.migrations_test_apps.migrated_app",
  2253. "migrations.migrations_test_apps.conflicting_app_with_dependencies",
  2254. ]
  2255. )
  2256. def test_makemigrations_merge_dont_output_dependency_operations(self):
  2257. """
  2258. makemigrations --merge does not output any operations from apps that
  2259. don't belong to a given app.
  2260. """
  2261. # Monkeypatch interactive questioner to auto accept
  2262. with mock.patch("builtins.input", mock.Mock(return_value="N")):
  2263. out = io.StringIO()
  2264. with mock.patch(
  2265. "django.core.management.color.supports_color", lambda *args: False
  2266. ):
  2267. call_command(
  2268. "makemigrations",
  2269. "conflicting_app_with_dependencies",
  2270. merge=True,
  2271. interactive=True,
  2272. stdout=out,
  2273. )
  2274. self.assertEqual(
  2275. out.getvalue().lower(),
  2276. "merging conflicting_app_with_dependencies\n"
  2277. " branch 0002_conflicting_second\n"
  2278. " + create model something\n"
  2279. " branch 0002_second\n"
  2280. " - delete model tribble\n"
  2281. " - remove field silly_field from author\n"
  2282. " + add field rating to author\n"
  2283. " + create model book\n"
  2284. "\n"
  2285. "merging will only work if the operations printed above do not "
  2286. "conflict\n"
  2287. "with each other (working on different fields or models)\n"
  2288. "should these migration branches be merged? [y/n] ",
  2289. )
  2290. def test_makemigrations_with_custom_name(self):
  2291. """
  2292. makemigrations --name generate a custom migration name.
  2293. """
  2294. with self.temporary_migration_module() as migration_dir:
  2295. def cmd(migration_count, migration_name, *args):
  2296. call_command(
  2297. "makemigrations",
  2298. "migrations",
  2299. "--verbosity",
  2300. "0",
  2301. "--name",
  2302. migration_name,
  2303. *args,
  2304. )
  2305. migration_file = os.path.join(
  2306. migration_dir, "%s_%s.py" % (migration_count, migration_name)
  2307. )
  2308. # Check for existing migration file in migration folder
  2309. self.assertTrue(os.path.exists(migration_file))
  2310. with open(migration_file, encoding="utf-8") as fp:
  2311. content = fp.read()
  2312. content = content.replace(" ", "")
  2313. return content
  2314. # generate an initial migration
  2315. migration_name_0001 = "my_initial_migration"
  2316. content = cmd("0001", migration_name_0001)
  2317. self.assertIn(
  2318. "dependencies=[]" if HAS_BLACK else "dependencies=[\n]", content
  2319. )
  2320. # importlib caches os.listdir() on some platforms like macOS
  2321. # (#23850).
  2322. if hasattr(importlib, "invalidate_caches"):
  2323. importlib.invalidate_caches()
  2324. # generate an empty migration
  2325. migration_name_0002 = "my_custom_migration"
  2326. content = cmd("0002", migration_name_0002, "--empty")
  2327. if HAS_BLACK:
  2328. template_str = 'dependencies=[\n("migrations","0001_%s"),\n]'
  2329. else:
  2330. template_str = "dependencies=[\n('migrations','0001_%s'),\n]"
  2331. self.assertIn(
  2332. template_str % migration_name_0001,
  2333. content,
  2334. )
  2335. self.assertIn("operations=[]" if HAS_BLACK else "operations=[\n]", content)
  2336. def test_makemigrations_with_invalid_custom_name(self):
  2337. msg = "The migration name must be a valid Python identifier."
  2338. with self.assertRaisesMessage(CommandError, msg):
  2339. call_command(
  2340. "makemigrations", "migrations", "--name", "invalid name", "--empty"
  2341. )
  2342. def test_makemigrations_check_with_changes(self):
  2343. """
  2344. makemigrations --check should exit with a non-zero status when
  2345. there are changes to an app requiring migrations.
  2346. """
  2347. out = io.StringIO()
  2348. with self.temporary_migration_module() as tmpdir:
  2349. with self.assertRaises(SystemExit) as cm:
  2350. call_command(
  2351. "makemigrations",
  2352. "--check",
  2353. "migrations",
  2354. stdout=out,
  2355. )
  2356. self.assertEqual(os.listdir(tmpdir), ["__init__.py"])
  2357. self.assertEqual(cm.exception.code, 1)
  2358. self.assertIn("Migrations for 'migrations':", out.getvalue())
  2359. def test_makemigrations_check_no_changes(self):
  2360. """
  2361. makemigrations --check should exit with a zero status when there are no
  2362. changes.
  2363. """
  2364. out = io.StringIO()
  2365. with self.temporary_migration_module(
  2366. module="migrations.test_migrations_no_changes"
  2367. ):
  2368. call_command("makemigrations", "--check", "migrations", stdout=out)
  2369. self.assertEqual("No changes detected in app 'migrations'\n", out.getvalue())
  2370. def test_makemigrations_migration_path_output(self):
  2371. """
  2372. makemigrations should print the relative paths to the migrations unless
  2373. they are outside of the current tree, in which case the absolute path
  2374. should be shown.
  2375. """
  2376. out = io.StringIO()
  2377. apps.register_model("migrations", UnicodeModel)
  2378. with self.temporary_migration_module() as migration_dir:
  2379. call_command("makemigrations", "migrations", stdout=out)
  2380. self.assertIn(
  2381. os.path.join(migration_dir, "0001_initial.py"), out.getvalue()
  2382. )
  2383. def test_makemigrations_migration_path_output_valueerror(self):
  2384. """
  2385. makemigrations prints the absolute path if os.path.relpath() raises a
  2386. ValueError when it's impossible to obtain a relative path, e.g. on
  2387. Windows if Django is installed on a different drive than where the
  2388. migration files are created.
  2389. """
  2390. out = io.StringIO()
  2391. with self.temporary_migration_module() as migration_dir:
  2392. with mock.patch("os.path.relpath", side_effect=ValueError):
  2393. call_command("makemigrations", "migrations", stdout=out)
  2394. self.assertIn(os.path.join(migration_dir, "0001_initial.py"), out.getvalue())
  2395. def test_makemigrations_inconsistent_history(self):
  2396. """
  2397. makemigrations should raise InconsistentMigrationHistory exception if
  2398. there are some migrations applied before their dependencies.
  2399. """
  2400. recorder = MigrationRecorder(connection)
  2401. recorder.record_applied("migrations", "0002_second")
  2402. msg = (
  2403. "Migration migrations.0002_second is applied before its dependency "
  2404. "migrations.0001_initial"
  2405. )
  2406. with self.temporary_migration_module(module="migrations.test_migrations"):
  2407. with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
  2408. call_command("makemigrations")
  2409. def test_makemigrations_inconsistent_history_db_failure(self):
  2410. msg = (
  2411. "Got an error checking a consistent migration history performed "
  2412. "for database connection 'default': could not connect to server"
  2413. )
  2414. with mock.patch(
  2415. "django.db.migrations.loader.MigrationLoader.check_consistent_history",
  2416. side_effect=OperationalError("could not connect to server"),
  2417. ):
  2418. with self.temporary_migration_module():
  2419. with self.assertWarns(RuntimeWarning) as cm:
  2420. call_command("makemigrations", verbosity=0)
  2421. self.assertEqual(str(cm.warning), msg)
  2422. @mock.patch("builtins.input", return_value="1")
  2423. @mock.patch(
  2424. "django.db.migrations.questioner.sys.stdin",
  2425. mock.MagicMock(encoding=sys.getdefaultencoding()),
  2426. )
  2427. def test_makemigrations_auto_now_add_interactive(self, *args):
  2428. """
  2429. makemigrations prompts the user when adding auto_now_add to an existing
  2430. model.
  2431. """
  2432. class Entry(models.Model):
  2433. title = models.CharField(max_length=255)
  2434. creation_date = models.DateTimeField(auto_now_add=True)
  2435. class Meta:
  2436. app_label = "migrations"
  2437. input_msg = (
  2438. "It is impossible to add the field 'creation_date' with "
  2439. "'auto_now_add=True' to entry without providing a default. This "
  2440. "is because the database needs something to populate existing "
  2441. "rows.\n"
  2442. " 1) Provide a one-off default now which will be set on all "
  2443. "existing rows\n"
  2444. " 2) Quit and manually define a default value in models.py."
  2445. )
  2446. # Monkeypatch interactive questioner to auto accept
  2447. prompt_stdout = io.StringIO()
  2448. with self.temporary_migration_module(module="migrations.test_auto_now_add"):
  2449. call_command(
  2450. "makemigrations", "migrations", interactive=True, stdout=prompt_stdout
  2451. )
  2452. prompt_output = prompt_stdout.getvalue()
  2453. self.assertIn(input_msg, prompt_output)
  2454. self.assertIn("Please enter the default value as valid Python.", prompt_output)
  2455. self.assertIn(
  2456. "Accept the default 'timezone.now' by pressing 'Enter' or provide "
  2457. "another value.",
  2458. prompt_output,
  2459. )
  2460. self.assertIn("Type 'exit' to exit this prompt", prompt_output)
  2461. self.assertIn("Add field creation_date to entry", prompt_output)
  2462. @mock.patch("builtins.input", return_value="2")
  2463. def test_makemigrations_auto_now_add_interactive_quit(self, mock_input):
  2464. class Author(models.Model):
  2465. publishing_date = models.DateField(auto_now_add=True)
  2466. class Meta:
  2467. app_label = "migrations"
  2468. with self.temporary_migration_module(module="migrations.test_migrations"):
  2469. with captured_stdout():
  2470. with self.assertRaises(SystemExit):
  2471. call_command("makemigrations", "migrations", interactive=True)
  2472. def test_makemigrations_non_interactive_auto_now_add_addition(self):
  2473. """
  2474. Non-interactive makemigrations fails when a default is missing on a
  2475. new field when auto_now_add=True.
  2476. """
  2477. class Entry(models.Model):
  2478. creation_date = models.DateTimeField(auto_now_add=True)
  2479. class Meta:
  2480. app_label = "migrations"
  2481. with self.temporary_migration_module(module="migrations.test_auto_now_add"):
  2482. with self.assertRaises(SystemExit), captured_stdout() as out:
  2483. call_command("makemigrations", "migrations", interactive=False)
  2484. self.assertIn(
  2485. "Field 'creation_date' on model 'entry' not migrated: it is "
  2486. "impossible to add a field with 'auto_now_add=True' without "
  2487. "specifying a default.",
  2488. out.getvalue(),
  2489. )
  2490. def test_makemigrations_interactive_unique_callable_default_addition(self):
  2491. """
  2492. makemigrations prompts the user when adding a unique field with
  2493. a callable default.
  2494. """
  2495. class Book(models.Model):
  2496. created = models.DateTimeField(unique=True, default=timezone.now)
  2497. class Meta:
  2498. app_label = "migrations"
  2499. version = get_docs_version()
  2500. input_msg = (
  2501. f"Callable default on unique field book.created will not generate "
  2502. f"unique values upon migrating.\n"
  2503. f"Please choose how to proceed:\n"
  2504. f" 1) Continue making this migration as the first step in writing "
  2505. f"a manual migration to generate unique values described here: "
  2506. f"https://docs.djangoproject.com/en/{version}/howto/"
  2507. f"writing-migrations/#migrations-that-add-unique-fields.\n"
  2508. f" 2) Quit and edit field options in models.py.\n"
  2509. )
  2510. with self.temporary_migration_module(module="migrations.test_migrations"):
  2511. # 2 - quit.
  2512. with mock.patch("builtins.input", return_value="2"):
  2513. with captured_stdout() as out, self.assertRaises(SystemExit):
  2514. call_command("makemigrations", "migrations", interactive=True)
  2515. out_value = out.getvalue()
  2516. self.assertIn(input_msg, out_value)
  2517. self.assertNotIn("Add field created to book", out_value)
  2518. # 1 - continue.
  2519. with mock.patch("builtins.input", return_value="1"):
  2520. with captured_stdout() as out:
  2521. call_command("makemigrations", "migrations", interactive=True)
  2522. out_value = out.getvalue()
  2523. self.assertIn(input_msg, out_value)
  2524. self.assertIn("Add field created to book", out_value)
  2525. def test_makemigrations_non_interactive_unique_callable_default_addition(self):
  2526. class Book(models.Model):
  2527. created = models.DateTimeField(unique=True, default=timezone.now)
  2528. class Meta:
  2529. app_label = "migrations"
  2530. with self.temporary_migration_module(module="migrations.test_migrations"):
  2531. with captured_stdout() as out:
  2532. call_command("makemigrations", "migrations", interactive=False)
  2533. out_value = out.getvalue()
  2534. self.assertIn("Add field created to book", out_value)
  2535. @override_settings(
  2536. MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"},
  2537. )
  2538. def test_makemigrations_continues_number_sequence_after_squash(self):
  2539. with self.temporary_migration_module(
  2540. module="migrations.test_migrations_squashed"
  2541. ):
  2542. with captured_stdout() as out:
  2543. call_command(
  2544. "makemigrations",
  2545. "migrations",
  2546. interactive=False,
  2547. empty=True,
  2548. )
  2549. out_value = out.getvalue()
  2550. self.assertIn("0003_auto", out_value)
  2551. def test_makemigrations_update(self):
  2552. with self.temporary_migration_module(
  2553. module="migrations.test_migrations"
  2554. ) as migration_dir:
  2555. migration_file = os.path.join(migration_dir, "0002_second.py")
  2556. with open(migration_file) as fp:
  2557. initial_content = fp.read()
  2558. with captured_stdout() as out:
  2559. call_command("makemigrations", "migrations", update=True)
  2560. self.assertFalse(
  2561. any(
  2562. filename.startswith("0003")
  2563. for filename in os.listdir(migration_dir)
  2564. )
  2565. )
  2566. self.assertIs(os.path.exists(migration_file), False)
  2567. new_migration_file = os.path.join(
  2568. migration_dir,
  2569. "0002_delete_tribble_author_rating_modelwithcustombase_and_more.py",
  2570. )
  2571. with open(new_migration_file) as fp:
  2572. self.assertNotEqual(initial_content, fp.read())
  2573. self.assertIn(f"Deleted {migration_file}", out.getvalue())
  2574. def test_makemigrations_update_existing_name(self):
  2575. with self.temporary_migration_module(
  2576. module="migrations.test_auto_now_add"
  2577. ) as migration_dir:
  2578. migration_file = os.path.join(migration_dir, "0001_initial.py")
  2579. with open(migration_file) as fp:
  2580. initial_content = fp.read()
  2581. with captured_stdout() as out:
  2582. call_command("makemigrations", "migrations", update=True)
  2583. self.assertIs(os.path.exists(migration_file), False)
  2584. new_migration_file = os.path.join(
  2585. migration_dir,
  2586. "0001_initial_updated.py",
  2587. )
  2588. with open(new_migration_file) as fp:
  2589. self.assertNotEqual(initial_content, fp.read())
  2590. self.assertIn(f"Deleted {migration_file}", out.getvalue())
  2591. def test_makemigrations_update_custom_name(self):
  2592. custom_name = "delete_something"
  2593. with self.temporary_migration_module(
  2594. module="migrations.test_migrations"
  2595. ) as migration_dir:
  2596. old_migration_file = os.path.join(migration_dir, "0002_second.py")
  2597. with open(old_migration_file) as fp:
  2598. initial_content = fp.read()
  2599. with captured_stdout() as out:
  2600. call_command(
  2601. "makemigrations", "migrations", update=True, name=custom_name
  2602. )
  2603. self.assertFalse(
  2604. any(
  2605. filename.startswith("0003")
  2606. for filename in os.listdir(migration_dir)
  2607. )
  2608. )
  2609. self.assertIs(os.path.exists(old_migration_file), False)
  2610. new_migration_file = os.path.join(migration_dir, f"0002_{custom_name}.py")
  2611. self.assertIs(os.path.exists(new_migration_file), True)
  2612. with open(new_migration_file) as fp:
  2613. self.assertNotEqual(initial_content, fp.read())
  2614. self.assertIn(f"Deleted {old_migration_file}", out.getvalue())
  2615. def test_makemigrations_update_applied_migration(self):
  2616. recorder = MigrationRecorder(connection)
  2617. recorder.record_applied("migrations", "0001_initial")
  2618. recorder.record_applied("migrations", "0002_second")
  2619. with self.temporary_migration_module(module="migrations.test_migrations"):
  2620. msg = "Cannot update applied migration 'migrations.0002_second'."
  2621. with self.assertRaisesMessage(CommandError, msg):
  2622. call_command("makemigrations", "migrations", update=True)
  2623. def test_makemigrations_update_no_migration(self):
  2624. with self.temporary_migration_module(module="migrations.test_migrations_empty"):
  2625. msg = "App migrations has no migration, cannot update last migration."
  2626. with self.assertRaisesMessage(CommandError, msg):
  2627. call_command("makemigrations", "migrations", update=True)
  2628. def test_makemigrations_update_squash_migration(self):
  2629. with self.temporary_migration_module(
  2630. module="migrations.test_migrations_squashed"
  2631. ):
  2632. msg = "Cannot update squash migration 'migrations.0001_squashed_0002'."
  2633. with self.assertRaisesMessage(CommandError, msg):
  2634. call_command("makemigrations", "migrations", update=True)
  2635. def test_makemigrations_update_manual_porting(self):
  2636. with self.temporary_migration_module(
  2637. module="migrations.test_migrations_plan"
  2638. ) as migration_dir:
  2639. with captured_stdout() as out:
  2640. call_command("makemigrations", "migrations", update=True)
  2641. # Previous migration exists.
  2642. previous_migration_file = os.path.join(migration_dir, "0005_fifth.py")
  2643. self.assertIs(os.path.exists(previous_migration_file), True)
  2644. # New updated migration exists.
  2645. files = [f for f in os.listdir(migration_dir) if f.startswith("0005_auto")]
  2646. updated_migration_file = os.path.join(migration_dir, files[0])
  2647. self.assertIs(os.path.exists(updated_migration_file), True)
  2648. self.assertIn(
  2649. f"Updated migration {updated_migration_file} requires manual porting.\n"
  2650. f"Previous migration {previous_migration_file} was kept and must be "
  2651. f"deleted after porting functions manually.",
  2652. out.getvalue(),
  2653. )
  2654. @override_settings(
  2655. INSTALLED_APPS=[
  2656. "migrations.migrations_test_apps.alter_fk.author_app",
  2657. "migrations.migrations_test_apps.alter_fk.book_app",
  2658. ]
  2659. )
  2660. def test_makemigrations_update_dependency_migration(self):
  2661. with self.temporary_migration_module(app_label="book_app"):
  2662. msg = (
  2663. "Cannot update migration 'book_app.0001_initial' that migrations "
  2664. "'author_app.0002_alter_id' depend on."
  2665. )
  2666. with self.assertRaisesMessage(CommandError, msg):
  2667. call_command("makemigrations", "book_app", update=True)
  2668. class SquashMigrationsTests(MigrationTestBase):
  2669. """
  2670. Tests running the squashmigrations command.
  2671. """
  2672. def test_squashmigrations_squashes(self):
  2673. """
  2674. squashmigrations squashes migrations.
  2675. """
  2676. out = io.StringIO()
  2677. with self.temporary_migration_module(
  2678. module="migrations.test_migrations"
  2679. ) as migration_dir:
  2680. call_command(
  2681. "squashmigrations",
  2682. "migrations",
  2683. "0002",
  2684. interactive=False,
  2685. stdout=out,
  2686. no_color=True,
  2687. )
  2688. squashed_migration_file = os.path.join(
  2689. migration_dir, "0001_squashed_0002_second.py"
  2690. )
  2691. self.assertTrue(os.path.exists(squashed_migration_file))
  2692. self.assertEqual(
  2693. out.getvalue(),
  2694. "Will squash the following migrations:\n"
  2695. " - 0001_initial\n"
  2696. " - 0002_second\n"
  2697. "Optimizing...\n"
  2698. " Optimized from 8 operations to 2 operations.\n"
  2699. "Created new squashed migration %s\n"
  2700. " You should commit this migration but leave the old ones in place;\n"
  2701. " the new migration will be used for new installs. Once you are sure\n"
  2702. " all instances of the codebase have applied the migrations you "
  2703. "squashed,\n"
  2704. " you can delete them.\n" % squashed_migration_file,
  2705. )
  2706. def test_squashmigrations_replacement_cycle(self):
  2707. out = io.StringIO()
  2708. with self.temporary_migration_module(
  2709. module="migrations.test_migrations_squashed_loop"
  2710. ):
  2711. # Hits a squash replacement cycle check error, but the actual failure is
  2712. # dependent on the order in which the files are read on disk.
  2713. with self.assertRaisesRegex(
  2714. CommandError,
  2715. r"Cyclical squash replacement found, starting at"
  2716. r" \('migrations', '2_(squashed|auto)'\)",
  2717. ):
  2718. call_command(
  2719. "migrate", "migrations", "--plan", interactive=False, stdout=out
  2720. )
  2721. def test_squashmigrations_squashes_already_squashed(self):
  2722. out = io.StringIO()
  2723. with self.temporary_migration_module(
  2724. module="migrations.test_migrations_squashed_complex"
  2725. ):
  2726. call_command(
  2727. "squashmigrations",
  2728. "migrations",
  2729. "3_squashed_5",
  2730. "--squashed-name",
  2731. "double_squash",
  2732. stdout=out,
  2733. interactive=False,
  2734. )
  2735. loader = MigrationLoader(connection)
  2736. migration = loader.disk_migrations[("migrations", "0001_double_squash")]
  2737. # Confirm the replaces mechanism holds the squashed migration
  2738. # (and not what it squashes, as the squash operations are what
  2739. # end up being used).
  2740. self.assertEqual(
  2741. migration.replaces,
  2742. [
  2743. ("migrations", "1_auto"),
  2744. ("migrations", "2_auto"),
  2745. ("migrations", "3_squashed_5"),
  2746. ],
  2747. )
  2748. out = io.StringIO()
  2749. call_command(
  2750. "migrate", "migrations", "--plan", interactive=False, stdout=out
  2751. )
  2752. migration_plan = re.findall("migrations.(.+)\n", out.getvalue())
  2753. self.assertEqual(migration_plan, ["0001_double_squash", "6_auto", "7_auto"])
  2754. def test_squash_partially_applied(self):
  2755. """
  2756. Replacement migrations are partially applied. Then we squash again and
  2757. verify that only unapplied migrations will be applied by "migrate".
  2758. """
  2759. out = io.StringIO()
  2760. with self.temporary_migration_module(
  2761. module="migrations.test_migrations_squashed_partially_applied"
  2762. ):
  2763. # Apply first 2 migrations.
  2764. call_command("migrate", "migrations", "0002", interactive=False, stdout=out)
  2765. # Squash the 2 migrations, that we just applied + 1 more.
  2766. call_command(
  2767. "squashmigrations",
  2768. "migrations",
  2769. "0001",
  2770. "0003",
  2771. "--squashed-name",
  2772. "squashed_0001_0003",
  2773. stdout=out,
  2774. interactive=False,
  2775. )
  2776. # Update the 4th migration to depend on the squash(replacement) migration.
  2777. loader = MigrationLoader(connection)
  2778. migration = loader.disk_migrations[
  2779. ("migrations", "0004_remove_mymodel1_field_1_mymodel1_field_3_and_more")
  2780. ]
  2781. migration.dependencies = [("migrations", "0001_squashed_0001_0003")]
  2782. writer = MigrationWriter(migration)
  2783. with open(writer.path, "w", encoding="utf-8") as fh:
  2784. fh.write(writer.as_string())
  2785. # Squash the squash(replacement) migration with the 4th migration.
  2786. call_command(
  2787. "squashmigrations",
  2788. "migrations",
  2789. "0001_squashed_0001_0003",
  2790. "0004",
  2791. "--squashed-name",
  2792. "squashed_0001_0004",
  2793. stdout=out,
  2794. interactive=False,
  2795. )
  2796. loader = MigrationLoader(connection)
  2797. migration = loader.disk_migrations[
  2798. ("migrations", "0001_squashed_0001_0004")
  2799. ]
  2800. self.assertEqual(
  2801. migration.replaces,
  2802. [
  2803. ("migrations", "0001_squashed_0001_0003"),
  2804. (
  2805. "migrations",
  2806. "0004_remove_mymodel1_field_1_mymodel1_field_3_and_more",
  2807. ),
  2808. ],
  2809. )
  2810. # Verify that only unapplied migrations will be applied.
  2811. out = io.StringIO()
  2812. call_command(
  2813. "migrate", "migrations", "--plan", interactive=False, stdout=out
  2814. )
  2815. migration_plan = re.findall("migrations.(.+)\n", out.getvalue())
  2816. self.assertEqual(
  2817. migration_plan,
  2818. [
  2819. "0003_alter_mymodel2_unique_together",
  2820. "0004_remove_mymodel1_field_1_mymodel1_field_3_and_more",
  2821. ],
  2822. )
  2823. def test_double_replaced_migrations_are_recorded(self):
  2824. """
  2825. All recursively replaced migrations should be recorded/unrecorded, when
  2826. migrating an app with double squashed migrations.
  2827. """
  2828. out = io.StringIO()
  2829. with self.temporary_migration_module(
  2830. module="migrations.test_migrations_squashed_double"
  2831. ):
  2832. recorder = MigrationRecorder(connection)
  2833. applied_app_labels = [
  2834. app_label for app_label, _ in recorder.applied_migrations()
  2835. ]
  2836. self.assertNotIn("migrations", applied_app_labels)
  2837. call_command(
  2838. "migrate", "migrations", "--plan", interactive=False, stdout=out
  2839. )
  2840. migration_plan = re.findall("migrations.(.+)\n", out.getvalue())
  2841. # Only the top-level replacement migration should be applied.
  2842. self.assertEqual(migration_plan, ["0005_squashed_0003_and_0004"])
  2843. call_command("migrate", "migrations", interactive=False, verbosity=0)
  2844. applied_migrations = recorder.applied_migrations()
  2845. # Make sure all replaced migrations are recorded.
  2846. self.assertIn(("migrations", "0001_initial"), applied_migrations)
  2847. self.assertIn(("migrations", "0002_auto"), applied_migrations)
  2848. self.assertIn(
  2849. ("migrations", "0003_squashed_0001_and_0002"), applied_migrations
  2850. )
  2851. self.assertIn(("migrations", "0004_auto"), applied_migrations)
  2852. self.assertIn(
  2853. ("migrations", "0005_squashed_0003_and_0004"), applied_migrations
  2854. )
  2855. # Unapply all migrations from this app.
  2856. call_command(
  2857. "migrate", "migrations", "zero", interactive=False, verbosity=0
  2858. )
  2859. applied_app_labels = [
  2860. app_label for app_label, _ in recorder.applied_migrations()
  2861. ]
  2862. self.assertNotIn("migrations", applied_app_labels)
  2863. def test_squashmigrations_initial_attribute(self):
  2864. with self.temporary_migration_module(
  2865. module="migrations.test_migrations"
  2866. ) as migration_dir:
  2867. call_command(
  2868. "squashmigrations", "migrations", "0002", interactive=False, verbosity=0
  2869. )
  2870. squashed_migration_file = os.path.join(
  2871. migration_dir, "0001_squashed_0002_second.py"
  2872. )
  2873. with open(squashed_migration_file, encoding="utf-8") as fp:
  2874. content = fp.read()
  2875. self.assertIn("initial = True", content)
  2876. def test_squashmigrations_optimizes(self):
  2877. """
  2878. squashmigrations optimizes operations.
  2879. """
  2880. out = io.StringIO()
  2881. with self.temporary_migration_module(module="migrations.test_migrations"):
  2882. call_command(
  2883. "squashmigrations",
  2884. "migrations",
  2885. "0002",
  2886. interactive=False,
  2887. verbosity=1,
  2888. stdout=out,
  2889. )
  2890. self.assertIn("Optimized from 8 operations to 2 operations.", out.getvalue())
  2891. def test_ticket_23799_squashmigrations_no_optimize(self):
  2892. """
  2893. squashmigrations --no-optimize doesn't optimize operations.
  2894. """
  2895. out = io.StringIO()
  2896. with self.temporary_migration_module(module="migrations.test_migrations"):
  2897. call_command(
  2898. "squashmigrations",
  2899. "migrations",
  2900. "0002",
  2901. interactive=False,
  2902. verbosity=1,
  2903. no_optimize=True,
  2904. stdout=out,
  2905. )
  2906. self.assertIn("Skipping optimization", out.getvalue())
  2907. def test_squashmigrations_valid_start(self):
  2908. """
  2909. squashmigrations accepts a starting migration.
  2910. """
  2911. out = io.StringIO()
  2912. with self.temporary_migration_module(
  2913. module="migrations.test_migrations_no_changes"
  2914. ) as migration_dir:
  2915. call_command(
  2916. "squashmigrations",
  2917. "migrations",
  2918. "0002",
  2919. "0003",
  2920. interactive=False,
  2921. verbosity=1,
  2922. stdout=out,
  2923. )
  2924. squashed_migration_file = os.path.join(
  2925. migration_dir, "0002_second_squashed_0003_third.py"
  2926. )
  2927. with open(squashed_migration_file, encoding="utf-8") as fp:
  2928. content = fp.read()
  2929. if HAS_BLACK:
  2930. test_str = ' ("migrations", "0001_initial")'
  2931. else:
  2932. test_str = " ('migrations', '0001_initial')"
  2933. self.assertIn(test_str, content)
  2934. self.assertNotIn("initial = True", content)
  2935. out = out.getvalue()
  2936. self.assertNotIn(" - 0001_initial", out)
  2937. self.assertIn(" - 0002_second", out)
  2938. self.assertIn(" - 0003_third", out)
  2939. def test_squashmigrations_invalid_start(self):
  2940. """
  2941. squashmigrations doesn't accept a starting migration after the ending migration.
  2942. """
  2943. with self.temporary_migration_module(
  2944. module="migrations.test_migrations_no_changes"
  2945. ):
  2946. msg = (
  2947. "The migration 'migrations.0003_third' cannot be found. Maybe "
  2948. "it comes after the migration 'migrations.0002_second'"
  2949. )
  2950. with self.assertRaisesMessage(CommandError, msg):
  2951. call_command(
  2952. "squashmigrations",
  2953. "migrations",
  2954. "0003",
  2955. "0002",
  2956. interactive=False,
  2957. verbosity=0,
  2958. )
  2959. def test_squashed_name_with_start_migration_name(self):
  2960. """--squashed-name specifies the new migration's name."""
  2961. squashed_name = "squashed_name"
  2962. with self.temporary_migration_module(
  2963. module="migrations.test_migrations"
  2964. ) as migration_dir:
  2965. call_command(
  2966. "squashmigrations",
  2967. "migrations",
  2968. "0001",
  2969. "0002",
  2970. squashed_name=squashed_name,
  2971. interactive=False,
  2972. verbosity=0,
  2973. )
  2974. squashed_migration_file = os.path.join(
  2975. migration_dir, "0001_%s.py" % squashed_name
  2976. )
  2977. self.assertTrue(os.path.exists(squashed_migration_file))
  2978. def test_squashed_name_without_start_migration_name(self):
  2979. """--squashed-name also works if a start migration is omitted."""
  2980. squashed_name = "squashed_name"
  2981. with self.temporary_migration_module(
  2982. module="migrations.test_migrations"
  2983. ) as migration_dir:
  2984. call_command(
  2985. "squashmigrations",
  2986. "migrations",
  2987. "0001",
  2988. squashed_name=squashed_name,
  2989. interactive=False,
  2990. verbosity=0,
  2991. )
  2992. squashed_migration_file = os.path.join(
  2993. migration_dir, "0001_%s.py" % squashed_name
  2994. )
  2995. self.assertTrue(os.path.exists(squashed_migration_file))
  2996. def test_squashed_name_exists(self):
  2997. msg = "Migration 0001_initial already exists. Use a different name."
  2998. with self.temporary_migration_module(module="migrations.test_migrations"):
  2999. with self.assertRaisesMessage(CommandError, msg):
  3000. call_command(
  3001. "squashmigrations",
  3002. "migrations",
  3003. "0001",
  3004. "0002",
  3005. squashed_name="initial",
  3006. interactive=False,
  3007. verbosity=0,
  3008. )
  3009. def test_squashmigrations_manual_porting(self):
  3010. out = io.StringIO()
  3011. with self.temporary_migration_module(
  3012. module="migrations.test_migrations_manual_porting",
  3013. ) as migration_dir:
  3014. call_command(
  3015. "squashmigrations",
  3016. "migrations",
  3017. "0002",
  3018. interactive=False,
  3019. stdout=out,
  3020. no_color=True,
  3021. )
  3022. squashed_migration_file = os.path.join(
  3023. migration_dir,
  3024. "0001_squashed_0002_second.py",
  3025. )
  3026. self.assertTrue(os.path.exists(squashed_migration_file))
  3027. black_warning = ""
  3028. if HAS_BLACK:
  3029. black_warning = (
  3030. "Squashed migration couldn't be formatted using the "
  3031. '"black" command. You can call it manually.\n'
  3032. )
  3033. self.assertEqual(
  3034. out.getvalue(),
  3035. f"Will squash the following migrations:\n"
  3036. f" - 0001_initial\n"
  3037. f" - 0002_second\n"
  3038. f"Optimizing...\n"
  3039. f" No optimizations possible.\n"
  3040. f"Created new squashed migration {squashed_migration_file}\n"
  3041. f" You should commit this migration but leave the old ones in place;\n"
  3042. f" the new migration will be used for new installs. Once you are sure\n"
  3043. f" all instances of the codebase have applied the migrations you "
  3044. f"squashed,\n"
  3045. f" you can delete them.\n"
  3046. f"Manual porting required\n"
  3047. f" Your migrations contained functions that must be manually copied "
  3048. f"over,\n"
  3049. f" as we could not safely copy their implementation.\n"
  3050. f" See the comment at the top of the squashed migration for details.\n"
  3051. + black_warning,
  3052. )
  3053. def test_failure_to_format_code(self):
  3054. self.assertFormatterFailureCaught(
  3055. "squashmigrations", "migrations", "0002", interactive=False
  3056. )
  3057. class AppLabelErrorTests(TestCase):
  3058. """
  3059. This class inherits TestCase because MigrationTestBase uses
  3060. `available_apps = ['migrations']` which means that it's the only installed
  3061. app. 'django.contrib.auth' must be in INSTALLED_APPS for some of these
  3062. tests.
  3063. """
  3064. nonexistent_app_error = "No installed app with label 'nonexistent_app'."
  3065. did_you_mean_auth_error = (
  3066. "No installed app with label 'django.contrib.auth'. Did you mean 'auth'?"
  3067. )
  3068. def test_makemigrations_nonexistent_app_label(self):
  3069. err = io.StringIO()
  3070. with self.assertRaises(SystemExit):
  3071. call_command("makemigrations", "nonexistent_app", stderr=err)
  3072. self.assertIn(self.nonexistent_app_error, err.getvalue())
  3073. def test_makemigrations_app_name_specified_as_label(self):
  3074. err = io.StringIO()
  3075. with self.assertRaises(SystemExit):
  3076. call_command("makemigrations", "django.contrib.auth", stderr=err)
  3077. self.assertIn(self.did_you_mean_auth_error, err.getvalue())
  3078. def test_migrate_nonexistent_app_label(self):
  3079. with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
  3080. call_command("migrate", "nonexistent_app")
  3081. def test_migrate_app_name_specified_as_label(self):
  3082. with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
  3083. call_command("migrate", "django.contrib.auth")
  3084. def test_showmigrations_nonexistent_app_label(self):
  3085. err = io.StringIO()
  3086. with self.assertRaises(SystemExit):
  3087. call_command("showmigrations", "nonexistent_app", stderr=err)
  3088. self.assertIn(self.nonexistent_app_error, err.getvalue())
  3089. def test_showmigrations_app_name_specified_as_label(self):
  3090. err = io.StringIO()
  3091. with self.assertRaises(SystemExit):
  3092. call_command("showmigrations", "django.contrib.auth", stderr=err)
  3093. self.assertIn(self.did_you_mean_auth_error, err.getvalue())
  3094. def test_sqlmigrate_nonexistent_app_label(self):
  3095. with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
  3096. call_command("sqlmigrate", "nonexistent_app", "0002")
  3097. def test_sqlmigrate_app_name_specified_as_label(self):
  3098. with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
  3099. call_command("sqlmigrate", "django.contrib.auth", "0002")
  3100. def test_squashmigrations_nonexistent_app_label(self):
  3101. with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
  3102. call_command("squashmigrations", "nonexistent_app", "0002")
  3103. def test_squashmigrations_app_name_specified_as_label(self):
  3104. with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
  3105. call_command("squashmigrations", "django.contrib.auth", "0002")
  3106. def test_optimizemigration_nonexistent_app_label(self):
  3107. with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
  3108. call_command("optimizemigration", "nonexistent_app", "0002")
  3109. def test_optimizemigration_app_name_specified_as_label(self):
  3110. with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
  3111. call_command("optimizemigration", "django.contrib.auth", "0002")
  3112. class OptimizeMigrationTests(MigrationTestBase):
  3113. def test_no_optimization_possible(self):
  3114. out = io.StringIO()
  3115. with self.temporary_migration_module(
  3116. module="migrations.test_migrations"
  3117. ) as migration_dir:
  3118. call_command(
  3119. "optimizemigration", "migrations", "0002", stdout=out, no_color=True
  3120. )
  3121. migration_file = os.path.join(migration_dir, "0002_second.py")
  3122. self.assertTrue(os.path.exists(migration_file))
  3123. call_command(
  3124. "optimizemigration",
  3125. "migrations",
  3126. "0002",
  3127. stdout=out,
  3128. no_color=True,
  3129. verbosity=0,
  3130. )
  3131. self.assertEqual(out.getvalue(), "No optimizations possible.\n")
  3132. def test_optimization(self):
  3133. out = io.StringIO()
  3134. with self.temporary_migration_module(
  3135. module="migrations.test_migrations"
  3136. ) as migration_dir:
  3137. call_command(
  3138. "optimizemigration", "migrations", "0001", stdout=out, no_color=True
  3139. )
  3140. initial_migration_file = os.path.join(migration_dir, "0001_initial.py")
  3141. self.assertTrue(os.path.exists(initial_migration_file))
  3142. with open(initial_migration_file) as fp:
  3143. content = fp.read()
  3144. self.assertIn(
  3145. (
  3146. '("bool", models.BooleanField'
  3147. if HAS_BLACK
  3148. else "('bool', models.BooleanField"
  3149. ),
  3150. content,
  3151. )
  3152. self.assertEqual(
  3153. out.getvalue(),
  3154. f"Optimizing from 4 operations to 2 operations.\n"
  3155. f"Optimized migration {initial_migration_file}\n",
  3156. )
  3157. def test_optimization_no_verbosity(self):
  3158. out = io.StringIO()
  3159. with self.temporary_migration_module(
  3160. module="migrations.test_migrations"
  3161. ) as migration_dir:
  3162. call_command(
  3163. "optimizemigration",
  3164. "migrations",
  3165. "0001",
  3166. stdout=out,
  3167. no_color=True,
  3168. verbosity=0,
  3169. )
  3170. initial_migration_file = os.path.join(migration_dir, "0001_initial.py")
  3171. self.assertTrue(os.path.exists(initial_migration_file))
  3172. with open(initial_migration_file) as fp:
  3173. content = fp.read()
  3174. self.assertIn(
  3175. (
  3176. '("bool", models.BooleanField'
  3177. if HAS_BLACK
  3178. else "('bool', models.BooleanField"
  3179. ),
  3180. content,
  3181. )
  3182. self.assertEqual(out.getvalue(), "")
  3183. def test_creates_replace_migration_manual_porting(self):
  3184. out = io.StringIO()
  3185. with self.temporary_migration_module(
  3186. module="migrations.test_migrations_manual_porting"
  3187. ) as migration_dir:
  3188. call_command(
  3189. "optimizemigration", "migrations", "0003", stdout=out, no_color=True
  3190. )
  3191. optimized_migration_file = os.path.join(
  3192. migration_dir, "0003_third_optimized.py"
  3193. )
  3194. self.assertTrue(os.path.exists(optimized_migration_file))
  3195. with open(optimized_migration_file) as fp:
  3196. content = fp.read()
  3197. self.assertIn("replaces = [", content)
  3198. black_warning = ""
  3199. if HAS_BLACK:
  3200. black_warning = (
  3201. "Optimized migration couldn't be formatted using the "
  3202. '"black" command. You can call it manually.\n'
  3203. )
  3204. self.assertEqual(
  3205. out.getvalue(),
  3206. "Optimizing from 3 operations to 2 operations.\n"
  3207. "Manual porting required\n"
  3208. " Your migrations contained functions that must be manually copied over,\n"
  3209. " as we could not safely copy their implementation.\n"
  3210. " See the comment at the top of the optimized migration for details.\n"
  3211. + black_warning
  3212. + f"Optimized migration {optimized_migration_file}\n",
  3213. )
  3214. def test_fails_squash_migration_manual_porting(self):
  3215. out = io.StringIO()
  3216. with self.temporary_migration_module(
  3217. module="migrations.test_migrations_manual_porting"
  3218. ) as migration_dir:
  3219. version = get_docs_version()
  3220. msg = (
  3221. f"Migration will require manual porting but is already a squashed "
  3222. f"migration.\nTransition to a normal migration first: "
  3223. f"https://docs.djangoproject.com/en/{version}/topics/migrations/"
  3224. f"#squashing-migrations"
  3225. )
  3226. with self.assertRaisesMessage(CommandError, msg):
  3227. call_command("optimizemigration", "migrations", "0004", stdout=out)
  3228. optimized_migration_file = os.path.join(
  3229. migration_dir, "0004_fourth_optimized.py"
  3230. )
  3231. self.assertFalse(os.path.exists(optimized_migration_file))
  3232. self.assertEqual(
  3233. out.getvalue(), "Optimizing from 3 operations to 2 operations.\n"
  3234. )
  3235. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  3236. def test_optimizemigration_check(self):
  3237. with self.assertRaises(SystemExit):
  3238. call_command(
  3239. "optimizemigration", "--check", "migrations", "0001", verbosity=0
  3240. )
  3241. call_command("optimizemigration", "--check", "migrations", "0002", verbosity=0)
  3242. @override_settings(
  3243. INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app_simple"],
  3244. )
  3245. def test_app_without_migrations(self):
  3246. msg = "App 'unmigrated_app_simple' does not have migrations."
  3247. with self.assertRaisesMessage(CommandError, msg):
  3248. call_command("optimizemigration", "unmigrated_app_simple", "0001")
  3249. @override_settings(
  3250. MIGRATION_MODULES={"migrations": "migrations.test_migrations_clashing_prefix"},
  3251. )
  3252. def test_ambigious_prefix(self):
  3253. msg = (
  3254. "More than one migration matches 'a' in app 'migrations'. Please "
  3255. "be more specific."
  3256. )
  3257. with self.assertRaisesMessage(CommandError, msg):
  3258. call_command("optimizemigration", "migrations", "a")
  3259. @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
  3260. def test_unknown_prefix(self):
  3261. msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'."
  3262. with self.assertRaisesMessage(CommandError, msg):
  3263. call_command("optimizemigration", "migrations", "nonexistent")
  3264. def test_failure_to_format_code(self):
  3265. self.assertFormatterFailureCaught("optimizemigration", "migrations", "0001")
  3266. class CustomMigrationCommandTests(MigrationTestBase):
  3267. @override_settings(
  3268. MIGRATION_MODULES={"migrations": "migrations.test_migrations"},
  3269. INSTALLED_APPS=["migrations.migrations_test_apps.migrated_app"],
  3270. )
  3271. @isolate_apps("migrations.migrations_test_apps.migrated_app")
  3272. def test_makemigrations_custom_autodetector(self):
  3273. class CustomAutodetector(MigrationAutodetector):
  3274. def changes(self, *args, **kwargs):
  3275. return []
  3276. class CustomMakeMigrationsCommand(MakeMigrationsCommand):
  3277. autodetector = CustomAutodetector
  3278. class NewModel(models.Model):
  3279. class Meta:
  3280. app_label = "migrated_app"
  3281. out = io.StringIO()
  3282. command = CustomMakeMigrationsCommand(stdout=out)
  3283. call_command(command, "migrated_app", stdout=out)
  3284. self.assertIn("No changes detected", out.getvalue())
  3285. @override_settings(INSTALLED_APPS=["migrations.migrations_test_apps.migrated_app"])
  3286. @isolate_apps("migrations.migrations_test_apps.migrated_app")
  3287. def test_migrate_custom_autodetector(self):
  3288. class CustomAutodetector(MigrationAutodetector):
  3289. def changes(self, *args, **kwargs):
  3290. return []
  3291. class CustomMigrateCommand(MigrateCommand):
  3292. autodetector = CustomAutodetector
  3293. class NewModel(models.Model):
  3294. class Meta:
  3295. app_label = "migrated_app"
  3296. out = io.StringIO()
  3297. command = CustomMigrateCommand(stdout=out)
  3298. out = io.StringIO()
  3299. try:
  3300. call_command(command, verbosity=0)
  3301. call_command(command, stdout=out, no_color=True)
  3302. command_stdout = out.getvalue().lower()
  3303. self.assertEqual(
  3304. "operations to perform:\n"
  3305. " apply all migrations: migrated_app\n"
  3306. "running migrations:\n"
  3307. " no migrations to apply.\n",
  3308. command_stdout,
  3309. )
  3310. finally:
  3311. call_command(command, "migrated_app", "zero", verbosity=0)