tests.py 120 KB

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