tests.py 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063
  1. """
  2. A series of tests to establish that the command-line management tools work as
  3. advertised - especially with regards to the handling of the
  4. DJANGO_SETTINGS_MODULE and default settings.py files.
  5. """
  6. import os
  7. import re
  8. import shutil
  9. import socket
  10. import stat
  11. import subprocess
  12. import sys
  13. import tempfile
  14. import unittest
  15. from io import StringIO
  16. from unittest import mock
  17. from django import conf, get_version
  18. from django.conf import settings
  19. from django.core.management import (
  20. BaseCommand,
  21. CommandError,
  22. call_command,
  23. color,
  24. execute_from_command_line,
  25. )
  26. from django.core.management.commands.loaddata import Command as LoaddataCommand
  27. from django.core.management.commands.runserver import Command as RunserverCommand
  28. from django.core.management.commands.testserver import Command as TestserverCommand
  29. from django.db import ConnectionHandler, connection
  30. from django.db.migrations.recorder import MigrationRecorder
  31. from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings
  32. from django.test.utils import captured_stderr, captured_stdout
  33. from django.urls import path
  34. from django.views.static import serve
  35. from . import urls
  36. custom_templates_dir = os.path.join(os.path.dirname(__file__), "custom_templates")
  37. SYSTEM_CHECK_MSG = "System check identified no issues"
  38. HAS_BLACK = shutil.which("black")
  39. class AdminScriptTestCase(SimpleTestCase):
  40. def setUp(self):
  41. tmpdir = tempfile.TemporaryDirectory()
  42. self.addCleanup(tmpdir.cleanup)
  43. # os.path.realpath() is required for temporary directories on macOS,
  44. # where `/var` is a symlink to `/private/var`.
  45. self.test_dir = os.path.realpath(os.path.join(tmpdir.name, "test_project"))
  46. os.mkdir(self.test_dir)
  47. def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None):
  48. if is_dir:
  49. settings_dir = os.path.join(self.test_dir, filename)
  50. os.mkdir(settings_dir)
  51. settings_file_path = os.path.join(settings_dir, "__init__.py")
  52. else:
  53. settings_file_path = os.path.join(self.test_dir, filename)
  54. with open(settings_file_path, "w") as settings_file:
  55. settings_file.write(
  56. "# Settings file automatically generated by admin_scripts test case\n"
  57. )
  58. if extra:
  59. settings_file.write("%s\n" % extra)
  60. exports = [
  61. "DATABASES",
  62. "DEFAULT_AUTO_FIELD",
  63. "ROOT_URLCONF",
  64. "SECRET_KEY",
  65. "USE_TZ",
  66. ]
  67. for s in exports:
  68. if hasattr(settings, s):
  69. o = getattr(settings, s)
  70. if not isinstance(o, (dict, tuple, list)):
  71. o = "'%s'" % o
  72. settings_file.write("%s = %s\n" % (s, o))
  73. if apps is None:
  74. apps = [
  75. "django.contrib.auth",
  76. "django.contrib.contenttypes",
  77. "admin_scripts",
  78. ]
  79. settings_file.write("INSTALLED_APPS = %s\n" % apps)
  80. if sdict:
  81. for k, v in sdict.items():
  82. settings_file.write("%s = %s\n" % (k, v))
  83. def _ext_backend_paths(self):
  84. """
  85. Returns the paths for any external backend packages.
  86. """
  87. paths = []
  88. for backend in settings.DATABASES.values():
  89. package = backend["ENGINE"].split(".")[0]
  90. if package != "django":
  91. backend_pkg = __import__(package)
  92. backend_dir = os.path.dirname(backend_pkg.__file__)
  93. paths.append(os.path.dirname(backend_dir))
  94. return paths
  95. def run_test(self, args, settings_file=None, apps=None, umask=-1):
  96. base_dir = os.path.dirname(self.test_dir)
  97. # The base dir for Django's tests is one level up.
  98. tests_dir = os.path.dirname(os.path.dirname(__file__))
  99. # The base dir for Django is one level above the test dir. We don't use
  100. # `import django` to figure that out, so we don't pick up a Django
  101. # from site-packages or similar.
  102. django_dir = os.path.dirname(tests_dir)
  103. ext_backend_base_dirs = self._ext_backend_paths()
  104. # Define a temporary environment for the subprocess
  105. test_environ = os.environ.copy()
  106. # Set the test environment
  107. if settings_file:
  108. test_environ["DJANGO_SETTINGS_MODULE"] = settings_file
  109. elif "DJANGO_SETTINGS_MODULE" in test_environ:
  110. del test_environ["DJANGO_SETTINGS_MODULE"]
  111. python_path = [base_dir, django_dir, tests_dir]
  112. python_path.extend(ext_backend_base_dirs)
  113. test_environ["PYTHONPATH"] = os.pathsep.join(python_path)
  114. test_environ["PYTHONWARNINGS"] = ""
  115. p = subprocess.run(
  116. [sys.executable, *args],
  117. capture_output=True,
  118. cwd=self.test_dir,
  119. env=test_environ,
  120. text=True,
  121. umask=umask,
  122. )
  123. return p.stdout, p.stderr
  124. def run_django_admin(self, args, settings_file=None, umask=-1):
  125. return self.run_test(["-m", "django", *args], settings_file, umask=umask)
  126. def run_manage(self, args, settings_file=None, manage_py=None):
  127. template_manage_py = (
  128. os.path.join(os.path.dirname(__file__), manage_py)
  129. if manage_py
  130. else os.path.join(
  131. os.path.dirname(conf.__file__), "project_template", "manage.py-tpl"
  132. )
  133. )
  134. test_manage_py = os.path.join(self.test_dir, "manage.py")
  135. shutil.copyfile(template_manage_py, test_manage_py)
  136. with open(test_manage_py) as fp:
  137. manage_py_contents = fp.read()
  138. manage_py_contents = manage_py_contents.replace(
  139. "{{ project_name }}", "test_project"
  140. )
  141. with open(test_manage_py, "w") as fp:
  142. fp.write(manage_py_contents)
  143. return self.run_test(["./manage.py", *args], settings_file)
  144. def assertNoOutput(self, stream):
  145. "Utility assertion: assert that the given stream is empty"
  146. self.assertEqual(
  147. len(stream), 0, "Stream should be empty: actually contains '%s'" % stream
  148. )
  149. def assertOutput(self, stream, msg, regex=False):
  150. "Utility assertion: assert that the given message exists in the output"
  151. if regex:
  152. self.assertIsNotNone(
  153. re.search(msg, stream),
  154. "'%s' does not match actual output text '%s'" % (msg, stream),
  155. )
  156. else:
  157. self.assertIn(
  158. msg,
  159. stream,
  160. "'%s' does not match actual output text '%s'" % (msg, stream),
  161. )
  162. def assertNotInOutput(self, stream, msg):
  163. "Utility assertion: assert that the given message doesn't exist in the output"
  164. self.assertNotIn(
  165. msg, stream, "'%s' matches actual output text '%s'" % (msg, stream)
  166. )
  167. ##########################################################################
  168. # DJANGO ADMIN TESTS
  169. # This first series of test classes checks the environment processing
  170. # of the django-admin.
  171. ##########################################################################
  172. class DjangoAdminNoSettings(AdminScriptTestCase):
  173. "A series of tests for django-admin when there is no settings.py file."
  174. def test_builtin_command(self):
  175. """
  176. no settings: django-admin builtin commands fail with an error when no
  177. settings provided.
  178. """
  179. args = ["check", "admin_scripts"]
  180. out, err = self.run_django_admin(args)
  181. self.assertNoOutput(out)
  182. self.assertOutput(err, "settings are not configured")
  183. def test_builtin_with_bad_settings(self):
  184. """
  185. no settings: django-admin builtin commands fail if settings file (from
  186. argument) doesn't exist.
  187. """
  188. args = ["check", "--settings=bad_settings", "admin_scripts"]
  189. out, err = self.run_django_admin(args)
  190. self.assertNoOutput(out)
  191. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  192. def test_builtin_with_bad_environment(self):
  193. """
  194. no settings: django-admin builtin commands fail if settings file (from
  195. environment) doesn't exist.
  196. """
  197. args = ["check", "admin_scripts"]
  198. out, err = self.run_django_admin(args, "bad_settings")
  199. self.assertNoOutput(out)
  200. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  201. def test_commands_with_invalid_settings(self):
  202. """
  203. Commands that don't require settings succeed if the settings file
  204. doesn't exist.
  205. """
  206. args = ["startproject"]
  207. out, err = self.run_django_admin(args, settings_file="bad_settings")
  208. self.assertNoOutput(out)
  209. self.assertOutput(err, "You must provide a project name", regex=True)
  210. class DjangoAdminDefaultSettings(AdminScriptTestCase):
  211. """
  212. A series of tests for django-admin when using a settings.py file that
  213. contains the test application.
  214. """
  215. def setUp(self):
  216. super().setUp()
  217. self.write_settings("settings.py")
  218. def test_builtin_command(self):
  219. """
  220. default: django-admin builtin commands fail with an error when no
  221. settings provided.
  222. """
  223. args = ["check", "admin_scripts"]
  224. out, err = self.run_django_admin(args)
  225. self.assertNoOutput(out)
  226. self.assertOutput(err, "settings are not configured")
  227. def test_builtin_with_settings(self):
  228. """
  229. default: django-admin builtin commands succeed if settings are provided
  230. as argument.
  231. """
  232. args = ["check", "--settings=test_project.settings", "admin_scripts"]
  233. out, err = self.run_django_admin(args)
  234. self.assertNoOutput(err)
  235. self.assertOutput(out, SYSTEM_CHECK_MSG)
  236. def test_builtin_with_environment(self):
  237. """
  238. default: django-admin builtin commands succeed if settings are provided
  239. in the environment.
  240. """
  241. args = ["check", "admin_scripts"]
  242. out, err = self.run_django_admin(args, "test_project.settings")
  243. self.assertNoOutput(err)
  244. self.assertOutput(out, SYSTEM_CHECK_MSG)
  245. def test_builtin_with_bad_settings(self):
  246. """
  247. default: django-admin builtin commands fail if settings file (from
  248. argument) doesn't exist.
  249. """
  250. args = ["check", "--settings=bad_settings", "admin_scripts"]
  251. out, err = self.run_django_admin(args)
  252. self.assertNoOutput(out)
  253. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  254. def test_builtin_with_bad_environment(self):
  255. """
  256. default: django-admin builtin commands fail if settings file (from
  257. environment) doesn't exist.
  258. """
  259. args = ["check", "admin_scripts"]
  260. out, err = self.run_django_admin(args, "bad_settings")
  261. self.assertNoOutput(out)
  262. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  263. def test_custom_command(self):
  264. """
  265. default: django-admin can't execute user commands if it isn't provided
  266. settings.
  267. """
  268. args = ["noargs_command"]
  269. out, err = self.run_django_admin(args)
  270. self.assertNoOutput(out)
  271. self.assertOutput(err, "No Django settings specified")
  272. self.assertOutput(err, "Unknown command: 'noargs_command'")
  273. def test_custom_command_with_settings(self):
  274. """
  275. default: django-admin can execute user commands if settings are
  276. provided as argument.
  277. """
  278. args = ["noargs_command", "--settings=test_project.settings"]
  279. out, err = self.run_django_admin(args)
  280. self.assertNoOutput(err)
  281. self.assertOutput(out, "EXECUTE: noargs_command")
  282. def test_custom_command_with_environment(self):
  283. """
  284. default: django-admin can execute user commands if settings are
  285. provided in environment.
  286. """
  287. args = ["noargs_command"]
  288. out, err = self.run_django_admin(args, "test_project.settings")
  289. self.assertNoOutput(err)
  290. self.assertOutput(out, "EXECUTE: noargs_command")
  291. class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
  292. """
  293. A series of tests for django-admin when using a settings.py file that
  294. contains the test application specified using a full path.
  295. """
  296. def setUp(self):
  297. super().setUp()
  298. self.write_settings(
  299. "settings.py",
  300. [
  301. "django.contrib.auth",
  302. "django.contrib.contenttypes",
  303. "admin_scripts",
  304. "admin_scripts.complex_app",
  305. ],
  306. )
  307. def test_builtin_command(self):
  308. """
  309. fulldefault: django-admin builtin commands fail with an error when no
  310. settings provided.
  311. """
  312. args = ["check", "admin_scripts"]
  313. out, err = self.run_django_admin(args)
  314. self.assertNoOutput(out)
  315. self.assertOutput(err, "settings are not configured")
  316. def test_builtin_with_settings(self):
  317. """
  318. fulldefault: django-admin builtin commands succeed if a settings file
  319. is provided.
  320. """
  321. args = ["check", "--settings=test_project.settings", "admin_scripts"]
  322. out, err = self.run_django_admin(args)
  323. self.assertNoOutput(err)
  324. self.assertOutput(out, SYSTEM_CHECK_MSG)
  325. def test_builtin_with_environment(self):
  326. """
  327. fulldefault: django-admin builtin commands succeed if the environment
  328. contains settings.
  329. """
  330. args = ["check", "admin_scripts"]
  331. out, err = self.run_django_admin(args, "test_project.settings")
  332. self.assertNoOutput(err)
  333. self.assertOutput(out, SYSTEM_CHECK_MSG)
  334. def test_builtin_with_bad_settings(self):
  335. """
  336. fulldefault: django-admin builtin commands fail if settings file (from
  337. argument) doesn't exist.
  338. """
  339. args = ["check", "--settings=bad_settings", "admin_scripts"]
  340. out, err = self.run_django_admin(args)
  341. self.assertNoOutput(out)
  342. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  343. def test_builtin_with_bad_environment(self):
  344. """
  345. fulldefault: django-admin builtin commands fail if settings file (from
  346. environment) doesn't exist.
  347. """
  348. args = ["check", "admin_scripts"]
  349. out, err = self.run_django_admin(args, "bad_settings")
  350. self.assertNoOutput(out)
  351. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  352. def test_custom_command(self):
  353. """
  354. fulldefault: django-admin can't execute user commands unless settings
  355. are provided.
  356. """
  357. args = ["noargs_command"]
  358. out, err = self.run_django_admin(args)
  359. self.assertNoOutput(out)
  360. self.assertOutput(err, "No Django settings specified")
  361. self.assertOutput(err, "Unknown command: 'noargs_command'")
  362. def test_custom_command_with_settings(self):
  363. """
  364. fulldefault: django-admin can execute user commands if settings are
  365. provided as argument.
  366. """
  367. args = ["noargs_command", "--settings=test_project.settings"]
  368. out, err = self.run_django_admin(args)
  369. self.assertNoOutput(err)
  370. self.assertOutput(out, "EXECUTE: noargs_command")
  371. def test_custom_command_with_environment(self):
  372. """
  373. fulldefault: django-admin can execute user commands if settings are
  374. provided in environment.
  375. """
  376. args = ["noargs_command"]
  377. out, err = self.run_django_admin(args, "test_project.settings")
  378. self.assertNoOutput(err)
  379. self.assertOutput(out, "EXECUTE: noargs_command")
  380. class DjangoAdminMinimalSettings(AdminScriptTestCase):
  381. """
  382. A series of tests for django-admin when using a settings.py file that
  383. doesn't contain the test application.
  384. """
  385. def setUp(self):
  386. super().setUp()
  387. self.write_settings(
  388. "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
  389. )
  390. def test_builtin_command(self):
  391. """
  392. minimal: django-admin builtin commands fail with an error when no
  393. settings provided.
  394. """
  395. args = ["check", "admin_scripts"]
  396. out, err = self.run_django_admin(args)
  397. self.assertNoOutput(out)
  398. self.assertOutput(err, "settings are not configured")
  399. def test_builtin_with_settings(self):
  400. """
  401. minimal: django-admin builtin commands fail if settings are provided as
  402. argument.
  403. """
  404. args = ["check", "--settings=test_project.settings", "admin_scripts"]
  405. out, err = self.run_django_admin(args)
  406. self.assertNoOutput(out)
  407. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  408. def test_builtin_with_environment(self):
  409. """
  410. minimal: django-admin builtin commands fail if settings are provided in
  411. the environment.
  412. """
  413. args = ["check", "admin_scripts"]
  414. out, err = self.run_django_admin(args, "test_project.settings")
  415. self.assertNoOutput(out)
  416. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  417. def test_builtin_with_bad_settings(self):
  418. """
  419. minimal: django-admin builtin commands fail if settings file (from
  420. argument) doesn't exist.
  421. """
  422. args = ["check", "--settings=bad_settings", "admin_scripts"]
  423. out, err = self.run_django_admin(args)
  424. self.assertNoOutput(out)
  425. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  426. def test_builtin_with_bad_environment(self):
  427. """
  428. minimal: django-admin builtin commands fail if settings file (from
  429. environment) doesn't exist.
  430. """
  431. args = ["check", "admin_scripts"]
  432. out, err = self.run_django_admin(args, "bad_settings")
  433. self.assertNoOutput(out)
  434. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  435. def test_custom_command(self):
  436. "minimal: django-admin can't execute user commands unless settings are provided"
  437. args = ["noargs_command"]
  438. out, err = self.run_django_admin(args)
  439. self.assertNoOutput(out)
  440. self.assertOutput(err, "No Django settings specified")
  441. self.assertOutput(err, "Unknown command: 'noargs_command'")
  442. def test_custom_command_with_settings(self):
  443. """
  444. minimal: django-admin can't execute user commands, even if settings are
  445. provided as argument.
  446. """
  447. args = ["noargs_command", "--settings=test_project.settings"]
  448. out, err = self.run_django_admin(args)
  449. self.assertNoOutput(out)
  450. self.assertOutput(err, "Unknown command: 'noargs_command'")
  451. def test_custom_command_with_environment(self):
  452. """
  453. minimal: django-admin can't execute user commands, even if settings are
  454. provided in environment.
  455. """
  456. args = ["noargs_command"]
  457. out, err = self.run_django_admin(args, "test_project.settings")
  458. self.assertNoOutput(out)
  459. self.assertOutput(err, "Unknown command: 'noargs_command'")
  460. class DjangoAdminAlternateSettings(AdminScriptTestCase):
  461. """
  462. A series of tests for django-admin when using a settings file with a name
  463. other than 'settings.py'.
  464. """
  465. def setUp(self):
  466. super().setUp()
  467. self.write_settings("alternate_settings.py")
  468. def test_builtin_command(self):
  469. """
  470. alternate: django-admin builtin commands fail with an error when no
  471. settings provided.
  472. """
  473. args = ["check", "admin_scripts"]
  474. out, err = self.run_django_admin(args)
  475. self.assertNoOutput(out)
  476. self.assertOutput(err, "settings are not configured")
  477. def test_builtin_with_settings(self):
  478. """
  479. alternate: django-admin builtin commands succeed if settings are
  480. provided as argument.
  481. """
  482. args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"]
  483. out, err = self.run_django_admin(args)
  484. self.assertNoOutput(err)
  485. self.assertOutput(out, SYSTEM_CHECK_MSG)
  486. def test_builtin_with_environment(self):
  487. """
  488. alternate: django-admin builtin commands succeed if settings are
  489. provided in the environment.
  490. """
  491. args = ["check", "admin_scripts"]
  492. out, err = self.run_django_admin(args, "test_project.alternate_settings")
  493. self.assertNoOutput(err)
  494. self.assertOutput(out, SYSTEM_CHECK_MSG)
  495. def test_builtin_with_bad_settings(self):
  496. """
  497. alternate: django-admin builtin commands fail if settings file (from
  498. argument) doesn't exist.
  499. """
  500. args = ["check", "--settings=bad_settings", "admin_scripts"]
  501. out, err = self.run_django_admin(args)
  502. self.assertNoOutput(out)
  503. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  504. def test_builtin_with_bad_environment(self):
  505. """
  506. alternate: django-admin builtin commands fail if settings file (from
  507. environment) doesn't exist.
  508. """
  509. args = ["check", "admin_scripts"]
  510. out, err = self.run_django_admin(args, "bad_settings")
  511. self.assertNoOutput(out)
  512. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  513. def test_custom_command(self):
  514. """
  515. alternate: django-admin can't execute user commands unless settings
  516. are provided.
  517. """
  518. args = ["noargs_command"]
  519. out, err = self.run_django_admin(args)
  520. self.assertNoOutput(out)
  521. self.assertOutput(err, "No Django settings specified")
  522. self.assertOutput(err, "Unknown command: 'noargs_command'")
  523. def test_custom_command_with_settings(self):
  524. """
  525. alternate: django-admin can execute user commands if settings are
  526. provided as argument.
  527. """
  528. args = ["noargs_command", "--settings=test_project.alternate_settings"]
  529. out, err = self.run_django_admin(args)
  530. self.assertNoOutput(err)
  531. self.assertOutput(out, "EXECUTE: noargs_command")
  532. def test_custom_command_with_environment(self):
  533. """
  534. alternate: django-admin can execute user commands if settings are
  535. provided in environment.
  536. """
  537. args = ["noargs_command"]
  538. out, err = self.run_django_admin(args, "test_project.alternate_settings")
  539. self.assertNoOutput(err)
  540. self.assertOutput(out, "EXECUTE: noargs_command")
  541. class DjangoAdminMultipleSettings(AdminScriptTestCase):
  542. """
  543. A series of tests for django-admin when multiple settings files
  544. (including the default 'settings.py') are available. The default settings
  545. file is insufficient for performing the operations described, so the
  546. alternate settings must be used by the running script.
  547. """
  548. def setUp(self):
  549. super().setUp()
  550. self.write_settings(
  551. "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
  552. )
  553. self.write_settings("alternate_settings.py")
  554. def test_builtin_command(self):
  555. """
  556. alternate: django-admin builtin commands fail with an error when no
  557. settings provided.
  558. """
  559. args = ["check", "admin_scripts"]
  560. out, err = self.run_django_admin(args)
  561. self.assertNoOutput(out)
  562. self.assertOutput(err, "settings are not configured")
  563. def test_builtin_with_settings(self):
  564. """
  565. alternate: django-admin builtin commands succeed if settings are
  566. provided as argument.
  567. """
  568. args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"]
  569. out, err = self.run_django_admin(args)
  570. self.assertNoOutput(err)
  571. self.assertOutput(out, SYSTEM_CHECK_MSG)
  572. def test_builtin_with_environment(self):
  573. """
  574. alternate: django-admin builtin commands succeed if settings are
  575. provided in the environment.
  576. """
  577. args = ["check", "admin_scripts"]
  578. out, err = self.run_django_admin(args, "test_project.alternate_settings")
  579. self.assertNoOutput(err)
  580. self.assertOutput(out, SYSTEM_CHECK_MSG)
  581. def test_builtin_with_bad_settings(self):
  582. """
  583. alternate: django-admin builtin commands fail if settings file (from
  584. argument) doesn't exist.
  585. """
  586. args = ["check", "--settings=bad_settings", "admin_scripts"]
  587. out, err = self.run_django_admin(args)
  588. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  589. def test_builtin_with_bad_environment(self):
  590. """
  591. alternate: django-admin builtin commands fail if settings file (from
  592. environment) doesn't exist.
  593. """
  594. args = ["check", "admin_scripts"]
  595. out, err = self.run_django_admin(args, "bad_settings")
  596. self.assertNoOutput(out)
  597. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  598. def test_custom_command(self):
  599. """
  600. alternate: django-admin can't execute user commands unless settings are
  601. provided.
  602. """
  603. args = ["noargs_command"]
  604. out, err = self.run_django_admin(args)
  605. self.assertNoOutput(out)
  606. self.assertOutput(err, "No Django settings specified")
  607. self.assertOutput(err, "Unknown command: 'noargs_command'")
  608. def test_custom_command_with_settings(self):
  609. """
  610. alternate: django-admin can execute user commands if settings are
  611. provided as argument.
  612. """
  613. args = ["noargs_command", "--settings=test_project.alternate_settings"]
  614. out, err = self.run_django_admin(args)
  615. self.assertNoOutput(err)
  616. self.assertOutput(out, "EXECUTE: noargs_command")
  617. def test_custom_command_with_environment(self):
  618. """
  619. alternate: django-admin can execute user commands if settings are
  620. provided in environment.
  621. """
  622. args = ["noargs_command"]
  623. out, err = self.run_django_admin(args, "test_project.alternate_settings")
  624. self.assertNoOutput(err)
  625. self.assertOutput(out, "EXECUTE: noargs_command")
  626. class DjangoAdminSettingsDirectory(AdminScriptTestCase):
  627. """
  628. A series of tests for django-admin when the settings file is in a
  629. directory. (see #9751).
  630. """
  631. def setUp(self):
  632. super().setUp()
  633. self.write_settings("settings", is_dir=True)
  634. def test_setup_environ(self):
  635. "directory: startapp creates the correct directory"
  636. args = ["startapp", "settings_test"]
  637. app_path = os.path.join(self.test_dir, "settings_test")
  638. out, err = self.run_django_admin(args, "test_project.settings")
  639. self.assertNoOutput(err)
  640. self.assertTrue(os.path.exists(app_path))
  641. with open(os.path.join(app_path, "apps.py")) as f:
  642. content = f.read()
  643. self.assertIn("class SettingsTestConfig(AppConfig)", content)
  644. self.assertIn(
  645. 'name = "settings_test"' if HAS_BLACK else "name = 'settings_test'",
  646. content,
  647. )
  648. def test_setup_environ_custom_template(self):
  649. "directory: startapp creates the correct directory with a custom template"
  650. template_path = os.path.join(custom_templates_dir, "app_template")
  651. args = ["startapp", "--template", template_path, "custom_settings_test"]
  652. app_path = os.path.join(self.test_dir, "custom_settings_test")
  653. out, err = self.run_django_admin(args, "test_project.settings")
  654. self.assertNoOutput(err)
  655. self.assertTrue(os.path.exists(app_path))
  656. self.assertTrue(os.path.exists(os.path.join(app_path, "api.py")))
  657. def test_startapp_unicode_name(self):
  658. """startapp creates the correct directory with Unicode characters."""
  659. args = ["startapp", "こんにちは"]
  660. app_path = os.path.join(self.test_dir, "こんにちは")
  661. out, err = self.run_django_admin(args, "test_project.settings")
  662. self.assertNoOutput(err)
  663. self.assertTrue(os.path.exists(app_path))
  664. with open(os.path.join(app_path, "apps.py"), encoding="utf8") as f:
  665. content = f.read()
  666. self.assertIn("class こんにちはConfig(AppConfig)", content)
  667. self.assertIn('name = "こんにちは"' if HAS_BLACK else "name = 'こんにちは'", content)
  668. def test_builtin_command(self):
  669. """
  670. directory: django-admin builtin commands fail with an error when no
  671. settings provided.
  672. """
  673. args = ["check", "admin_scripts"]
  674. out, err = self.run_django_admin(args)
  675. self.assertNoOutput(out)
  676. self.assertOutput(err, "settings are not configured")
  677. def test_builtin_with_bad_settings(self):
  678. """
  679. directory: django-admin builtin commands fail if settings file (from
  680. argument) doesn't exist.
  681. """
  682. args = ["check", "--settings=bad_settings", "admin_scripts"]
  683. out, err = self.run_django_admin(args)
  684. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  685. def test_builtin_with_bad_environment(self):
  686. """
  687. directory: django-admin builtin commands fail if settings file (from
  688. environment) doesn't exist.
  689. """
  690. args = ["check", "admin_scripts"]
  691. out, err = self.run_django_admin(args, "bad_settings")
  692. self.assertNoOutput(out)
  693. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  694. def test_custom_command(self):
  695. """
  696. directory: django-admin can't execute user commands unless settings are
  697. provided.
  698. """
  699. args = ["noargs_command"]
  700. out, err = self.run_django_admin(args)
  701. self.assertNoOutput(out)
  702. self.assertOutput(err, "No Django settings specified")
  703. self.assertOutput(err, "Unknown command: 'noargs_command'")
  704. def test_builtin_with_settings(self):
  705. """
  706. directory: django-admin builtin commands succeed if settings are
  707. provided as argument.
  708. """
  709. args = ["check", "--settings=test_project.settings", "admin_scripts"]
  710. out, err = self.run_django_admin(args)
  711. self.assertNoOutput(err)
  712. self.assertOutput(out, SYSTEM_CHECK_MSG)
  713. def test_builtin_with_environment(self):
  714. """
  715. directory: django-admin builtin commands succeed if settings are
  716. provided in the environment.
  717. """
  718. args = ["check", "admin_scripts"]
  719. out, err = self.run_django_admin(args, "test_project.settings")
  720. self.assertNoOutput(err)
  721. self.assertOutput(out, SYSTEM_CHECK_MSG)
  722. ##########################################################################
  723. # MANAGE.PY TESTS
  724. # This next series of test classes checks the environment processing
  725. # of the generated manage.py script
  726. ##########################################################################
  727. class ManageManuallyConfiguredSettings(AdminScriptTestCase):
  728. """Customized manage.py calling settings.configure()."""
  729. def test_non_existent_command_output(self):
  730. out, err = self.run_manage(
  731. ["invalid_command"], manage_py="configured_settings_manage.py"
  732. )
  733. self.assertNoOutput(out)
  734. self.assertOutput(err, "Unknown command: 'invalid_command'")
  735. self.assertNotInOutput(err, "No Django settings specified")
  736. class ManageNoSettings(AdminScriptTestCase):
  737. "A series of tests for manage.py when there is no settings.py file."
  738. def test_builtin_command(self):
  739. """
  740. no settings: manage.py builtin commands fail with an error when no
  741. settings provided.
  742. """
  743. args = ["check", "admin_scripts"]
  744. out, err = self.run_manage(args)
  745. self.assertNoOutput(out)
  746. self.assertOutput(
  747. err, r"No module named '?(test_project\.)?settings'?", regex=True
  748. )
  749. def test_builtin_with_bad_settings(self):
  750. """
  751. no settings: manage.py builtin commands fail if settings file (from
  752. argument) doesn't exist.
  753. """
  754. args = ["check", "--settings=bad_settings", "admin_scripts"]
  755. out, err = self.run_manage(args)
  756. self.assertNoOutput(out)
  757. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  758. def test_builtin_with_bad_environment(self):
  759. """
  760. no settings: manage.py builtin commands fail if settings file (from
  761. environment) doesn't exist.
  762. """
  763. args = ["check", "admin_scripts"]
  764. out, err = self.run_manage(args, "bad_settings")
  765. self.assertNoOutput(out)
  766. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  767. class ManageDefaultSettings(AdminScriptTestCase):
  768. """A series of tests for manage.py when using a settings.py file that
  769. contains the test application.
  770. """
  771. def setUp(self):
  772. super().setUp()
  773. self.write_settings("settings.py")
  774. def test_builtin_command(self):
  775. """
  776. default: manage.py builtin commands succeed when default settings are
  777. appropriate.
  778. """
  779. args = ["check", "admin_scripts"]
  780. out, err = self.run_manage(args)
  781. self.assertNoOutput(err)
  782. self.assertOutput(out, SYSTEM_CHECK_MSG)
  783. def test_builtin_with_settings(self):
  784. """
  785. default: manage.py builtin commands succeed if settings are provided as
  786. argument.
  787. """
  788. args = ["check", "--settings=test_project.settings", "admin_scripts"]
  789. out, err = self.run_manage(args)
  790. self.assertNoOutput(err)
  791. self.assertOutput(out, SYSTEM_CHECK_MSG)
  792. def test_builtin_with_environment(self):
  793. """
  794. default: manage.py builtin commands succeed if settings are provided in
  795. the environment.
  796. """
  797. args = ["check", "admin_scripts"]
  798. out, err = self.run_manage(args, "test_project.settings")
  799. self.assertNoOutput(err)
  800. self.assertOutput(out, SYSTEM_CHECK_MSG)
  801. def test_builtin_with_bad_settings(self):
  802. """
  803. default: manage.py builtin commands succeed if settings file (from
  804. argument) doesn't exist.
  805. """
  806. args = ["check", "--settings=bad_settings", "admin_scripts"]
  807. out, err = self.run_manage(args)
  808. self.assertNoOutput(out)
  809. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  810. def test_builtin_with_bad_environment(self):
  811. """
  812. default: manage.py builtin commands fail if settings file (from
  813. environment) doesn't exist.
  814. """
  815. args = ["check", "admin_scripts"]
  816. out, err = self.run_manage(args, "bad_settings")
  817. self.assertNoOutput(out)
  818. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  819. def test_custom_command(self):
  820. """
  821. default: manage.py can execute user commands when default settings are
  822. appropriate.
  823. """
  824. args = ["noargs_command"]
  825. out, err = self.run_manage(args)
  826. self.assertNoOutput(err)
  827. self.assertOutput(out, "EXECUTE: noargs_command")
  828. def test_custom_command_with_settings(self):
  829. """
  830. default: manage.py can execute user commands when settings are provided
  831. as argument.
  832. """
  833. args = ["noargs_command", "--settings=test_project.settings"]
  834. out, err = self.run_manage(args)
  835. self.assertNoOutput(err)
  836. self.assertOutput(out, "EXECUTE: noargs_command")
  837. def test_custom_command_with_environment(self):
  838. """
  839. default: manage.py can execute user commands when settings are provided
  840. in environment.
  841. """
  842. args = ["noargs_command"]
  843. out, err = self.run_manage(args, "test_project.settings")
  844. self.assertNoOutput(err)
  845. self.assertOutput(out, "EXECUTE: noargs_command")
  846. class ManageFullPathDefaultSettings(AdminScriptTestCase):
  847. """A series of tests for manage.py when using a settings.py file that
  848. contains the test application specified using a full path.
  849. """
  850. def setUp(self):
  851. super().setUp()
  852. self.write_settings(
  853. "settings.py",
  854. ["django.contrib.auth", "django.contrib.contenttypes", "admin_scripts"],
  855. )
  856. def test_builtin_command(self):
  857. """
  858. fulldefault: manage.py builtin commands succeed when default settings
  859. are appropriate.
  860. """
  861. args = ["check", "admin_scripts"]
  862. out, err = self.run_manage(args)
  863. self.assertNoOutput(err)
  864. self.assertOutput(out, SYSTEM_CHECK_MSG)
  865. def test_builtin_with_settings(self):
  866. """
  867. fulldefault: manage.py builtin commands succeed if settings are
  868. provided as argument.
  869. """
  870. args = ["check", "--settings=test_project.settings", "admin_scripts"]
  871. out, err = self.run_manage(args)
  872. self.assertNoOutput(err)
  873. self.assertOutput(out, SYSTEM_CHECK_MSG)
  874. def test_builtin_with_environment(self):
  875. """
  876. fulldefault: manage.py builtin commands succeed if settings are
  877. provided in the environment.
  878. """
  879. args = ["check", "admin_scripts"]
  880. out, err = self.run_manage(args, "test_project.settings")
  881. self.assertNoOutput(err)
  882. self.assertOutput(out, SYSTEM_CHECK_MSG)
  883. def test_builtin_with_bad_settings(self):
  884. """
  885. fulldefault: manage.py builtin commands succeed if settings file (from
  886. argument) doesn't exist.
  887. """
  888. args = ["check", "--settings=bad_settings", "admin_scripts"]
  889. out, err = self.run_manage(args)
  890. self.assertNoOutput(out)
  891. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  892. def test_builtin_with_bad_environment(self):
  893. """
  894. fulldefault: manage.py builtin commands fail if settings file (from
  895. environment) doesn't exist.
  896. """
  897. args = ["check", "admin_scripts"]
  898. out, err = self.run_manage(args, "bad_settings")
  899. self.assertNoOutput(out)
  900. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  901. def test_custom_command(self):
  902. """
  903. fulldefault: manage.py can execute user commands when default settings
  904. are appropriate.
  905. """
  906. args = ["noargs_command"]
  907. out, err = self.run_manage(args)
  908. self.assertNoOutput(err)
  909. self.assertOutput(out, "EXECUTE: noargs_command")
  910. def test_custom_command_with_settings(self):
  911. """
  912. fulldefault: manage.py can execute user commands when settings are
  913. provided as argument.
  914. """
  915. args = ["noargs_command", "--settings=test_project.settings"]
  916. out, err = self.run_manage(args)
  917. self.assertNoOutput(err)
  918. self.assertOutput(out, "EXECUTE: noargs_command")
  919. def test_custom_command_with_environment(self):
  920. """
  921. fulldefault: manage.py can execute user commands when settings are
  922. provided in environment.
  923. """
  924. args = ["noargs_command"]
  925. out, err = self.run_manage(args, "test_project.settings")
  926. self.assertNoOutput(err)
  927. self.assertOutput(out, "EXECUTE: noargs_command")
  928. class ManageMinimalSettings(AdminScriptTestCase):
  929. """A series of tests for manage.py when using a settings.py file that
  930. doesn't contain the test application.
  931. """
  932. def setUp(self):
  933. super().setUp()
  934. self.write_settings(
  935. "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
  936. )
  937. def test_builtin_command(self):
  938. """
  939. minimal: manage.py builtin commands fail with an error when no settings
  940. provided.
  941. """
  942. args = ["check", "admin_scripts"]
  943. out, err = self.run_manage(args)
  944. self.assertNoOutput(out)
  945. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  946. def test_builtin_with_settings(self):
  947. "minimal: manage.py builtin commands fail if settings are provided as argument"
  948. args = ["check", "--settings=test_project.settings", "admin_scripts"]
  949. out, err = self.run_manage(args)
  950. self.assertNoOutput(out)
  951. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  952. def test_builtin_with_environment(self):
  953. """
  954. minimal: manage.py builtin commands fail if settings are provided in
  955. the environment.
  956. """
  957. args = ["check", "admin_scripts"]
  958. out, err = self.run_manage(args, "test_project.settings")
  959. self.assertNoOutput(out)
  960. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  961. def test_builtin_with_bad_settings(self):
  962. """
  963. minimal: manage.py builtin commands fail if settings file (from
  964. argument) doesn't exist.
  965. """
  966. args = ["check", "--settings=bad_settings", "admin_scripts"]
  967. out, err = self.run_manage(args)
  968. self.assertNoOutput(out)
  969. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  970. def test_builtin_with_bad_environment(self):
  971. """
  972. minimal: manage.py builtin commands fail if settings file (from
  973. environment) doesn't exist.
  974. """
  975. args = ["check", "admin_scripts"]
  976. out, err = self.run_manage(args, "bad_settings")
  977. self.assertNoOutput(out)
  978. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  979. def test_custom_command(self):
  980. "minimal: manage.py can't execute user commands without appropriate settings"
  981. args = ["noargs_command"]
  982. out, err = self.run_manage(args)
  983. self.assertNoOutput(out)
  984. self.assertOutput(err, "Unknown command: 'noargs_command'")
  985. def test_custom_command_with_settings(self):
  986. """
  987. minimal: manage.py can't execute user commands, even if settings are
  988. provided as argument.
  989. """
  990. args = ["noargs_command", "--settings=test_project.settings"]
  991. out, err = self.run_manage(args)
  992. self.assertNoOutput(out)
  993. self.assertOutput(err, "Unknown command: 'noargs_command'")
  994. def test_custom_command_with_environment(self):
  995. """
  996. minimal: manage.py can't execute user commands, even if settings are
  997. provided in environment.
  998. """
  999. args = ["noargs_command"]
  1000. out, err = self.run_manage(args, "test_project.settings")
  1001. self.assertNoOutput(out)
  1002. self.assertOutput(err, "Unknown command: 'noargs_command'")
  1003. class ManageAlternateSettings(AdminScriptTestCase):
  1004. """A series of tests for manage.py when using a settings file
  1005. with a name other than 'settings.py'.
  1006. """
  1007. def setUp(self):
  1008. super().setUp()
  1009. self.write_settings("alternate_settings.py")
  1010. def test_builtin_command(self):
  1011. """
  1012. alternate: manage.py builtin commands fail with an error when no
  1013. default settings provided.
  1014. """
  1015. args = ["check", "admin_scripts"]
  1016. out, err = self.run_manage(args)
  1017. self.assertNoOutput(out)
  1018. self.assertOutput(
  1019. err, r"No module named '?(test_project\.)?settings'?", regex=True
  1020. )
  1021. def test_builtin_with_settings(self):
  1022. "alternate: manage.py builtin commands work with settings provided as argument"
  1023. args = ["check", "--settings=alternate_settings", "admin_scripts"]
  1024. out, err = self.run_manage(args)
  1025. self.assertOutput(out, SYSTEM_CHECK_MSG)
  1026. self.assertNoOutput(err)
  1027. def test_builtin_with_environment(self):
  1028. """
  1029. alternate: manage.py builtin commands work if settings are provided in
  1030. the environment
  1031. """
  1032. args = ["check", "admin_scripts"]
  1033. out, err = self.run_manage(args, "alternate_settings")
  1034. self.assertOutput(out, SYSTEM_CHECK_MSG)
  1035. self.assertNoOutput(err)
  1036. def test_builtin_with_bad_settings(self):
  1037. """
  1038. alternate: manage.py builtin commands fail if settings file (from
  1039. argument) doesn't exist.
  1040. """
  1041. args = ["check", "--settings=bad_settings", "admin_scripts"]
  1042. out, err = self.run_manage(args)
  1043. self.assertNoOutput(out)
  1044. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  1045. def test_builtin_with_bad_environment(self):
  1046. """
  1047. alternate: manage.py builtin commands fail if settings file (from
  1048. environment) doesn't exist
  1049. """
  1050. args = ["check", "admin_scripts"]
  1051. out, err = self.run_manage(args, "bad_settings")
  1052. self.assertNoOutput(out)
  1053. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  1054. def test_custom_command(self):
  1055. "alternate: manage.py can't execute user commands without settings"
  1056. args = ["noargs_command"]
  1057. out, err = self.run_manage(args)
  1058. self.assertNoOutput(out)
  1059. self.assertOutput(
  1060. err, r"No module named '?(test_project\.)?settings'?", regex=True
  1061. )
  1062. def test_custom_command_with_settings(self):
  1063. """
  1064. alternate: manage.py can execute user commands if settings are provided
  1065. as argument
  1066. """
  1067. args = ["noargs_command", "--settings=alternate_settings"]
  1068. out, err = self.run_manage(args)
  1069. self.assertOutput(
  1070. out,
  1071. "EXECUTE: noargs_command options=[('force_color', False), "
  1072. "('no_color', False), ('pythonpath', None), ('settings', "
  1073. "'alternate_settings'), ('traceback', False), ('verbosity', 1)]",
  1074. )
  1075. self.assertNoOutput(err)
  1076. def test_custom_command_with_environment(self):
  1077. """
  1078. alternate: manage.py can execute user commands if settings are provided
  1079. in environment.
  1080. """
  1081. args = ["noargs_command"]
  1082. out, err = self.run_manage(args, "alternate_settings")
  1083. self.assertOutput(
  1084. out,
  1085. "EXECUTE: noargs_command options=[('force_color', False), "
  1086. "('no_color', False), ('pythonpath', None), ('settings', None), "
  1087. "('traceback', False), ('verbosity', 1)]",
  1088. )
  1089. self.assertNoOutput(err)
  1090. def test_custom_command_output_color(self):
  1091. """
  1092. alternate: manage.py output syntax color can be deactivated with the
  1093. `--no-color` option.
  1094. """
  1095. args = ["noargs_command", "--no-color", "--settings=alternate_settings"]
  1096. out, err = self.run_manage(args)
  1097. self.assertOutput(
  1098. out,
  1099. "EXECUTE: noargs_command options=[('force_color', False), "
  1100. "('no_color', True), ('pythonpath', None), ('settings', "
  1101. "'alternate_settings'), ('traceback', False), ('verbosity', 1)]",
  1102. )
  1103. self.assertNoOutput(err)
  1104. class ManageMultipleSettings(AdminScriptTestCase):
  1105. """A series of tests for manage.py when multiple settings files
  1106. (including the default 'settings.py') are available. The default settings
  1107. file is insufficient for performing the operations described, so the
  1108. alternate settings must be used by the running script.
  1109. """
  1110. def setUp(self):
  1111. super().setUp()
  1112. self.write_settings(
  1113. "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
  1114. )
  1115. self.write_settings("alternate_settings.py")
  1116. def test_builtin_command(self):
  1117. """
  1118. multiple: manage.py builtin commands fail with an error when no
  1119. settings provided.
  1120. """
  1121. args = ["check", "admin_scripts"]
  1122. out, err = self.run_manage(args)
  1123. self.assertNoOutput(out)
  1124. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  1125. def test_builtin_with_settings(self):
  1126. """
  1127. multiple: manage.py builtin commands succeed if settings are provided
  1128. as argument.
  1129. """
  1130. args = ["check", "--settings=alternate_settings", "admin_scripts"]
  1131. out, err = self.run_manage(args)
  1132. self.assertNoOutput(err)
  1133. self.assertOutput(out, SYSTEM_CHECK_MSG)
  1134. def test_builtin_with_environment(self):
  1135. """
  1136. multiple: manage.py can execute builtin commands if settings are
  1137. provided in the environment.
  1138. """
  1139. args = ["check", "admin_scripts"]
  1140. out, err = self.run_manage(args, "alternate_settings")
  1141. self.assertNoOutput(err)
  1142. self.assertOutput(out, SYSTEM_CHECK_MSG)
  1143. def test_builtin_with_bad_settings(self):
  1144. """
  1145. multiple: manage.py builtin commands fail if settings file (from
  1146. argument) doesn't exist.
  1147. """
  1148. args = ["check", "--settings=bad_settings", "admin_scripts"]
  1149. out, err = self.run_manage(args)
  1150. self.assertNoOutput(out)
  1151. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  1152. def test_builtin_with_bad_environment(self):
  1153. """
  1154. multiple: manage.py builtin commands fail if settings file (from
  1155. environment) doesn't exist.
  1156. """
  1157. args = ["check", "admin_scripts"]
  1158. out, err = self.run_manage(args, "bad_settings")
  1159. self.assertNoOutput(out)
  1160. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  1161. def test_custom_command(self):
  1162. "multiple: manage.py can't execute user commands using default settings"
  1163. args = ["noargs_command"]
  1164. out, err = self.run_manage(args)
  1165. self.assertNoOutput(out)
  1166. self.assertOutput(err, "Unknown command: 'noargs_command'")
  1167. def test_custom_command_with_settings(self):
  1168. """
  1169. multiple: manage.py can execute user commands if settings are provided
  1170. as argument.
  1171. """
  1172. args = ["noargs_command", "--settings=alternate_settings"]
  1173. out, err = self.run_manage(args)
  1174. self.assertNoOutput(err)
  1175. self.assertOutput(out, "EXECUTE: noargs_command")
  1176. def test_custom_command_with_environment(self):
  1177. """
  1178. multiple: manage.py can execute user commands if settings are provided
  1179. in environment.
  1180. """
  1181. args = ["noargs_command"]
  1182. out, err = self.run_manage(args, "alternate_settings")
  1183. self.assertNoOutput(err)
  1184. self.assertOutput(out, "EXECUTE: noargs_command")
  1185. class ManageSettingsWithSettingsErrors(AdminScriptTestCase):
  1186. """
  1187. Tests for manage.py when using the default settings.py file containing
  1188. runtime errors.
  1189. """
  1190. def write_settings_with_import_error(self, filename):
  1191. settings_file_path = os.path.join(self.test_dir, filename)
  1192. with open(settings_file_path, "w") as settings_file:
  1193. settings_file.write(
  1194. "# Settings file automatically generated by admin_scripts test case\n"
  1195. )
  1196. settings_file.write(
  1197. "# The next line will cause an import error:\nimport foo42bar\n"
  1198. )
  1199. def test_import_error(self):
  1200. """
  1201. import error: manage.py builtin commands shows useful diagnostic info
  1202. when settings with import errors is provided (#14130).
  1203. """
  1204. self.write_settings_with_import_error("settings.py")
  1205. args = ["check", "admin_scripts"]
  1206. out, err = self.run_manage(args)
  1207. self.assertNoOutput(out)
  1208. self.assertOutput(err, "No module named")
  1209. self.assertOutput(err, "foo42bar")
  1210. def test_attribute_error(self):
  1211. """
  1212. manage.py builtin commands does not swallow attribute error due to bad
  1213. settings (#18845).
  1214. """
  1215. self.write_settings("settings.py", sdict={"BAD_VAR": "INSTALLED_APPS.crash"})
  1216. args = ["collectstatic", "admin_scripts"]
  1217. out, err = self.run_manage(args)
  1218. self.assertNoOutput(out)
  1219. self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'")
  1220. def test_key_error(self):
  1221. self.write_settings("settings.py", sdict={"BAD_VAR": 'DATABASES["blah"]'})
  1222. args = ["collectstatic", "admin_scripts"]
  1223. out, err = self.run_manage(args)
  1224. self.assertNoOutput(out)
  1225. self.assertOutput(err, "KeyError: 'blah'")
  1226. def test_help(self):
  1227. """
  1228. Test listing available commands output note when only core commands are
  1229. available.
  1230. """
  1231. self.write_settings(
  1232. "settings.py",
  1233. extra="from django.core.exceptions import ImproperlyConfigured\n"
  1234. "raise ImproperlyConfigured()",
  1235. )
  1236. args = ["help"]
  1237. out, err = self.run_manage(args)
  1238. self.assertOutput(out, "only Django core commands are listed")
  1239. self.assertNoOutput(err)
  1240. class ManageCheck(AdminScriptTestCase):
  1241. def test_nonexistent_app(self):
  1242. """check reports an error on a nonexistent app in INSTALLED_APPS."""
  1243. self.write_settings(
  1244. "settings.py",
  1245. apps=["admin_scriptz.broken_app"],
  1246. sdict={"USE_I18N": False},
  1247. )
  1248. args = ["check"]
  1249. out, err = self.run_manage(args)
  1250. self.assertNoOutput(out)
  1251. self.assertOutput(err, "ModuleNotFoundError")
  1252. self.assertOutput(err, "No module named")
  1253. self.assertOutput(err, "admin_scriptz")
  1254. def test_broken_app(self):
  1255. """manage.py check reports an ImportError if an app's models.py
  1256. raises one on import"""
  1257. self.write_settings("settings.py", apps=["admin_scripts.broken_app"])
  1258. args = ["check"]
  1259. out, err = self.run_manage(args)
  1260. self.assertNoOutput(out)
  1261. self.assertOutput(err, "ImportError")
  1262. def test_complex_app(self):
  1263. """manage.py check does not raise an ImportError validating a
  1264. complex app with nested calls to load_app"""
  1265. self.write_settings(
  1266. "settings.py",
  1267. apps=[
  1268. "admin_scripts.complex_app",
  1269. "admin_scripts.simple_app",
  1270. "django.contrib.admin.apps.SimpleAdminConfig",
  1271. "django.contrib.auth",
  1272. "django.contrib.contenttypes",
  1273. "django.contrib.messages",
  1274. ],
  1275. sdict={
  1276. "DEBUG": True,
  1277. "MIDDLEWARE": [
  1278. "django.contrib.messages.middleware.MessageMiddleware",
  1279. "django.contrib.auth.middleware.AuthenticationMiddleware",
  1280. "django.contrib.sessions.middleware.SessionMiddleware",
  1281. ],
  1282. "TEMPLATES": [
  1283. {
  1284. "BACKEND": "django.template.backends.django.DjangoTemplates",
  1285. "DIRS": [],
  1286. "APP_DIRS": True,
  1287. "OPTIONS": {
  1288. "context_processors": [
  1289. "django.template.context_processors.request",
  1290. "django.contrib.auth.context_processors.auth",
  1291. "django.contrib.messages.context_processors.messages",
  1292. ],
  1293. },
  1294. },
  1295. ],
  1296. },
  1297. )
  1298. args = ["check"]
  1299. out, err = self.run_manage(args)
  1300. self.assertNoOutput(err)
  1301. self.assertEqual(out, "System check identified no issues (0 silenced).\n")
  1302. def test_app_with_import(self):
  1303. """manage.py check does not raise errors when an app imports a base
  1304. class that itself has an abstract base."""
  1305. self.write_settings(
  1306. "settings.py",
  1307. apps=[
  1308. "admin_scripts.app_with_import",
  1309. "django.contrib.auth",
  1310. "django.contrib.contenttypes",
  1311. "django.contrib.sites",
  1312. ],
  1313. sdict={"DEBUG": True},
  1314. )
  1315. args = ["check"]
  1316. out, err = self.run_manage(args)
  1317. self.assertNoOutput(err)
  1318. self.assertEqual(out, "System check identified no issues (0 silenced).\n")
  1319. def test_output_format(self):
  1320. """All errors/warnings should be sorted by level and by message."""
  1321. self.write_settings(
  1322. "settings.py",
  1323. apps=[
  1324. "admin_scripts.app_raising_messages",
  1325. "django.contrib.auth",
  1326. "django.contrib.contenttypes",
  1327. ],
  1328. sdict={"DEBUG": True},
  1329. )
  1330. args = ["check"]
  1331. out, err = self.run_manage(args)
  1332. expected_err = (
  1333. "SystemCheckError: System check identified some issues:\n"
  1334. "\n"
  1335. "ERRORS:\n"
  1336. "?: An error\n"
  1337. "\tHINT: Error hint\n"
  1338. "\n"
  1339. "WARNINGS:\n"
  1340. "a: Second warning\n"
  1341. "obj: First warning\n"
  1342. "\tHINT: Hint\n"
  1343. "\n"
  1344. "System check identified 3 issues (0 silenced).\n"
  1345. )
  1346. self.assertEqual(err, expected_err)
  1347. self.assertNoOutput(out)
  1348. def test_warning_does_not_halt(self):
  1349. """
  1350. When there are only warnings or less serious messages, then Django
  1351. should not prevent user from launching their project, so `check`
  1352. command should not raise `CommandError` exception.
  1353. In this test we also test output format.
  1354. """
  1355. self.write_settings(
  1356. "settings.py",
  1357. apps=[
  1358. "admin_scripts.app_raising_warning",
  1359. "django.contrib.auth",
  1360. "django.contrib.contenttypes",
  1361. ],
  1362. sdict={"DEBUG": True},
  1363. )
  1364. args = ["check"]
  1365. out, err = self.run_manage(args)
  1366. expected_err = (
  1367. "System check identified some issues:\n" # No "CommandError: " part
  1368. "\n"
  1369. "WARNINGS:\n"
  1370. "?: A warning\n"
  1371. "\n"
  1372. "System check identified 1 issue (0 silenced).\n"
  1373. )
  1374. self.assertEqual(err, expected_err)
  1375. self.assertNoOutput(out)
  1376. class ManageRunserver(SimpleTestCase):
  1377. def setUp(self):
  1378. def monkey_run(*args, **options):
  1379. return
  1380. self.output = StringIO()
  1381. self.cmd = RunserverCommand(stdout=self.output)
  1382. self.cmd.run = monkey_run
  1383. def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False):
  1384. self.assertEqual(self.cmd.addr, addr)
  1385. self.assertEqual(self.cmd.port, port)
  1386. self.assertEqual(self.cmd.use_ipv6, ipv6)
  1387. self.assertEqual(self.cmd._raw_ipv6, raw_ipv6)
  1388. def test_runserver_addrport(self):
  1389. call_command(self.cmd)
  1390. self.assertServerSettings("127.0.0.1", "8000")
  1391. call_command(self.cmd, addrport="1.2.3.4:8000")
  1392. self.assertServerSettings("1.2.3.4", "8000")
  1393. call_command(self.cmd, addrport="7000")
  1394. self.assertServerSettings("127.0.0.1", "7000")
  1395. @mock.patch("django.core.management.commands.runserver.run")
  1396. @mock.patch("django.core.management.base.BaseCommand.check_migrations")
  1397. def test_zero_ip_addr(self, *mocked_objects):
  1398. call_command(
  1399. "runserver",
  1400. addrport="0:8000",
  1401. use_reloader=False,
  1402. skip_checks=True,
  1403. stdout=self.output,
  1404. )
  1405. self.assertIn(
  1406. "Starting development server at http://0.0.0.0:8000/",
  1407. self.output.getvalue(),
  1408. )
  1409. @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
  1410. def test_runner_addrport_ipv6(self):
  1411. call_command(self.cmd, addrport="", use_ipv6=True)
  1412. self.assertServerSettings("::1", "8000", ipv6=True, raw_ipv6=True)
  1413. call_command(self.cmd, addrport="7000", use_ipv6=True)
  1414. self.assertServerSettings("::1", "7000", ipv6=True, raw_ipv6=True)
  1415. call_command(self.cmd, addrport="[2001:0db8:1234:5678::9]:7000")
  1416. self.assertServerSettings(
  1417. "2001:0db8:1234:5678::9", "7000", ipv6=True, raw_ipv6=True
  1418. )
  1419. def test_runner_hostname(self):
  1420. call_command(self.cmd, addrport="localhost:8000")
  1421. self.assertServerSettings("localhost", "8000")
  1422. call_command(self.cmd, addrport="test.domain.local:7000")
  1423. self.assertServerSettings("test.domain.local", "7000")
  1424. @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
  1425. def test_runner_hostname_ipv6(self):
  1426. call_command(self.cmd, addrport="test.domain.local:7000", use_ipv6=True)
  1427. self.assertServerSettings("test.domain.local", "7000", ipv6=True)
  1428. def test_runner_custom_defaults(self):
  1429. self.cmd.default_addr = "0.0.0.0"
  1430. self.cmd.default_port = "5000"
  1431. call_command(self.cmd)
  1432. self.assertServerSettings("0.0.0.0", "5000")
  1433. @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
  1434. def test_runner_custom_defaults_ipv6(self):
  1435. self.cmd.default_addr_ipv6 = "::"
  1436. call_command(self.cmd, use_ipv6=True)
  1437. self.assertServerSettings("::", "8000", ipv6=True, raw_ipv6=True)
  1438. def test_runner_ambiguous(self):
  1439. # Only 4 characters, all of which could be in an ipv6 address
  1440. call_command(self.cmd, addrport="beef:7654")
  1441. self.assertServerSettings("beef", "7654")
  1442. # Uses only characters that could be in an ipv6 address
  1443. call_command(self.cmd, addrport="deadbeef:7654")
  1444. self.assertServerSettings("deadbeef", "7654")
  1445. def test_no_database(self):
  1446. """
  1447. Ensure runserver.check_migrations doesn't choke on empty DATABASES.
  1448. """
  1449. tested_connections = ConnectionHandler({})
  1450. with mock.patch(
  1451. "django.core.management.base.connections", new=tested_connections
  1452. ):
  1453. self.cmd.check_migrations()
  1454. def test_readonly_database(self):
  1455. """
  1456. runserver.check_migrations() doesn't choke when a database is read-only.
  1457. """
  1458. with mock.patch.object(MigrationRecorder, "has_table", return_value=False):
  1459. self.cmd.check_migrations()
  1460. # You have # ...
  1461. self.assertIn("unapplied migration(s)", self.output.getvalue())
  1462. @mock.patch("django.core.management.commands.runserver.run")
  1463. @mock.patch("django.core.management.base.BaseCommand.check_migrations")
  1464. @mock.patch("django.core.management.base.BaseCommand.check")
  1465. def test_skip_checks(self, mocked_check, *mocked_objects):
  1466. call_command(
  1467. "runserver",
  1468. use_reloader=False,
  1469. skip_checks=True,
  1470. stdout=self.output,
  1471. )
  1472. self.assertNotIn("Performing system checks...", self.output.getvalue())
  1473. mocked_check.assert_not_called()
  1474. self.output.truncate(0)
  1475. call_command(
  1476. "runserver",
  1477. use_reloader=False,
  1478. skip_checks=False,
  1479. stdout=self.output,
  1480. )
  1481. self.assertIn("Performing system checks...", self.output.getvalue())
  1482. mocked_check.assert_called()
  1483. class ManageRunserverMigrationWarning(TestCase):
  1484. def setUp(self):
  1485. self.stdout = StringIO()
  1486. self.runserver_command = RunserverCommand(stdout=self.stdout)
  1487. @override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"])
  1488. def test_migration_warning_one_app(self):
  1489. self.runserver_command.check_migrations()
  1490. output = self.stdout.getvalue()
  1491. self.assertIn("You have 1 unapplied migration(s)", output)
  1492. self.assertIn("apply the migrations for app(s): app_waiting_migration.", output)
  1493. @override_settings(
  1494. INSTALLED_APPS=[
  1495. "admin_scripts.app_waiting_migration",
  1496. "admin_scripts.another_app_waiting_migration",
  1497. ],
  1498. )
  1499. def test_migration_warning_multiple_apps(self):
  1500. self.runserver_command.check_migrations()
  1501. output = self.stdout.getvalue()
  1502. self.assertIn("You have 2 unapplied migration(s)", output)
  1503. self.assertIn(
  1504. "apply the migrations for app(s): another_app_waiting_migration, "
  1505. "app_waiting_migration.",
  1506. output,
  1507. )
  1508. class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
  1509. def setUp(self):
  1510. super().setUp()
  1511. self.write_settings(
  1512. "settings.py",
  1513. sdict={
  1514. "ALLOWED_HOSTS": [],
  1515. "DEBUG": False,
  1516. },
  1517. )
  1518. def test_empty_allowed_hosts_error(self):
  1519. out, err = self.run_manage(["runserver"])
  1520. self.assertNoOutput(out)
  1521. self.assertOutput(
  1522. err, "CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False."
  1523. )
  1524. class ManageRunserverHelpOutput(AdminScriptTestCase):
  1525. def test_suppressed_options(self):
  1526. """runserver doesn't support --verbosity and --trackback options."""
  1527. out, err = self.run_manage(["runserver", "--help"])
  1528. self.assertNotInOutput(out, "--verbosity")
  1529. self.assertNotInOutput(out, "--trackback")
  1530. self.assertOutput(out, "--settings")
  1531. class ManageTestserver(SimpleTestCase):
  1532. @mock.patch.object(TestserverCommand, "handle", return_value="")
  1533. def test_testserver_handle_params(self, mock_handle):
  1534. out = StringIO()
  1535. call_command("testserver", "blah.json", stdout=out)
  1536. mock_handle.assert_called_with(
  1537. "blah.json",
  1538. stdout=out,
  1539. settings=None,
  1540. pythonpath=None,
  1541. verbosity=1,
  1542. traceback=False,
  1543. addrport="",
  1544. no_color=False,
  1545. use_ipv6=False,
  1546. skip_checks=True,
  1547. interactive=True,
  1548. force_color=False,
  1549. )
  1550. @mock.patch("django.db.connection.creation.create_test_db", return_value="test_db")
  1551. @mock.patch.object(LoaddataCommand, "handle", return_value="")
  1552. @mock.patch.object(RunserverCommand, "handle", return_value="")
  1553. def test_params_to_runserver(
  1554. self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db
  1555. ):
  1556. call_command("testserver", "blah.json")
  1557. mock_runserver_handle.assert_called_with(
  1558. addrport="",
  1559. force_color=False,
  1560. insecure_serving=False,
  1561. no_color=False,
  1562. pythonpath=None,
  1563. settings=None,
  1564. shutdown_message=(
  1565. "\nServer stopped.\nNote that the test database, 'test_db', "
  1566. "has not been deleted. You can explore it on your own."
  1567. ),
  1568. skip_checks=True,
  1569. traceback=False,
  1570. use_ipv6=False,
  1571. use_reloader=False,
  1572. use_static_handler=True,
  1573. use_threading=connection.features.test_db_allows_multiple_connections,
  1574. verbosity=1,
  1575. )
  1576. ##########################################################################
  1577. # COMMAND PROCESSING TESTS
  1578. # user-space commands are correctly handled - in particular, arguments to
  1579. # the commands are correctly parsed and processed.
  1580. ##########################################################################
  1581. class ColorCommand(BaseCommand):
  1582. requires_system_checks = []
  1583. def handle(self, *args, **options):
  1584. self.stdout.write("Hello, world!", self.style.ERROR)
  1585. self.stderr.write("Hello, world!", self.style.ERROR)
  1586. class CommandTypes(AdminScriptTestCase):
  1587. "Tests for the various types of base command types that can be defined."
  1588. def setUp(self):
  1589. super().setUp()
  1590. self.write_settings("settings.py")
  1591. def test_version(self):
  1592. "version is handled as a special case"
  1593. args = ["version"]
  1594. out, err = self.run_manage(args)
  1595. self.assertNoOutput(err)
  1596. self.assertOutput(out, get_version())
  1597. def test_version_alternative(self):
  1598. "--version is equivalent to version"
  1599. args1, args2 = ["version"], ["--version"]
  1600. # It's possible one outputs on stderr and the other on stdout, hence the set
  1601. self.assertEqual(set(self.run_manage(args1)), set(self.run_manage(args2)))
  1602. def test_help(self):
  1603. "help is handled as a special case"
  1604. args = ["help"]
  1605. out, err = self.run_manage(args)
  1606. self.assertOutput(
  1607. out, "Type 'manage.py help <subcommand>' for help on a specific subcommand."
  1608. )
  1609. self.assertOutput(out, "[django]")
  1610. self.assertOutput(out, "startapp")
  1611. self.assertOutput(out, "startproject")
  1612. def test_help_commands(self):
  1613. "help --commands shows the list of all available commands"
  1614. args = ["help", "--commands"]
  1615. out, err = self.run_manage(args)
  1616. self.assertNotInOutput(out, "usage:")
  1617. self.assertNotInOutput(out, "Options:")
  1618. self.assertNotInOutput(out, "[django]")
  1619. self.assertOutput(out, "startapp")
  1620. self.assertOutput(out, "startproject")
  1621. self.assertNotInOutput(out, "\n\n")
  1622. def test_help_alternative(self):
  1623. "--help is equivalent to help"
  1624. args1, args2 = ["help"], ["--help"]
  1625. self.assertEqual(self.run_manage(args1), self.run_manage(args2))
  1626. def test_help_short_altert(self):
  1627. "-h is handled as a short form of --help"
  1628. args1, args2 = ["--help"], ["-h"]
  1629. self.assertEqual(self.run_manage(args1), self.run_manage(args2))
  1630. def test_specific_help(self):
  1631. "--help can be used on a specific command"
  1632. args = ["check", "--help"]
  1633. out, err = self.run_manage(args)
  1634. self.assertNoOutput(err)
  1635. # Command-specific options like --tag appear before options common to
  1636. # all commands like --version.
  1637. tag_location = out.find("--tag")
  1638. version_location = out.find("--version")
  1639. self.assertNotEqual(tag_location, -1)
  1640. self.assertNotEqual(version_location, -1)
  1641. self.assertLess(tag_location, version_location)
  1642. self.assertOutput(
  1643. out, "Checks the entire Django project for potential problems."
  1644. )
  1645. def test_help_default_options_with_custom_arguments(self):
  1646. args = ["base_command", "--help"]
  1647. out, err = self.run_manage(args)
  1648. self.assertNoOutput(err)
  1649. expected_options = [
  1650. "-h",
  1651. "--option_a OPTION_A",
  1652. "--option_b OPTION_B",
  1653. "--option_c OPTION_C",
  1654. "--version",
  1655. "-v {0,1,2,3}",
  1656. "--settings SETTINGS",
  1657. "--pythonpath PYTHONPATH",
  1658. "--traceback",
  1659. "--no-color",
  1660. "--force-color",
  1661. "args ...",
  1662. ]
  1663. for option in expected_options:
  1664. self.assertOutput(out, f"[{option}]")
  1665. self.assertOutput(out, "--option_a OPTION_A, -a OPTION_A")
  1666. self.assertOutput(out, "--option_b OPTION_B, -b OPTION_B")
  1667. self.assertOutput(out, "--option_c OPTION_C, -c OPTION_C")
  1668. self.assertOutput(out, "-v {0,1,2,3}, --verbosity {0,1,2,3}")
  1669. def test_color_style(self):
  1670. style = color.no_style()
  1671. self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!")
  1672. style = color.make_style("nocolor")
  1673. self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!")
  1674. style = color.make_style("dark")
  1675. self.assertIn("Hello, world!", style.ERROR("Hello, world!"))
  1676. self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!")
  1677. # Default palette has color.
  1678. style = color.make_style("")
  1679. self.assertIn("Hello, world!", style.ERROR("Hello, world!"))
  1680. self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!")
  1681. def test_command_color(self):
  1682. out = StringIO()
  1683. err = StringIO()
  1684. command = ColorCommand(stdout=out, stderr=err)
  1685. call_command(command)
  1686. if color.supports_color():
  1687. self.assertIn("Hello, world!\n", out.getvalue())
  1688. self.assertIn("Hello, world!\n", err.getvalue())
  1689. self.assertNotEqual(out.getvalue(), "Hello, world!\n")
  1690. self.assertNotEqual(err.getvalue(), "Hello, world!\n")
  1691. else:
  1692. self.assertEqual(out.getvalue(), "Hello, world!\n")
  1693. self.assertEqual(err.getvalue(), "Hello, world!\n")
  1694. def test_command_no_color(self):
  1695. "--no-color prevent colorization of the output"
  1696. out = StringIO()
  1697. err = StringIO()
  1698. command = ColorCommand(stdout=out, stderr=err, no_color=True)
  1699. call_command(command)
  1700. self.assertEqual(out.getvalue(), "Hello, world!\n")
  1701. self.assertEqual(err.getvalue(), "Hello, world!\n")
  1702. out = StringIO()
  1703. err = StringIO()
  1704. command = ColorCommand(stdout=out, stderr=err)
  1705. call_command(command, no_color=True)
  1706. self.assertEqual(out.getvalue(), "Hello, world!\n")
  1707. self.assertEqual(err.getvalue(), "Hello, world!\n")
  1708. def test_force_color_execute(self):
  1709. out = StringIO()
  1710. err = StringIO()
  1711. with mock.patch.object(sys.stdout, "isatty", lambda: False):
  1712. command = ColorCommand(stdout=out, stderr=err)
  1713. call_command(command, force_color=True)
  1714. self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m")
  1715. self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m")
  1716. def test_force_color_command_init(self):
  1717. out = StringIO()
  1718. err = StringIO()
  1719. with mock.patch.object(sys.stdout, "isatty", lambda: False):
  1720. command = ColorCommand(stdout=out, stderr=err, force_color=True)
  1721. call_command(command)
  1722. self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m")
  1723. self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m")
  1724. def test_no_color_force_color_mutually_exclusive_execute(self):
  1725. msg = "The --no-color and --force-color options can't be used together."
  1726. with self.assertRaisesMessage(CommandError, msg):
  1727. call_command(BaseCommand(), no_color=True, force_color=True)
  1728. def test_no_color_force_color_mutually_exclusive_command_init(self):
  1729. msg = "'no_color' and 'force_color' can't be used together."
  1730. with self.assertRaisesMessage(CommandError, msg):
  1731. call_command(BaseCommand(no_color=True, force_color=True))
  1732. def test_custom_stdout(self):
  1733. class Command(BaseCommand):
  1734. requires_system_checks = []
  1735. def handle(self, *args, **options):
  1736. self.stdout.write("Hello, World!")
  1737. out = StringIO()
  1738. command = Command(stdout=out)
  1739. call_command(command)
  1740. self.assertEqual(out.getvalue(), "Hello, World!\n")
  1741. out.truncate(0)
  1742. new_out = StringIO()
  1743. call_command(command, stdout=new_out)
  1744. self.assertEqual(out.getvalue(), "")
  1745. self.assertEqual(new_out.getvalue(), "Hello, World!\n")
  1746. def test_custom_stderr(self):
  1747. class Command(BaseCommand):
  1748. requires_system_checks = []
  1749. def handle(self, *args, **options):
  1750. self.stderr.write("Hello, World!")
  1751. err = StringIO()
  1752. command = Command(stderr=err)
  1753. call_command(command)
  1754. self.assertEqual(err.getvalue(), "Hello, World!\n")
  1755. err.truncate(0)
  1756. new_err = StringIO()
  1757. call_command(command, stderr=new_err)
  1758. self.assertEqual(err.getvalue(), "")
  1759. self.assertEqual(new_err.getvalue(), "Hello, World!\n")
  1760. def test_base_command(self):
  1761. "User BaseCommands can execute when a label is provided"
  1762. args = ["base_command", "testlabel"]
  1763. expected_labels = "('testlabel',)"
  1764. self._test_base_command(args, expected_labels)
  1765. def test_base_command_no_label(self):
  1766. "User BaseCommands can execute when no labels are provided"
  1767. args = ["base_command"]
  1768. expected_labels = "()"
  1769. self._test_base_command(args, expected_labels)
  1770. def test_base_command_multiple_label(self):
  1771. "User BaseCommands can execute when no labels are provided"
  1772. args = ["base_command", "testlabel", "anotherlabel"]
  1773. expected_labels = "('testlabel', 'anotherlabel')"
  1774. self._test_base_command(args, expected_labels)
  1775. def test_base_command_with_option(self):
  1776. "User BaseCommands can execute with options when a label is provided"
  1777. args = ["base_command", "testlabel", "--option_a=x"]
  1778. expected_labels = "('testlabel',)"
  1779. self._test_base_command(args, expected_labels, option_a="'x'")
  1780. def test_base_command_with_options(self):
  1781. "User BaseCommands can execute with multiple options when a label is provided"
  1782. args = ["base_command", "testlabel", "-a", "x", "--option_b=y"]
  1783. expected_labels = "('testlabel',)"
  1784. self._test_base_command(args, expected_labels, option_a="'x'", option_b="'y'")
  1785. def test_base_command_with_wrong_option(self):
  1786. "User BaseCommands outputs command usage when wrong option is specified"
  1787. args = ["base_command", "--invalid"]
  1788. out, err = self.run_manage(args)
  1789. self.assertNoOutput(out)
  1790. self.assertOutput(err, "usage: manage.py base_command")
  1791. self.assertOutput(err, "error: unrecognized arguments: --invalid")
  1792. def _test_base_command(self, args, labels, option_a="'1'", option_b="'2'"):
  1793. out, err = self.run_manage(args)
  1794. expected_out = (
  1795. "EXECUTE:BaseCommand labels=%s, "
  1796. "options=[('force_color', False), ('no_color', False), "
  1797. "('option_a', %s), ('option_b', %s), ('option_c', '3'), "
  1798. "('pythonpath', None), ('settings', None), ('traceback', False), "
  1799. "('verbosity', 1)]"
  1800. ) % (labels, option_a, option_b)
  1801. self.assertNoOutput(err)
  1802. self.assertOutput(out, expected_out)
  1803. def test_base_run_from_argv(self):
  1804. """
  1805. Test run_from_argv properly terminates even with custom execute() (#19665)
  1806. Also test proper traceback display.
  1807. """
  1808. err = StringIO()
  1809. command = BaseCommand(stderr=err)
  1810. def raise_command_error(*args, **kwargs):
  1811. raise CommandError("Custom error")
  1812. command.execute = lambda args: args # This will trigger TypeError
  1813. # If the Exception is not CommandError it should always
  1814. # raise the original exception.
  1815. with self.assertRaises(TypeError):
  1816. command.run_from_argv(["", ""])
  1817. # If the Exception is CommandError and --traceback is not present
  1818. # this command should raise a SystemExit and don't print any
  1819. # traceback to the stderr.
  1820. command.execute = raise_command_error
  1821. err.truncate(0)
  1822. with self.assertRaises(SystemExit):
  1823. command.run_from_argv(["", ""])
  1824. err_message = err.getvalue()
  1825. self.assertNotIn("Traceback", err_message)
  1826. self.assertIn("CommandError", err_message)
  1827. # If the Exception is CommandError and --traceback is present
  1828. # this command should raise the original CommandError as if it
  1829. # were not a CommandError.
  1830. err.truncate(0)
  1831. with self.assertRaises(CommandError):
  1832. command.run_from_argv(["", "", "--traceback"])
  1833. def test_run_from_argv_non_ascii_error(self):
  1834. """
  1835. Non-ASCII message of CommandError does not raise any
  1836. UnicodeDecodeError in run_from_argv.
  1837. """
  1838. def raise_command_error(*args, **kwargs):
  1839. raise CommandError("Erreur personnalisée")
  1840. command = BaseCommand(stderr=StringIO())
  1841. command.execute = raise_command_error
  1842. with self.assertRaises(SystemExit):
  1843. command.run_from_argv(["", ""])
  1844. def test_run_from_argv_closes_connections(self):
  1845. """
  1846. A command called from the command line should close connections after
  1847. being executed (#21255).
  1848. """
  1849. command = BaseCommand()
  1850. command.check = lambda: []
  1851. command.handle = lambda *args, **kwargs: args
  1852. with mock.patch("django.core.management.base.connections") as mock_connections:
  1853. command.run_from_argv(["", ""])
  1854. # Test connections have been closed
  1855. self.assertTrue(mock_connections.close_all.called)
  1856. def test_noargs(self):
  1857. "NoArg Commands can be executed"
  1858. args = ["noargs_command"]
  1859. out, err = self.run_manage(args)
  1860. self.assertNoOutput(err)
  1861. self.assertOutput(
  1862. out,
  1863. "EXECUTE: noargs_command options=[('force_color', False), "
  1864. "('no_color', False), ('pythonpath', None), ('settings', None), "
  1865. "('traceback', False), ('verbosity', 1)]",
  1866. )
  1867. def test_noargs_with_args(self):
  1868. "NoArg Commands raise an error if an argument is provided"
  1869. args = ["noargs_command", "argument"]
  1870. out, err = self.run_manage(args)
  1871. self.assertOutput(err, "error: unrecognized arguments: argument")
  1872. def test_app_command(self):
  1873. "User AppCommands can execute when a single app name is provided"
  1874. args = ["app_command", "auth"]
  1875. out, err = self.run_manage(args)
  1876. self.assertNoOutput(err)
  1877. self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=")
  1878. self.assertOutput(
  1879. out,
  1880. ", options=[('force_color', False), ('no_color', False), "
  1881. "('pythonpath', None), ('settings', None), ('traceback', False), "
  1882. "('verbosity', 1)]",
  1883. )
  1884. def test_app_command_no_apps(self):
  1885. "User AppCommands raise an error when no app name is provided"
  1886. args = ["app_command"]
  1887. out, err = self.run_manage(args)
  1888. self.assertOutput(err, "error: Enter at least one application label.")
  1889. def test_app_command_multiple_apps(self):
  1890. "User AppCommands raise an error when multiple app names are provided"
  1891. args = ["app_command", "auth", "contenttypes"]
  1892. out, err = self.run_manage(args)
  1893. self.assertNoOutput(err)
  1894. self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=")
  1895. self.assertOutput(
  1896. out,
  1897. ", options=[('force_color', False), ('no_color', False), "
  1898. "('pythonpath', None), ('settings', None), ('traceback', False), "
  1899. "('verbosity', 1)]",
  1900. )
  1901. self.assertOutput(
  1902. out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options="
  1903. )
  1904. self.assertOutput(
  1905. out,
  1906. ", options=[('force_color', False), ('no_color', False), "
  1907. "('pythonpath', None), ('settings', None), ('traceback', False), "
  1908. "('verbosity', 1)]",
  1909. )
  1910. def test_app_command_invalid_app_label(self):
  1911. "User AppCommands can execute when a single app name is provided"
  1912. args = ["app_command", "NOT_AN_APP"]
  1913. out, err = self.run_manage(args)
  1914. self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.")
  1915. def test_app_command_some_invalid_app_labels(self):
  1916. "User AppCommands can execute when some of the provided app names are invalid"
  1917. args = ["app_command", "auth", "NOT_AN_APP"]
  1918. out, err = self.run_manage(args)
  1919. self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.")
  1920. def test_label_command(self):
  1921. "User LabelCommands can execute when a label is provided"
  1922. args = ["label_command", "testlabel"]
  1923. out, err = self.run_manage(args)
  1924. self.assertNoOutput(err)
  1925. self.assertOutput(
  1926. out,
  1927. "EXECUTE:LabelCommand label=testlabel, options=[('force_color', "
  1928. "False), ('no_color', False), ('pythonpath', None), ('settings', "
  1929. "None), ('traceback', False), ('verbosity', 1)]",
  1930. )
  1931. def test_label_command_no_label(self):
  1932. "User LabelCommands raise an error if no label is provided"
  1933. args = ["label_command"]
  1934. out, err = self.run_manage(args)
  1935. self.assertOutput(err, "Enter at least one label")
  1936. def test_label_command_multiple_label(self):
  1937. "User LabelCommands are executed multiple times if multiple labels are provided"
  1938. args = ["label_command", "testlabel", "anotherlabel"]
  1939. out, err = self.run_manage(args)
  1940. self.assertNoOutput(err)
  1941. self.assertOutput(
  1942. out,
  1943. "EXECUTE:LabelCommand label=testlabel, options=[('force_color', "
  1944. "False), ('no_color', False), ('pythonpath', None), "
  1945. "('settings', None), ('traceback', False), ('verbosity', 1)]",
  1946. )
  1947. self.assertOutput(
  1948. out,
  1949. "EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', "
  1950. "False), ('no_color', False), ('pythonpath', None), "
  1951. "('settings', None), ('traceback', False), ('verbosity', 1)]",
  1952. )
  1953. def test_suppress_base_options_command_help(self):
  1954. args = ["suppress_base_options_command", "--help"]
  1955. out, err = self.run_manage(args)
  1956. self.assertNoOutput(err)
  1957. self.assertOutput(out, "Test suppress base options command.")
  1958. self.assertNotInOutput(out, "input file")
  1959. self.assertOutput(out, "-h, --help")
  1960. self.assertNotInOutput(out, "--version")
  1961. self.assertNotInOutput(out, "--verbosity")
  1962. self.assertNotInOutput(out, "-v {0,1,2,3}")
  1963. self.assertNotInOutput(out, "--settings")
  1964. self.assertNotInOutput(out, "--pythonpath")
  1965. self.assertNotInOutput(out, "--traceback")
  1966. self.assertNotInOutput(out, "--no-color")
  1967. self.assertNotInOutput(out, "--force-color")
  1968. def test_suppress_base_options_command_defaults(self):
  1969. args = ["suppress_base_options_command"]
  1970. out, err = self.run_manage(args)
  1971. self.assertNoOutput(err)
  1972. self.assertOutput(
  1973. out,
  1974. "EXECUTE:SuppressBaseOptionsCommand options=[('file', None), "
  1975. "('force_color', False), ('no_color', False), "
  1976. "('pythonpath', None), ('settings', None), "
  1977. "('traceback', False), ('verbosity', 1)]",
  1978. )
  1979. class Discovery(SimpleTestCase):
  1980. def test_precedence(self):
  1981. """
  1982. Apps listed first in INSTALLED_APPS have precedence.
  1983. """
  1984. with self.settings(
  1985. INSTALLED_APPS=[
  1986. "admin_scripts.complex_app",
  1987. "admin_scripts.simple_app",
  1988. "django.contrib.auth",
  1989. "django.contrib.contenttypes",
  1990. ]
  1991. ):
  1992. out = StringIO()
  1993. call_command("duplicate", stdout=out)
  1994. self.assertEqual(out.getvalue().strip(), "complex_app")
  1995. with self.settings(
  1996. INSTALLED_APPS=[
  1997. "admin_scripts.simple_app",
  1998. "admin_scripts.complex_app",
  1999. "django.contrib.auth",
  2000. "django.contrib.contenttypes",
  2001. ]
  2002. ):
  2003. out = StringIO()
  2004. call_command("duplicate", stdout=out)
  2005. self.assertEqual(out.getvalue().strip(), "simple_app")
  2006. class ArgumentOrder(AdminScriptTestCase):
  2007. """Tests for 2-stage argument parsing scheme.
  2008. django-admin command arguments are parsed in 2 parts; the core arguments
  2009. (--settings, --traceback and --pythonpath) are parsed using a basic parser,
  2010. ignoring any unknown options. Then the full settings are
  2011. passed to the command parser, which extracts commands of interest to the
  2012. individual command.
  2013. """
  2014. def setUp(self):
  2015. super().setUp()
  2016. self.write_settings(
  2017. "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
  2018. )
  2019. self.write_settings("alternate_settings.py")
  2020. def test_setting_then_option(self):
  2021. """Options passed after settings are correctly handled."""
  2022. args = [
  2023. "base_command",
  2024. "testlabel",
  2025. "--settings=alternate_settings",
  2026. "--option_a=x",
  2027. ]
  2028. self._test(args)
  2029. def test_setting_then_short_option(self):
  2030. """Short options passed after settings are correctly handled."""
  2031. args = ["base_command", "testlabel", "--settings=alternate_settings", "-a", "x"]
  2032. self._test(args)
  2033. def test_option_then_setting(self):
  2034. """Options passed before settings are correctly handled."""
  2035. args = [
  2036. "base_command",
  2037. "testlabel",
  2038. "--option_a=x",
  2039. "--settings=alternate_settings",
  2040. ]
  2041. self._test(args)
  2042. def test_short_option_then_setting(self):
  2043. """Short options passed before settings are correctly handled."""
  2044. args = ["base_command", "testlabel", "-a", "x", "--settings=alternate_settings"]
  2045. self._test(args)
  2046. def test_option_then_setting_then_option(self):
  2047. """Options are correctly handled when they are passed before and after
  2048. a setting."""
  2049. args = [
  2050. "base_command",
  2051. "testlabel",
  2052. "--option_a=x",
  2053. "--settings=alternate_settings",
  2054. "--option_b=y",
  2055. ]
  2056. self._test(args, option_b="'y'")
  2057. def _test(self, args, option_b="'2'"):
  2058. out, err = self.run_manage(args)
  2059. self.assertNoOutput(err)
  2060. self.assertOutput(
  2061. out,
  2062. "EXECUTE:BaseCommand labels=('testlabel',), options=["
  2063. "('force_color', False), ('no_color', False), ('option_a', 'x'), "
  2064. "('option_b', %s), ('option_c', '3'), ('pythonpath', None), "
  2065. "('settings', 'alternate_settings'), ('traceback', False), "
  2066. "('verbosity', 1)]" % option_b,
  2067. )
  2068. class ExecuteFromCommandLine(SimpleTestCase):
  2069. def test_program_name_from_argv(self):
  2070. """
  2071. Program name is computed from the execute_from_command_line()'s argv
  2072. argument, not sys.argv.
  2073. """
  2074. args = ["help", "shell"]
  2075. with captured_stdout() as out, captured_stderr() as err:
  2076. with mock.patch("sys.argv", [None] + args):
  2077. execute_from_command_line(["django-admin"] + args)
  2078. self.assertIn("usage: django-admin shell", out.getvalue())
  2079. self.assertEqual(err.getvalue(), "")
  2080. @override_settings(ROOT_URLCONF="admin_scripts.urls")
  2081. class StartProject(LiveServerTestCase, AdminScriptTestCase):
  2082. available_apps = [
  2083. "admin_scripts",
  2084. "django.contrib.auth",
  2085. "django.contrib.contenttypes",
  2086. "django.contrib.sessions",
  2087. ]
  2088. def test_wrong_args(self):
  2089. """
  2090. Passing the wrong kinds of arguments outputs an error and prints usage.
  2091. """
  2092. out, err = self.run_django_admin(["startproject"])
  2093. self.assertNoOutput(out)
  2094. self.assertOutput(err, "usage:")
  2095. self.assertOutput(err, "You must provide a project name.")
  2096. def test_simple_project(self):
  2097. "Make sure the startproject management command creates a project"
  2098. args = ["startproject", "testproject"]
  2099. testproject_dir = os.path.join(self.test_dir, "testproject")
  2100. out, err = self.run_django_admin(args)
  2101. self.assertNoOutput(err)
  2102. self.assertTrue(os.path.isdir(testproject_dir))
  2103. # running again..
  2104. out, err = self.run_django_admin(args)
  2105. self.assertNoOutput(out)
  2106. self.assertOutput(
  2107. err,
  2108. "CommandError: 'testproject' conflicts with the name of an "
  2109. "existing Python module and cannot be used as a project name. "
  2110. "Please try another name.",
  2111. )
  2112. def test_invalid_project_name(self):
  2113. "Make sure the startproject management command validates a project name"
  2114. for bad_name in ("7testproject", "../testproject"):
  2115. with self.subTest(project_name=bad_name):
  2116. args = ["startproject", bad_name]
  2117. testproject_dir = os.path.join(self.test_dir, bad_name)
  2118. out, err = self.run_django_admin(args)
  2119. self.assertOutput(
  2120. err,
  2121. "Error: '%s' is not a valid project name. Please make "
  2122. "sure the name is a valid identifier." % bad_name,
  2123. )
  2124. self.assertFalse(os.path.exists(testproject_dir))
  2125. def test_importable_project_name(self):
  2126. """
  2127. startproject validates that project name doesn't clash with existing
  2128. Python modules.
  2129. """
  2130. bad_name = "os"
  2131. args = ["startproject", bad_name]
  2132. testproject_dir = os.path.join(self.test_dir, bad_name)
  2133. out, err = self.run_django_admin(args)
  2134. self.assertOutput(
  2135. err,
  2136. "CommandError: 'os' conflicts with the name of an existing "
  2137. "Python module and cannot be used as a project name. Please try "
  2138. "another name.",
  2139. )
  2140. self.assertFalse(os.path.exists(testproject_dir))
  2141. def test_simple_project_different_directory(self):
  2142. """
  2143. The startproject management command creates a project in a specific
  2144. directory.
  2145. """
  2146. args = ["startproject", "testproject", "othertestproject"]
  2147. testproject_dir = os.path.join(self.test_dir, "othertestproject")
  2148. os.mkdir(testproject_dir)
  2149. out, err = self.run_django_admin(args)
  2150. self.assertNoOutput(err)
  2151. self.assertTrue(os.path.exists(os.path.join(testproject_dir, "manage.py")))
  2152. # running again..
  2153. out, err = self.run_django_admin(args)
  2154. self.assertNoOutput(out)
  2155. self.assertOutput(
  2156. err,
  2157. "already exists. Overlaying a project into an existing directory "
  2158. "won't replace conflicting files.",
  2159. )
  2160. def test_custom_project_template(self):
  2161. """
  2162. The startproject management command is able to use a different project
  2163. template.
  2164. """
  2165. template_path = os.path.join(custom_templates_dir, "project_template")
  2166. args = ["startproject", "--template", template_path, "customtestproject"]
  2167. testproject_dir = os.path.join(self.test_dir, "customtestproject")
  2168. out, err = self.run_django_admin(args)
  2169. self.assertNoOutput(err)
  2170. self.assertTrue(os.path.isdir(testproject_dir))
  2171. self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir")))
  2172. def test_custom_project_template_non_python_files_not_formatted(self):
  2173. template_path = os.path.join(custom_templates_dir, "project_template")
  2174. args = ["startproject", "--template", template_path, "customtestproject"]
  2175. testproject_dir = os.path.join(self.test_dir, "customtestproject")
  2176. _, err = self.run_django_admin(args)
  2177. self.assertNoOutput(err)
  2178. with open(
  2179. os.path.join(template_path, "additional_dir", "requirements.in")
  2180. ) as f:
  2181. expected = f.read()
  2182. with open(
  2183. os.path.join(testproject_dir, "additional_dir", "requirements.in")
  2184. ) as f:
  2185. result = f.read()
  2186. self.assertEqual(expected, result)
  2187. def test_template_dir_with_trailing_slash(self):
  2188. "Ticket 17475: Template dir passed has a trailing path separator"
  2189. template_path = os.path.join(custom_templates_dir, "project_template" + os.sep)
  2190. args = ["startproject", "--template", template_path, "customtestproject"]
  2191. testproject_dir = os.path.join(self.test_dir, "customtestproject")
  2192. out, err = self.run_django_admin(args)
  2193. self.assertNoOutput(err)
  2194. self.assertTrue(os.path.isdir(testproject_dir))
  2195. self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir")))
  2196. def test_custom_project_template_from_tarball_by_path(self):
  2197. """
  2198. The startproject management command is able to use a different project
  2199. template from a tarball.
  2200. """
  2201. template_path = os.path.join(custom_templates_dir, "project_template.tgz")
  2202. args = ["startproject", "--template", template_path, "tarballtestproject"]
  2203. testproject_dir = os.path.join(self.test_dir, "tarballtestproject")
  2204. out, err = self.run_django_admin(args)
  2205. self.assertNoOutput(err)
  2206. self.assertTrue(os.path.isdir(testproject_dir))
  2207. self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
  2208. def test_custom_project_template_from_tarball_to_alternative_location(self):
  2209. """
  2210. Startproject can use a project template from a tarball and create it in
  2211. a specified location.
  2212. """
  2213. template_path = os.path.join(custom_templates_dir, "project_template.tgz")
  2214. args = [
  2215. "startproject",
  2216. "--template",
  2217. template_path,
  2218. "tarballtestproject",
  2219. "altlocation",
  2220. ]
  2221. testproject_dir = os.path.join(self.test_dir, "altlocation")
  2222. os.mkdir(testproject_dir)
  2223. out, err = self.run_django_admin(args)
  2224. self.assertNoOutput(err)
  2225. self.assertTrue(os.path.isdir(testproject_dir))
  2226. self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
  2227. def test_custom_project_template_from_tarball_by_url(self):
  2228. """
  2229. The startproject management command is able to use a different project
  2230. template from a tarball via a URL.
  2231. """
  2232. template_url = "%s/custom_templates/project_template.tgz" % self.live_server_url
  2233. args = ["startproject", "--template", template_url, "urltestproject"]
  2234. testproject_dir = os.path.join(self.test_dir, "urltestproject")
  2235. out, err = self.run_django_admin(args)
  2236. self.assertNoOutput(err)
  2237. self.assertTrue(os.path.isdir(testproject_dir))
  2238. self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
  2239. def test_custom_project_template_from_tarball_by_url_django_user_agent(self):
  2240. user_agent = None
  2241. def serve_template(request, *args, **kwargs):
  2242. nonlocal user_agent
  2243. user_agent = request.headers["User-Agent"]
  2244. return serve(request, *args, **kwargs)
  2245. old_urlpatterns = urls.urlpatterns[:]
  2246. try:
  2247. urls.urlpatterns += [
  2248. path(
  2249. "user_agent_check/<path:path>",
  2250. serve_template,
  2251. {"document_root": os.path.join(urls.here, "custom_templates")},
  2252. ),
  2253. ]
  2254. template_url = (
  2255. f"{self.live_server_url}/user_agent_check/project_template.tgz"
  2256. )
  2257. args = ["startproject", "--template", template_url, "urltestproject"]
  2258. _, err = self.run_django_admin(args)
  2259. self.assertNoOutput(err)
  2260. self.assertIn("Django/%s" % get_version(), user_agent)
  2261. finally:
  2262. urls.urlpatterns = old_urlpatterns
  2263. def test_project_template_tarball_url(self):
  2264. """ "
  2265. Startproject management command handles project template tar/zip balls
  2266. from non-canonical urls.
  2267. """
  2268. template_url = (
  2269. "%s/custom_templates/project_template.tgz/" % self.live_server_url
  2270. )
  2271. args = ["startproject", "--template", template_url, "urltestproject"]
  2272. testproject_dir = os.path.join(self.test_dir, "urltestproject")
  2273. out, err = self.run_django_admin(args)
  2274. self.assertNoOutput(err)
  2275. self.assertTrue(os.path.isdir(testproject_dir))
  2276. self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
  2277. def test_file_without_extension(self):
  2278. "Make sure the startproject management command is able to render custom files"
  2279. template_path = os.path.join(custom_templates_dir, "project_template")
  2280. args = [
  2281. "startproject",
  2282. "--template",
  2283. template_path,
  2284. "customtestproject",
  2285. "-e",
  2286. "txt",
  2287. "-n",
  2288. "Procfile",
  2289. ]
  2290. testproject_dir = os.path.join(self.test_dir, "customtestproject")
  2291. out, err = self.run_django_admin(args)
  2292. self.assertNoOutput(err)
  2293. self.assertTrue(os.path.isdir(testproject_dir))
  2294. self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir")))
  2295. base_path = os.path.join(testproject_dir, "additional_dir")
  2296. for f in ("Procfile", "additional_file.py", "requirements.txt"):
  2297. self.assertTrue(os.path.exists(os.path.join(base_path, f)))
  2298. with open(os.path.join(base_path, f)) as fh:
  2299. self.assertEqual(
  2300. fh.read().strip(), "# some file for customtestproject test project"
  2301. )
  2302. def test_custom_project_template_context_variables(self):
  2303. "Make sure template context variables are rendered with proper values"
  2304. template_path = os.path.join(custom_templates_dir, "project_template")
  2305. args = [
  2306. "startproject",
  2307. "--template",
  2308. template_path,
  2309. "another_project",
  2310. "project_dir",
  2311. ]
  2312. testproject_dir = os.path.join(self.test_dir, "project_dir")
  2313. os.mkdir(testproject_dir)
  2314. out, err = self.run_django_admin(args)
  2315. self.assertNoOutput(err)
  2316. test_manage_py = os.path.join(testproject_dir, "manage.py")
  2317. with open(test_manage_py) as fp:
  2318. content = fp.read()
  2319. self.assertIn('project_name = "another_project"', content)
  2320. self.assertIn('project_directory = "%s"' % testproject_dir, content)
  2321. def test_no_escaping_of_project_variables(self):
  2322. "Make sure template context variables are not html escaped"
  2323. # We're using a custom command so we need the alternate settings
  2324. self.write_settings("alternate_settings.py")
  2325. template_path = os.path.join(custom_templates_dir, "project_template")
  2326. args = [
  2327. "custom_startproject",
  2328. "--template",
  2329. template_path,
  2330. "another_project",
  2331. "project_dir",
  2332. "--extra",
  2333. "<&>",
  2334. "--settings=alternate_settings",
  2335. ]
  2336. testproject_dir = os.path.join(self.test_dir, "project_dir")
  2337. os.mkdir(testproject_dir)
  2338. out, err = self.run_manage(args)
  2339. self.assertNoOutput(err)
  2340. test_manage_py = os.path.join(testproject_dir, "additional_dir", "extra.py")
  2341. with open(test_manage_py) as fp:
  2342. content = fp.read()
  2343. self.assertIn("<&>", content)
  2344. def test_custom_project_destination_missing(self):
  2345. """
  2346. Make sure an exception is raised when the provided
  2347. destination directory doesn't exist
  2348. """
  2349. template_path = os.path.join(custom_templates_dir, "project_template")
  2350. args = [
  2351. "startproject",
  2352. "--template",
  2353. template_path,
  2354. "yet_another_project",
  2355. "project_dir2",
  2356. ]
  2357. testproject_dir = os.path.join(self.test_dir, "project_dir2")
  2358. out, err = self.run_django_admin(args)
  2359. self.assertNoOutput(out)
  2360. self.assertOutput(
  2361. err,
  2362. "Destination directory '%s' does not exist, please create it first."
  2363. % testproject_dir,
  2364. )
  2365. self.assertFalse(os.path.exists(testproject_dir))
  2366. def test_custom_project_template_with_non_ascii_templates(self):
  2367. """
  2368. The startproject management command is able to render templates with
  2369. non-ASCII content.
  2370. """
  2371. template_path = os.path.join(custom_templates_dir, "project_template")
  2372. args = [
  2373. "startproject",
  2374. "--template",
  2375. template_path,
  2376. "--extension=txt",
  2377. "customtestproject",
  2378. ]
  2379. testproject_dir = os.path.join(self.test_dir, "customtestproject")
  2380. out, err = self.run_django_admin(args)
  2381. self.assertNoOutput(err)
  2382. self.assertTrue(os.path.isdir(testproject_dir))
  2383. path = os.path.join(testproject_dir, "ticket-18091-non-ascii-template.txt")
  2384. with open(path, encoding="utf-8") as f:
  2385. self.assertEqual(
  2386. f.read().splitlines(False),
  2387. ["Some non-ASCII text for testing ticket #18091:", "üäö €"],
  2388. )
  2389. def test_custom_project_template_hidden_directory_default_excluded(self):
  2390. """Hidden directories are excluded by default."""
  2391. template_path = os.path.join(custom_templates_dir, "project_template")
  2392. args = [
  2393. "startproject",
  2394. "--template",
  2395. template_path,
  2396. "custom_project_template_hidden_directories",
  2397. "project_dir",
  2398. ]
  2399. testproject_dir = os.path.join(self.test_dir, "project_dir")
  2400. os.mkdir(testproject_dir)
  2401. _, err = self.run_django_admin(args)
  2402. self.assertNoOutput(err)
  2403. hidden_dir = os.path.join(testproject_dir, ".hidden")
  2404. self.assertIs(os.path.exists(hidden_dir), False)
  2405. def test_custom_project_template_hidden_directory_included(self):
  2406. """
  2407. Template context variables in hidden directories are rendered, if not
  2408. excluded.
  2409. """
  2410. template_path = os.path.join(custom_templates_dir, "project_template")
  2411. project_name = "custom_project_template_hidden_directories_included"
  2412. args = [
  2413. "startproject",
  2414. "--template",
  2415. template_path,
  2416. project_name,
  2417. "project_dir",
  2418. "--exclude",
  2419. ]
  2420. testproject_dir = os.path.join(self.test_dir, "project_dir")
  2421. os.mkdir(testproject_dir)
  2422. _, err = self.run_django_admin(args)
  2423. self.assertNoOutput(err)
  2424. render_py_path = os.path.join(testproject_dir, ".hidden", "render.py")
  2425. with open(render_py_path) as fp:
  2426. self.assertIn(
  2427. f"# The {project_name} should be rendered.",
  2428. fp.read(),
  2429. )
  2430. def test_custom_project_template_exclude_directory(self):
  2431. """
  2432. Excluded directories (in addition to .git and __pycache__) are not
  2433. included in the project.
  2434. """
  2435. template_path = os.path.join(custom_templates_dir, "project_template")
  2436. project_name = "custom_project_with_excluded_directories"
  2437. args = [
  2438. "startproject",
  2439. "--template",
  2440. template_path,
  2441. project_name,
  2442. "project_dir",
  2443. "--exclude",
  2444. "additional_dir",
  2445. "-x",
  2446. ".hidden",
  2447. ]
  2448. testproject_dir = os.path.join(self.test_dir, "project_dir")
  2449. os.mkdir(testproject_dir)
  2450. _, err = self.run_django_admin(args)
  2451. self.assertNoOutput(err)
  2452. excluded_directories = [
  2453. ".hidden",
  2454. "additional_dir",
  2455. ".git",
  2456. "__pycache__",
  2457. ]
  2458. for directory in excluded_directories:
  2459. self.assertIs(
  2460. os.path.exists(os.path.join(testproject_dir, directory)),
  2461. False,
  2462. )
  2463. not_excluded = os.path.join(testproject_dir, project_name)
  2464. self.assertIs(os.path.exists(not_excluded), True)
  2465. @unittest.skipIf(
  2466. sys.platform == "win32",
  2467. "Windows only partially supports umasks and chmod.",
  2468. )
  2469. def test_honor_umask(self):
  2470. _, err = self.run_django_admin(["startproject", "testproject"], umask=0o077)
  2471. self.assertNoOutput(err)
  2472. testproject_dir = os.path.join(self.test_dir, "testproject")
  2473. self.assertIs(os.path.isdir(testproject_dir), True)
  2474. tests = [
  2475. (["manage.py"], 0o700),
  2476. (["testproject"], 0o700),
  2477. (["testproject", "settings.py"], 0o600),
  2478. ]
  2479. for paths, expected_mode in tests:
  2480. file_path = os.path.join(testproject_dir, *paths)
  2481. with self.subTest(paths[-1]):
  2482. self.assertEqual(
  2483. stat.S_IMODE(os.stat(file_path).st_mode),
  2484. expected_mode,
  2485. )
  2486. class StartApp(AdminScriptTestCase):
  2487. def test_invalid_name(self):
  2488. """startapp validates that app name is a valid Python identifier."""
  2489. for bad_name in ("7testproject", "../testproject"):
  2490. with self.subTest(app_name=bad_name):
  2491. args = ["startapp", bad_name]
  2492. testproject_dir = os.path.join(self.test_dir, bad_name)
  2493. out, err = self.run_django_admin(args)
  2494. self.assertOutput(
  2495. err,
  2496. "CommandError: '{}' is not a valid app name. Please make "
  2497. "sure the name is a valid identifier.".format(bad_name),
  2498. )
  2499. self.assertFalse(os.path.exists(testproject_dir))
  2500. def test_importable_name(self):
  2501. """
  2502. startapp validates that app name doesn't clash with existing Python
  2503. modules.
  2504. """
  2505. bad_name = "os"
  2506. args = ["startapp", bad_name]
  2507. testproject_dir = os.path.join(self.test_dir, bad_name)
  2508. out, err = self.run_django_admin(args)
  2509. self.assertOutput(
  2510. err,
  2511. "CommandError: 'os' conflicts with the name of an existing "
  2512. "Python module and cannot be used as an app name. Please try "
  2513. "another name.",
  2514. )
  2515. self.assertFalse(os.path.exists(testproject_dir))
  2516. def test_invalid_target_name(self):
  2517. for bad_target in (
  2518. "invalid.dir_name",
  2519. "7invalid_dir_name",
  2520. ".invalid_dir_name",
  2521. ):
  2522. with self.subTest(bad_target):
  2523. _, err = self.run_django_admin(["startapp", "app", bad_target])
  2524. self.assertOutput(
  2525. err,
  2526. "CommandError: '%s' is not a valid app directory. Please "
  2527. "make sure the directory is a valid identifier." % bad_target,
  2528. )
  2529. def test_importable_target_name(self):
  2530. _, err = self.run_django_admin(["startapp", "app", "os"])
  2531. self.assertOutput(
  2532. err,
  2533. "CommandError: 'os' conflicts with the name of an existing Python "
  2534. "module and cannot be used as an app directory. Please try "
  2535. "another directory.",
  2536. )
  2537. def test_trailing_slash_in_target_app_directory_name(self):
  2538. app_dir = os.path.join(self.test_dir, "apps", "app1")
  2539. os.makedirs(app_dir)
  2540. _, err = self.run_django_admin(
  2541. ["startapp", "app", os.path.join("apps", "app1", "")]
  2542. )
  2543. self.assertNoOutput(err)
  2544. self.assertIs(os.path.exists(os.path.join(app_dir, "apps.py")), True)
  2545. def test_overlaying_app(self):
  2546. # Use a subdirectory so it is outside the PYTHONPATH.
  2547. os.makedirs(os.path.join(self.test_dir, "apps/app1"))
  2548. self.run_django_admin(["startapp", "app1", "apps/app1"])
  2549. out, err = self.run_django_admin(["startapp", "app2", "apps/app1"])
  2550. self.assertOutput(
  2551. err,
  2552. "already exists. Overlaying an app into an existing directory "
  2553. "won't replace conflicting files.",
  2554. )
  2555. def test_template(self):
  2556. out, err = self.run_django_admin(["startapp", "new_app"])
  2557. self.assertNoOutput(err)
  2558. app_path = os.path.join(self.test_dir, "new_app")
  2559. self.assertIs(os.path.exists(app_path), True)
  2560. with open(os.path.join(app_path, "apps.py")) as f:
  2561. content = f.read()
  2562. self.assertIn("class NewAppConfig(AppConfig)", content)
  2563. if HAS_BLACK:
  2564. test_str = 'default_auto_field = "django.db.models.BigAutoField"'
  2565. else:
  2566. test_str = "default_auto_field = 'django.db.models.BigAutoField'"
  2567. self.assertIn(test_str, content)
  2568. self.assertIn(
  2569. 'name = "new_app"' if HAS_BLACK else "name = 'new_app'",
  2570. content,
  2571. )
  2572. class DiffSettings(AdminScriptTestCase):
  2573. """Tests for diffsettings management command."""
  2574. def test_basic(self):
  2575. """Runs without error and emits settings diff."""
  2576. self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'})
  2577. args = ["diffsettings", "--settings=settings_to_diff"]
  2578. out, err = self.run_manage(args)
  2579. self.assertNoOutput(err)
  2580. self.assertOutput(out, "FOO = 'bar' ###")
  2581. # Attributes from django.conf.Settings don't appear.
  2582. self.assertNotInOutput(out, "is_overridden = ")
  2583. def test_settings_configured(self):
  2584. out, err = self.run_manage(
  2585. ["diffsettings"], manage_py="configured_settings_manage.py"
  2586. )
  2587. self.assertNoOutput(err)
  2588. self.assertOutput(out, "CUSTOM = 1 ###\nDEBUG = True")
  2589. # Attributes from django.conf.UserSettingsHolder don't appear.
  2590. self.assertNotInOutput(out, "default_settings = ")
  2591. def test_dynamic_settings_configured(self):
  2592. # Custom default settings appear.
  2593. out, err = self.run_manage(
  2594. ["diffsettings"], manage_py="configured_dynamic_settings_manage.py"
  2595. )
  2596. self.assertNoOutput(err)
  2597. self.assertOutput(out, "FOO = 'bar' ###")
  2598. def test_all(self):
  2599. """The all option also shows settings with the default value."""
  2600. self.write_settings("settings_to_diff.py", sdict={"STATIC_URL": "None"})
  2601. args = ["diffsettings", "--settings=settings_to_diff", "--all"]
  2602. out, err = self.run_manage(args)
  2603. self.assertNoOutput(err)
  2604. self.assertOutput(out, "### STATIC_URL = None")
  2605. def test_custom_default(self):
  2606. """
  2607. The --default option specifies an alternate settings module for
  2608. comparison.
  2609. """
  2610. self.write_settings(
  2611. "settings_default.py", sdict={"FOO": '"foo"', "BAR": '"bar1"'}
  2612. )
  2613. self.write_settings(
  2614. "settings_to_diff.py", sdict={"FOO": '"foo"', "BAR": '"bar2"'}
  2615. )
  2616. out, err = self.run_manage(
  2617. [
  2618. "diffsettings",
  2619. "--settings=settings_to_diff",
  2620. "--default=settings_default",
  2621. ]
  2622. )
  2623. self.assertNoOutput(err)
  2624. self.assertNotInOutput(out, "FOO")
  2625. self.assertOutput(out, "BAR = 'bar2'")
  2626. def test_unified(self):
  2627. """--output=unified emits settings diff in unified mode."""
  2628. self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'})
  2629. args = ["diffsettings", "--settings=settings_to_diff", "--output=unified"]
  2630. out, err = self.run_manage(args)
  2631. self.assertNoOutput(err)
  2632. self.assertOutput(out, "+ FOO = 'bar'")
  2633. self.assertOutput(out, "- SECRET_KEY = ''")
  2634. self.assertOutput(out, "+ SECRET_KEY = 'django_tests_secret_key'")
  2635. self.assertNotInOutput(out, " APPEND_SLASH = True")
  2636. def test_unified_all(self):
  2637. """
  2638. --output=unified --all emits settings diff in unified mode and includes
  2639. settings with the default value.
  2640. """
  2641. self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'})
  2642. args = [
  2643. "diffsettings",
  2644. "--settings=settings_to_diff",
  2645. "--output=unified",
  2646. "--all",
  2647. ]
  2648. out, err = self.run_manage(args)
  2649. self.assertNoOutput(err)
  2650. self.assertOutput(out, " APPEND_SLASH = True")
  2651. self.assertOutput(out, "+ FOO = 'bar'")
  2652. self.assertOutput(out, "- SECRET_KEY = ''")
  2653. class Dumpdata(AdminScriptTestCase):
  2654. """Tests for dumpdata management command."""
  2655. def setUp(self):
  2656. super().setUp()
  2657. self.write_settings("settings.py")
  2658. def test_pks_parsing(self):
  2659. """Regression for #20509
  2660. Test would raise an exception rather than printing an error message.
  2661. """
  2662. args = ["dumpdata", "--pks=1"]
  2663. out, err = self.run_manage(args)
  2664. self.assertOutput(err, "You can only use --pks option with one model")
  2665. self.assertNoOutput(out)
  2666. class MainModule(AdminScriptTestCase):
  2667. """python -m django works like django-admin."""
  2668. def test_program_name_in_help(self):
  2669. out, err = self.run_test(["-m", "django", "help"])
  2670. self.assertOutput(
  2671. out,
  2672. "Type 'python -m django help <subcommand>' for help on a specific "
  2673. "subcommand.",
  2674. )
  2675. class DjangoAdminSuggestions(AdminScriptTestCase):
  2676. def setUp(self):
  2677. super().setUp()
  2678. self.write_settings("settings.py")
  2679. def test_suggestions(self):
  2680. args = ["rnserver", "--settings=test_project.settings"]
  2681. out, err = self.run_django_admin(args)
  2682. self.assertNoOutput(out)
  2683. self.assertOutput(err, "Unknown command: 'rnserver'. Did you mean runserver?")
  2684. def test_no_suggestions(self):
  2685. args = ["abcdef", "--settings=test_project.settings"]
  2686. out, err = self.run_django_admin(args)
  2687. self.assertNoOutput(out)
  2688. self.assertNotInOutput(err, "Did you mean")