test_commands.py 135 KB

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