tests.py 113 KB

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