2
0

tests.py 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289
  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 subprocess
  11. import sys
  12. import tempfile
  13. import unittest
  14. from io import StringIO
  15. from unittest import mock
  16. from django import conf, get_version
  17. from django.conf import settings
  18. from django.core.management import (
  19. BaseCommand, CommandError, call_command, color,
  20. )
  21. from django.core.management.commands.loaddata import Command as LoaddataCommand
  22. from django.core.management.commands.runserver import (
  23. Command as RunserverCommand,
  24. )
  25. from django.core.management.commands.testserver import (
  26. Command as TestserverCommand,
  27. )
  28. from django.db import ConnectionHandler, connection
  29. from django.db.migrations.recorder import MigrationRecorder
  30. from django.test import (
  31. LiveServerTestCase, SimpleTestCase, TestCase, override_settings,
  32. )
  33. custom_templates_dir = os.path.join(os.path.dirname(__file__), 'custom_templates')
  34. SYSTEM_CHECK_MSG = 'System check identified no issues'
  35. class AdminScriptTestCase(SimpleTestCase):
  36. def setUp(self):
  37. tmpdir = tempfile.TemporaryDirectory()
  38. self.addCleanup(tmpdir.cleanup)
  39. # os.path.realpath() is required for temporary directories on macOS,
  40. # where `/var` is a symlink to `/private/var`.
  41. self.test_dir = os.path.realpath(os.path.join(tmpdir.name, 'test_project'))
  42. os.mkdir(self.test_dir)
  43. def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None):
  44. if is_dir:
  45. settings_dir = os.path.join(self.test_dir, filename)
  46. os.mkdir(settings_dir)
  47. settings_file_path = os.path.join(settings_dir, '__init__.py')
  48. else:
  49. settings_file_path = os.path.join(self.test_dir, filename)
  50. with open(settings_file_path, 'w') as settings_file:
  51. settings_file.write('# Settings file automatically generated by admin_scripts test case\n')
  52. if extra:
  53. settings_file.write("%s\n" % extra)
  54. exports = [
  55. 'DATABASES',
  56. 'ROOT_URLCONF',
  57. 'SECRET_KEY',
  58. ]
  59. for s in exports:
  60. if hasattr(settings, s):
  61. o = getattr(settings, s)
  62. if not isinstance(o, (dict, tuple, list)):
  63. o = "'%s'" % o
  64. settings_file.write("%s = %s\n" % (s, o))
  65. if apps is None:
  66. apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts']
  67. settings_file.write("INSTALLED_APPS = %s\n" % apps)
  68. if sdict:
  69. for k, v in sdict.items():
  70. settings_file.write("%s = %s\n" % (k, v))
  71. def _ext_backend_paths(self):
  72. """
  73. Returns the paths for any external backend packages.
  74. """
  75. paths = []
  76. for backend in settings.DATABASES.values():
  77. package = backend['ENGINE'].split('.')[0]
  78. if package != 'django':
  79. backend_pkg = __import__(package)
  80. backend_dir = os.path.dirname(backend_pkg.__file__)
  81. paths.append(os.path.dirname(backend_dir))
  82. return paths
  83. def run_test(self, args, settings_file=None, apps=None):
  84. base_dir = os.path.dirname(self.test_dir)
  85. # The base dir for Django's tests is one level up.
  86. tests_dir = os.path.dirname(os.path.dirname(__file__))
  87. # The base dir for Django is one level above the test dir. We don't use
  88. # `import django` to figure that out, so we don't pick up a Django
  89. # from site-packages or similar.
  90. django_dir = os.path.dirname(tests_dir)
  91. ext_backend_base_dirs = self._ext_backend_paths()
  92. # Define a temporary environment for the subprocess
  93. test_environ = os.environ.copy()
  94. # Set the test environment
  95. if settings_file:
  96. test_environ['DJANGO_SETTINGS_MODULE'] = settings_file
  97. elif 'DJANGO_SETTINGS_MODULE' in test_environ:
  98. del test_environ['DJANGO_SETTINGS_MODULE']
  99. python_path = [base_dir, django_dir, tests_dir]
  100. python_path.extend(ext_backend_base_dirs)
  101. test_environ['PYTHONPATH'] = os.pathsep.join(python_path)
  102. test_environ['PYTHONWARNINGS'] = ''
  103. p = subprocess.run(
  104. [sys.executable, *args],
  105. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  106. cwd=self.test_dir,
  107. env=test_environ, universal_newlines=True,
  108. )
  109. return p.stdout, p.stderr
  110. def run_django_admin(self, args, settings_file=None):
  111. return self.run_test(['-m', 'django', *args], settings_file)
  112. def run_manage(self, args, settings_file=None, manage_py=None):
  113. template_manage_py = (
  114. os.path.join(os.path.dirname(__file__), manage_py)
  115. if manage_py else
  116. os.path.join(os.path.dirname(conf.__file__), 'project_template', 'manage.py-tpl')
  117. )
  118. test_manage_py = os.path.join(self.test_dir, 'manage.py')
  119. shutil.copyfile(template_manage_py, test_manage_py)
  120. with open(test_manage_py) as fp:
  121. manage_py_contents = fp.read()
  122. manage_py_contents = manage_py_contents.replace(
  123. "{{ project_name }}", "test_project")
  124. with open(test_manage_py, 'w') as fp:
  125. fp.write(manage_py_contents)
  126. return self.run_test(['./manage.py', *args], settings_file)
  127. def assertNoOutput(self, stream):
  128. "Utility assertion: assert that the given stream is empty"
  129. self.assertEqual(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream)
  130. def assertOutput(self, stream, msg, regex=False):
  131. "Utility assertion: assert that the given message exists in the output"
  132. if regex:
  133. self.assertIsNotNone(
  134. re.search(msg, stream),
  135. "'%s' does not match actual output text '%s'" % (msg, stream)
  136. )
  137. else:
  138. self.assertIn(msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream))
  139. def assertNotInOutput(self, stream, msg):
  140. "Utility assertion: assert that the given message doesn't exist in the output"
  141. self.assertNotIn(msg, stream, "'%s' matches actual output text '%s'" % (msg, stream))
  142. ##########################################################################
  143. # DJANGO ADMIN TESTS
  144. # This first series of test classes checks the environment processing
  145. # of the django-admin.py script
  146. ##########################################################################
  147. class DjangoAdminNoSettings(AdminScriptTestCase):
  148. "A series of tests for django-admin.py when there is no settings.py file."
  149. def test_builtin_command(self):
  150. "no settings: django-admin builtin commands fail with an error when no settings provided"
  151. args = ['check', 'admin_scripts']
  152. out, err = self.run_django_admin(args)
  153. self.assertNoOutput(out)
  154. self.assertOutput(err, 'settings are not configured')
  155. def test_builtin_with_bad_settings(self):
  156. "no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist"
  157. args = ['check', '--settings=bad_settings', 'admin_scripts']
  158. out, err = self.run_django_admin(args)
  159. self.assertNoOutput(out)
  160. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  161. def test_builtin_with_bad_environment(self):
  162. "no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist"
  163. args = ['check', 'admin_scripts']
  164. out, err = self.run_django_admin(args, 'bad_settings')
  165. self.assertNoOutput(out)
  166. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  167. def test_commands_with_invalid_settings(self):
  168. """"
  169. Commands that don't require settings succeed if the settings file
  170. doesn't exist.
  171. """
  172. args = ['startproject']
  173. out, err = self.run_django_admin(args, settings_file='bad_settings')
  174. self.assertNoOutput(out)
  175. self.assertOutput(err, "You must provide a project name", regex=True)
  176. class DjangoAdminDefaultSettings(AdminScriptTestCase):
  177. """A series of tests for django-admin.py when using a settings.py file that
  178. contains the test application.
  179. """
  180. def setUp(self):
  181. super().setUp()
  182. self.write_settings('settings.py')
  183. def test_builtin_command(self):
  184. "default: django-admin builtin commands fail with an error when no settings provided"
  185. args = ['check', 'admin_scripts']
  186. out, err = self.run_django_admin(args)
  187. self.assertNoOutput(out)
  188. self.assertOutput(err, 'settings are not configured')
  189. def test_builtin_with_settings(self):
  190. "default: django-admin builtin commands succeed if settings are provided as argument"
  191. args = ['check', '--settings=test_project.settings', 'admin_scripts']
  192. out, err = self.run_django_admin(args)
  193. self.assertNoOutput(err)
  194. self.assertOutput(out, SYSTEM_CHECK_MSG)
  195. def test_builtin_with_environment(self):
  196. "default: django-admin builtin commands succeed if settings are provided in the environment"
  197. args = ['check', 'admin_scripts']
  198. out, err = self.run_django_admin(args, 'test_project.settings')
  199. self.assertNoOutput(err)
  200. self.assertOutput(out, SYSTEM_CHECK_MSG)
  201. def test_builtin_with_bad_settings(self):
  202. "default: django-admin builtin commands fail if settings file (from argument) doesn't exist"
  203. args = ['check', '--settings=bad_settings', 'admin_scripts']
  204. out, err = self.run_django_admin(args)
  205. self.assertNoOutput(out)
  206. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  207. def test_builtin_with_bad_environment(self):
  208. "default: django-admin builtin commands fail if settings file (from environment) doesn't exist"
  209. args = ['check', 'admin_scripts']
  210. out, err = self.run_django_admin(args, 'bad_settings')
  211. self.assertNoOutput(out)
  212. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  213. def test_custom_command(self):
  214. "default: django-admin can't execute user commands if it isn't provided settings"
  215. args = ['noargs_command']
  216. out, err = self.run_django_admin(args)
  217. self.assertNoOutput(out)
  218. self.assertOutput(err, "No Django settings specified")
  219. self.assertOutput(err, "Unknown command: 'noargs_command'")
  220. def test_custom_command_with_settings(self):
  221. "default: django-admin can execute user commands if settings are provided as argument"
  222. args = ['noargs_command', '--settings=test_project.settings']
  223. out, err = self.run_django_admin(args)
  224. self.assertNoOutput(err)
  225. self.assertOutput(out, "EXECUTE: noargs_command")
  226. def test_custom_command_with_environment(self):
  227. "default: django-admin can execute user commands if settings are provided in environment"
  228. args = ['noargs_command']
  229. out, err = self.run_django_admin(args, 'test_project.settings')
  230. self.assertNoOutput(err)
  231. self.assertOutput(out, "EXECUTE: noargs_command")
  232. class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
  233. """A series of tests for django-admin.py when using a settings.py file that
  234. contains the test application specified using a full path.
  235. """
  236. def setUp(self):
  237. super().setUp()
  238. self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes',
  239. 'admin_scripts', 'admin_scripts.complex_app'])
  240. def test_builtin_command(self):
  241. "fulldefault: django-admin builtin commands fail with an error when no settings provided"
  242. args = ['check', 'admin_scripts']
  243. out, err = self.run_django_admin(args)
  244. self.assertNoOutput(out)
  245. self.assertOutput(err, 'settings are not configured')
  246. def test_builtin_with_settings(self):
  247. "fulldefault: django-admin builtin commands succeed if a settings file is provided"
  248. args = ['check', '--settings=test_project.settings', 'admin_scripts']
  249. out, err = self.run_django_admin(args)
  250. self.assertNoOutput(err)
  251. self.assertOutput(out, SYSTEM_CHECK_MSG)
  252. def test_builtin_with_environment(self):
  253. "fulldefault: django-admin builtin commands succeed if the environment contains settings"
  254. args = ['check', 'admin_scripts']
  255. out, err = self.run_django_admin(args, 'test_project.settings')
  256. self.assertNoOutput(err)
  257. self.assertOutput(out, SYSTEM_CHECK_MSG)
  258. def test_builtin_with_bad_settings(self):
  259. "fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist"
  260. args = ['check', '--settings=bad_settings', 'admin_scripts']
  261. out, err = self.run_django_admin(args)
  262. self.assertNoOutput(out)
  263. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  264. def test_builtin_with_bad_environment(self):
  265. "fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist"
  266. args = ['check', 'admin_scripts']
  267. out, err = self.run_django_admin(args, 'bad_settings')
  268. self.assertNoOutput(out)
  269. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  270. def test_custom_command(self):
  271. "fulldefault: django-admin can't execute user commands unless settings are provided"
  272. args = ['noargs_command']
  273. out, err = self.run_django_admin(args)
  274. self.assertNoOutput(out)
  275. self.assertOutput(err, "No Django settings specified")
  276. self.assertOutput(err, "Unknown command: 'noargs_command'")
  277. def test_custom_command_with_settings(self):
  278. "fulldefault: django-admin can execute user commands if settings are provided as argument"
  279. args = ['noargs_command', '--settings=test_project.settings']
  280. out, err = self.run_django_admin(args)
  281. self.assertNoOutput(err)
  282. self.assertOutput(out, "EXECUTE: noargs_command")
  283. def test_custom_command_with_environment(self):
  284. "fulldefault: django-admin can execute user commands if settings are provided in environment"
  285. args = ['noargs_command']
  286. out, err = self.run_django_admin(args, 'test_project.settings')
  287. self.assertNoOutput(err)
  288. self.assertOutput(out, "EXECUTE: noargs_command")
  289. class DjangoAdminMinimalSettings(AdminScriptTestCase):
  290. """A series of tests for django-admin.py when using a settings.py file that
  291. doesn't contain the test application.
  292. """
  293. def setUp(self):
  294. super().setUp()
  295. self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes'])
  296. def test_builtin_command(self):
  297. "minimal: django-admin builtin commands fail with an error when no settings provided"
  298. args = ['check', 'admin_scripts']
  299. out, err = self.run_django_admin(args)
  300. self.assertNoOutput(out)
  301. self.assertOutput(err, 'settings are not configured')
  302. def test_builtin_with_settings(self):
  303. "minimal: django-admin builtin commands fail if settings are provided as argument"
  304. args = ['check', '--settings=test_project.settings', 'admin_scripts']
  305. out, err = self.run_django_admin(args)
  306. self.assertNoOutput(out)
  307. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  308. def test_builtin_with_environment(self):
  309. "minimal: django-admin builtin commands fail if settings are provided in the environment"
  310. args = ['check', 'admin_scripts']
  311. out, err = self.run_django_admin(args, 'test_project.settings')
  312. self.assertNoOutput(out)
  313. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  314. def test_builtin_with_bad_settings(self):
  315. "minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist"
  316. args = ['check', '--settings=bad_settings', 'admin_scripts']
  317. out, err = self.run_django_admin(args)
  318. self.assertNoOutput(out)
  319. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  320. def test_builtin_with_bad_environment(self):
  321. "minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist"
  322. args = ['check', 'admin_scripts']
  323. out, err = self.run_django_admin(args, 'bad_settings')
  324. self.assertNoOutput(out)
  325. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  326. def test_custom_command(self):
  327. "minimal: django-admin can't execute user commands unless settings are provided"
  328. args = ['noargs_command']
  329. out, err = self.run_django_admin(args)
  330. self.assertNoOutput(out)
  331. self.assertOutput(err, "No Django settings specified")
  332. self.assertOutput(err, "Unknown command: 'noargs_command'")
  333. def test_custom_command_with_settings(self):
  334. "minimal: django-admin can't execute user commands, even if settings are provided as argument"
  335. args = ['noargs_command', '--settings=test_project.settings']
  336. out, err = self.run_django_admin(args)
  337. self.assertNoOutput(out)
  338. self.assertOutput(err, "Unknown command: 'noargs_command'")
  339. def test_custom_command_with_environment(self):
  340. "minimal: django-admin can't execute user commands, even if settings are provided in environment"
  341. args = ['noargs_command']
  342. out, err = self.run_django_admin(args, 'test_project.settings')
  343. self.assertNoOutput(out)
  344. self.assertOutput(err, "Unknown command: 'noargs_command'")
  345. class DjangoAdminAlternateSettings(AdminScriptTestCase):
  346. """A series of tests for django-admin.py when using a settings file
  347. with a name other than 'settings.py'.
  348. """
  349. def setUp(self):
  350. super().setUp()
  351. self.write_settings('alternate_settings.py')
  352. def test_builtin_command(self):
  353. "alternate: django-admin builtin commands fail with an error when no settings provided"
  354. args = ['check', 'admin_scripts']
  355. out, err = self.run_django_admin(args)
  356. self.assertNoOutput(out)
  357. self.assertOutput(err, 'settings are not configured')
  358. def test_builtin_with_settings(self):
  359. "alternate: django-admin builtin commands succeed if settings are provided as argument"
  360. args = ['check', '--settings=test_project.alternate_settings', 'admin_scripts']
  361. out, err = self.run_django_admin(args)
  362. self.assertNoOutput(err)
  363. self.assertOutput(out, SYSTEM_CHECK_MSG)
  364. def test_builtin_with_environment(self):
  365. "alternate: django-admin builtin commands succeed if settings are provided in the environment"
  366. args = ['check', 'admin_scripts']
  367. out, err = self.run_django_admin(args, 'test_project.alternate_settings')
  368. self.assertNoOutput(err)
  369. self.assertOutput(out, SYSTEM_CHECK_MSG)
  370. def test_builtin_with_bad_settings(self):
  371. "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist"
  372. args = ['check', '--settings=bad_settings', 'admin_scripts']
  373. out, err = self.run_django_admin(args)
  374. self.assertNoOutput(out)
  375. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  376. def test_builtin_with_bad_environment(self):
  377. "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist"
  378. args = ['check', 'admin_scripts']
  379. out, err = self.run_django_admin(args, 'bad_settings')
  380. self.assertNoOutput(out)
  381. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  382. def test_custom_command(self):
  383. "alternate: django-admin can't execute user commands unless settings are provided"
  384. args = ['noargs_command']
  385. out, err = self.run_django_admin(args)
  386. self.assertNoOutput(out)
  387. self.assertOutput(err, "No Django settings specified")
  388. self.assertOutput(err, "Unknown command: 'noargs_command'")
  389. def test_custom_command_with_settings(self):
  390. "alternate: django-admin can execute user commands if settings are provided as argument"
  391. args = ['noargs_command', '--settings=test_project.alternate_settings']
  392. out, err = self.run_django_admin(args)
  393. self.assertNoOutput(err)
  394. self.assertOutput(out, "EXECUTE: noargs_command")
  395. def test_custom_command_with_environment(self):
  396. "alternate: django-admin can execute user commands if settings are provided in environment"
  397. args = ['noargs_command']
  398. out, err = self.run_django_admin(args, 'test_project.alternate_settings')
  399. self.assertNoOutput(err)
  400. self.assertOutput(out, "EXECUTE: noargs_command")
  401. class DjangoAdminMultipleSettings(AdminScriptTestCase):
  402. """A series of tests for django-admin.py when multiple settings files
  403. (including the default 'settings.py') are available. The default settings
  404. file is insufficient for performing the operations described, so the
  405. alternate settings must be used by the running script.
  406. """
  407. def setUp(self):
  408. super().setUp()
  409. self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes'])
  410. self.write_settings('alternate_settings.py')
  411. def test_builtin_command(self):
  412. "alternate: django-admin builtin commands fail with an error when no settings provided"
  413. args = ['check', 'admin_scripts']
  414. out, err = self.run_django_admin(args)
  415. self.assertNoOutput(out)
  416. self.assertOutput(err, 'settings are not configured')
  417. def test_builtin_with_settings(self):
  418. "alternate: django-admin builtin commands succeed if settings are provided as argument"
  419. args = ['check', '--settings=test_project.alternate_settings', 'admin_scripts']
  420. out, err = self.run_django_admin(args)
  421. self.assertNoOutput(err)
  422. self.assertOutput(out, SYSTEM_CHECK_MSG)
  423. def test_builtin_with_environment(self):
  424. "alternate: django-admin builtin commands succeed if settings are provided in the environment"
  425. args = ['check', 'admin_scripts']
  426. out, err = self.run_django_admin(args, 'test_project.alternate_settings')
  427. self.assertNoOutput(err)
  428. self.assertOutput(out, SYSTEM_CHECK_MSG)
  429. def test_builtin_with_bad_settings(self):
  430. "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist"
  431. args = ['check', '--settings=bad_settings', 'admin_scripts']
  432. out, err = self.run_django_admin(args)
  433. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  434. def test_builtin_with_bad_environment(self):
  435. "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist"
  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. "alternate: 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. "alternate: django-admin can execute user commands if settings are provided as argument"
  449. args = ['noargs_command', '--settings=test_project.alternate_settings']
  450. out, err = self.run_django_admin(args)
  451. self.assertNoOutput(err)
  452. self.assertOutput(out, "EXECUTE: noargs_command")
  453. def test_custom_command_with_environment(self):
  454. "alternate: django-admin can execute user commands if settings are provided in environment"
  455. args = ['noargs_command']
  456. out, err = self.run_django_admin(args, 'test_project.alternate_settings')
  457. self.assertNoOutput(err)
  458. self.assertOutput(out, "EXECUTE: noargs_command")
  459. class DjangoAdminSettingsDirectory(AdminScriptTestCase):
  460. """
  461. A series of tests for django-admin.py when the settings file is in a
  462. directory. (see #9751).
  463. """
  464. def setUp(self):
  465. super().setUp()
  466. self.write_settings('settings', is_dir=True)
  467. def test_setup_environ(self):
  468. "directory: startapp creates the correct directory"
  469. args = ['startapp', 'settings_test']
  470. app_path = os.path.join(self.test_dir, 'settings_test')
  471. out, err = self.run_django_admin(args, 'test_project.settings')
  472. self.assertNoOutput(err)
  473. self.assertTrue(os.path.exists(app_path))
  474. with open(os.path.join(app_path, 'apps.py')) as f:
  475. content = f.read()
  476. self.assertIn("class SettingsTestConfig(AppConfig)", content)
  477. self.assertIn("name = 'settings_test'", content)
  478. def test_setup_environ_custom_template(self):
  479. "directory: startapp creates the correct directory with a custom template"
  480. template_path = os.path.join(custom_templates_dir, 'app_template')
  481. args = ['startapp', '--template', template_path, 'custom_settings_test']
  482. app_path = os.path.join(self.test_dir, 'custom_settings_test')
  483. out, err = self.run_django_admin(args, 'test_project.settings')
  484. self.assertNoOutput(err)
  485. self.assertTrue(os.path.exists(app_path))
  486. self.assertTrue(os.path.exists(os.path.join(app_path, 'api.py')))
  487. def test_startapp_unicode_name(self):
  488. """startapp creates the correct directory with Unicode characters."""
  489. args = ['startapp', 'こんにちは']
  490. app_path = os.path.join(self.test_dir, 'こんにちは')
  491. out, err = self.run_django_admin(args, 'test_project.settings')
  492. self.assertNoOutput(err)
  493. self.assertTrue(os.path.exists(app_path))
  494. with open(os.path.join(app_path, 'apps.py'), encoding='utf8') as f:
  495. content = f.read()
  496. self.assertIn("class こんにちはConfig(AppConfig)", content)
  497. self.assertIn("name = 'こんにちは'", content)
  498. def test_builtin_command(self):
  499. "directory: django-admin builtin commands fail with an error when no settings provided"
  500. args = ['check', 'admin_scripts']
  501. out, err = self.run_django_admin(args)
  502. self.assertNoOutput(out)
  503. self.assertOutput(err, 'settings are not configured')
  504. def test_builtin_with_bad_settings(self):
  505. "directory: django-admin builtin commands fail if settings file (from argument) doesn't exist"
  506. args = ['check', '--settings=bad_settings', 'admin_scripts']
  507. out, err = self.run_django_admin(args)
  508. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  509. def test_builtin_with_bad_environment(self):
  510. "directory: django-admin builtin commands fail if settings file (from environment) doesn't exist"
  511. args = ['check', 'admin_scripts']
  512. out, err = self.run_django_admin(args, 'bad_settings')
  513. self.assertNoOutput(out)
  514. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  515. def test_custom_command(self):
  516. "directory: django-admin can't execute user commands unless settings are provided"
  517. args = ['noargs_command']
  518. out, err = self.run_django_admin(args)
  519. self.assertNoOutput(out)
  520. self.assertOutput(err, "No Django settings specified")
  521. self.assertOutput(err, "Unknown command: 'noargs_command'")
  522. def test_builtin_with_settings(self):
  523. "directory: django-admin builtin commands succeed if settings are provided as argument"
  524. args = ['check', '--settings=test_project.settings', 'admin_scripts']
  525. out, err = self.run_django_admin(args)
  526. self.assertNoOutput(err)
  527. self.assertOutput(out, SYSTEM_CHECK_MSG)
  528. def test_builtin_with_environment(self):
  529. "directory: django-admin builtin commands succeed if settings are provided in the environment"
  530. args = ['check', 'admin_scripts']
  531. out, err = self.run_django_admin(args, 'test_project.settings')
  532. self.assertNoOutput(err)
  533. self.assertOutput(out, SYSTEM_CHECK_MSG)
  534. ##########################################################################
  535. # MANAGE.PY TESTS
  536. # This next series of test classes checks the environment processing
  537. # of the generated manage.py script
  538. ##########################################################################
  539. class ManageManuallyConfiguredSettings(AdminScriptTestCase):
  540. """Customized manage.py calling settings.configure()."""
  541. def test_non_existent_command_output(self):
  542. out, err = self.run_manage(['invalid_command'], manage_py='configured_settings_manage.py')
  543. self.assertNoOutput(out)
  544. self.assertOutput(err, "Unknown command: 'invalid_command'")
  545. self.assertNotInOutput(err, 'No Django settings specified')
  546. class ManageNoSettings(AdminScriptTestCase):
  547. "A series of tests for manage.py when there is no settings.py file."
  548. def test_builtin_command(self):
  549. "no settings: manage.py builtin commands fail with an error when no settings provided"
  550. args = ['check', 'admin_scripts']
  551. out, err = self.run_manage(args)
  552. self.assertNoOutput(out)
  553. self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True)
  554. def test_builtin_with_bad_settings(self):
  555. "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist"
  556. args = ['check', '--settings=bad_settings', 'admin_scripts']
  557. out, err = self.run_manage(args)
  558. self.assertNoOutput(out)
  559. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  560. def test_builtin_with_bad_environment(self):
  561. "no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist"
  562. args = ['check', 'admin_scripts']
  563. out, err = self.run_manage(args, 'bad_settings')
  564. self.assertNoOutput(out)
  565. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  566. class ManageDefaultSettings(AdminScriptTestCase):
  567. """A series of tests for manage.py when using a settings.py file that
  568. contains the test application.
  569. """
  570. def setUp(self):
  571. super().setUp()
  572. self.write_settings('settings.py')
  573. def test_builtin_command(self):
  574. "default: manage.py builtin commands succeed when default settings are appropriate"
  575. args = ['check', 'admin_scripts']
  576. out, err = self.run_manage(args)
  577. self.assertNoOutput(err)
  578. self.assertOutput(out, SYSTEM_CHECK_MSG)
  579. def test_builtin_with_settings(self):
  580. "default: manage.py builtin commands succeed if settings are provided as argument"
  581. args = ['check', '--settings=test_project.settings', 'admin_scripts']
  582. out, err = self.run_manage(args)
  583. self.assertNoOutput(err)
  584. self.assertOutput(out, SYSTEM_CHECK_MSG)
  585. def test_builtin_with_environment(self):
  586. "default: manage.py builtin commands succeed if settings are provided in the environment"
  587. args = ['check', 'admin_scripts']
  588. out, err = self.run_manage(args, 'test_project.settings')
  589. self.assertNoOutput(err)
  590. self.assertOutput(out, SYSTEM_CHECK_MSG)
  591. def test_builtin_with_bad_settings(self):
  592. "default: manage.py builtin commands succeed if settings file (from argument) doesn't exist"
  593. args = ['check', '--settings=bad_settings', 'admin_scripts']
  594. out, err = self.run_manage(args)
  595. self.assertNoOutput(out)
  596. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  597. def test_builtin_with_bad_environment(self):
  598. "default: manage.py builtin commands fail if settings file (from environment) doesn't exist"
  599. args = ['check', 'admin_scripts']
  600. out, err = self.run_manage(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. "default: manage.py can execute user commands when default settings are appropriate"
  605. args = ['noargs_command']
  606. out, err = self.run_manage(args)
  607. self.assertNoOutput(err)
  608. self.assertOutput(out, "EXECUTE: noargs_command")
  609. def test_custom_command_with_settings(self):
  610. "default: manage.py can execute user commands when settings are provided as argument"
  611. args = ['noargs_command', '--settings=test_project.settings']
  612. out, err = self.run_manage(args)
  613. self.assertNoOutput(err)
  614. self.assertOutput(out, "EXECUTE: noargs_command")
  615. def test_custom_command_with_environment(self):
  616. "default: manage.py can execute user commands when settings are provided in environment"
  617. args = ['noargs_command']
  618. out, err = self.run_manage(args, 'test_project.settings')
  619. self.assertNoOutput(err)
  620. self.assertOutput(out, "EXECUTE: noargs_command")
  621. class ManageFullPathDefaultSettings(AdminScriptTestCase):
  622. """A series of tests for manage.py when using a settings.py file that
  623. contains the test application specified using a full path.
  624. """
  625. def setUp(self):
  626. super().setUp()
  627. self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts'])
  628. def test_builtin_command(self):
  629. "fulldefault: manage.py builtin commands succeed when default settings are appropriate"
  630. args = ['check', 'admin_scripts']
  631. out, err = self.run_manage(args)
  632. self.assertNoOutput(err)
  633. self.assertOutput(out, SYSTEM_CHECK_MSG)
  634. def test_builtin_with_settings(self):
  635. "fulldefault: manage.py builtin commands succeed if settings are provided as argument"
  636. args = ['check', '--settings=test_project.settings', 'admin_scripts']
  637. out, err = self.run_manage(args)
  638. self.assertNoOutput(err)
  639. self.assertOutput(out, SYSTEM_CHECK_MSG)
  640. def test_builtin_with_environment(self):
  641. "fulldefault: manage.py builtin commands succeed if settings are provided in the environment"
  642. args = ['check', 'admin_scripts']
  643. out, err = self.run_manage(args, 'test_project.settings')
  644. self.assertNoOutput(err)
  645. self.assertOutput(out, SYSTEM_CHECK_MSG)
  646. def test_builtin_with_bad_settings(self):
  647. "fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist"
  648. args = ['check', '--settings=bad_settings', 'admin_scripts']
  649. out, err = self.run_manage(args)
  650. self.assertNoOutput(out)
  651. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  652. def test_builtin_with_bad_environment(self):
  653. "fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist"
  654. args = ['check', 'admin_scripts']
  655. out, err = self.run_manage(args, 'bad_settings')
  656. self.assertNoOutput(out)
  657. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  658. def test_custom_command(self):
  659. "fulldefault: manage.py can execute user commands when default settings are appropriate"
  660. args = ['noargs_command']
  661. out, err = self.run_manage(args)
  662. self.assertNoOutput(err)
  663. self.assertOutput(out, "EXECUTE: noargs_command")
  664. def test_custom_command_with_settings(self):
  665. "fulldefault: manage.py can execute user commands when settings are provided as argument"
  666. args = ['noargs_command', '--settings=test_project.settings']
  667. out, err = self.run_manage(args)
  668. self.assertNoOutput(err)
  669. self.assertOutput(out, "EXECUTE: noargs_command")
  670. def test_custom_command_with_environment(self):
  671. "fulldefault: manage.py can execute user commands when settings are provided in environment"
  672. args = ['noargs_command']
  673. out, err = self.run_manage(args, 'test_project.settings')
  674. self.assertNoOutput(err)
  675. self.assertOutput(out, "EXECUTE: noargs_command")
  676. class ManageMinimalSettings(AdminScriptTestCase):
  677. """A series of tests for manage.py when using a settings.py file that
  678. doesn't contain the test application.
  679. """
  680. def setUp(self):
  681. super().setUp()
  682. self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes'])
  683. def test_builtin_command(self):
  684. "minimal: manage.py builtin commands fail with an error when no settings provided"
  685. args = ['check', 'admin_scripts']
  686. out, err = self.run_manage(args)
  687. self.assertNoOutput(out)
  688. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  689. def test_builtin_with_settings(self):
  690. "minimal: manage.py builtin commands fail if settings are provided as argument"
  691. args = ['check', '--settings=test_project.settings', 'admin_scripts']
  692. out, err = self.run_manage(args)
  693. self.assertNoOutput(out)
  694. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  695. def test_builtin_with_environment(self):
  696. "minimal: manage.py builtin commands fail if settings are provided in the environment"
  697. args = ['check', 'admin_scripts']
  698. out, err = self.run_manage(args, 'test_project.settings')
  699. self.assertNoOutput(out)
  700. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  701. def test_builtin_with_bad_settings(self):
  702. "minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist"
  703. args = ['check', '--settings=bad_settings', 'admin_scripts']
  704. out, err = self.run_manage(args)
  705. self.assertNoOutput(out)
  706. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  707. def test_builtin_with_bad_environment(self):
  708. "minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist"
  709. args = ['check', 'admin_scripts']
  710. out, err = self.run_manage(args, 'bad_settings')
  711. self.assertNoOutput(out)
  712. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  713. def test_custom_command(self):
  714. "minimal: manage.py can't execute user commands without appropriate settings"
  715. args = ['noargs_command']
  716. out, err = self.run_manage(args)
  717. self.assertNoOutput(out)
  718. self.assertOutput(err, "Unknown command: 'noargs_command'")
  719. def test_custom_command_with_settings(self):
  720. "minimal: manage.py can't execute user commands, even if settings are provided as argument"
  721. args = ['noargs_command', '--settings=test_project.settings']
  722. out, err = self.run_manage(args)
  723. self.assertNoOutput(out)
  724. self.assertOutput(err, "Unknown command: 'noargs_command'")
  725. def test_custom_command_with_environment(self):
  726. "minimal: manage.py can't execute user commands, even if settings are provided in environment"
  727. args = ['noargs_command']
  728. out, err = self.run_manage(args, 'test_project.settings')
  729. self.assertNoOutput(out)
  730. self.assertOutput(err, "Unknown command: 'noargs_command'")
  731. class ManageAlternateSettings(AdminScriptTestCase):
  732. """A series of tests for manage.py when using a settings file
  733. with a name other than 'settings.py'.
  734. """
  735. def setUp(self):
  736. super().setUp()
  737. self.write_settings('alternate_settings.py')
  738. def test_builtin_command(self):
  739. "alternate: manage.py builtin commands fail with an error when no default settings provided"
  740. args = ['check', 'admin_scripts']
  741. out, err = self.run_manage(args)
  742. self.assertNoOutput(out)
  743. self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True)
  744. def test_builtin_with_settings(self):
  745. "alternate: manage.py builtin commands work with settings provided as argument"
  746. args = ['check', '--settings=alternate_settings', 'admin_scripts']
  747. out, err = self.run_manage(args)
  748. self.assertOutput(out, SYSTEM_CHECK_MSG)
  749. self.assertNoOutput(err)
  750. def test_builtin_with_environment(self):
  751. "alternate: manage.py builtin commands work if settings are provided in the environment"
  752. args = ['check', 'admin_scripts']
  753. out, err = self.run_manage(args, 'alternate_settings')
  754. self.assertOutput(out, SYSTEM_CHECK_MSG)
  755. self.assertNoOutput(err)
  756. def test_builtin_with_bad_settings(self):
  757. "alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist"
  758. args = ['check', '--settings=bad_settings', 'admin_scripts']
  759. out, err = self.run_manage(args)
  760. self.assertNoOutput(out)
  761. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  762. def test_builtin_with_bad_environment(self):
  763. "alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist"
  764. args = ['check', 'admin_scripts']
  765. out, err = self.run_manage(args, 'bad_settings')
  766. self.assertNoOutput(out)
  767. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  768. def test_custom_command(self):
  769. "alternate: manage.py can't execute user commands without settings"
  770. args = ['noargs_command']
  771. out, err = self.run_manage(args)
  772. self.assertNoOutput(out)
  773. self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True)
  774. def test_custom_command_with_settings(self):
  775. "alternate: manage.py can execute user commands if settings are provided as argument"
  776. args = ['noargs_command', '--settings=alternate_settings']
  777. out, err = self.run_manage(args)
  778. self.assertOutput(
  779. out,
  780. "EXECUTE: noargs_command options=[('force_color', False), "
  781. "('no_color', False), ('pythonpath', None), ('settings', "
  782. "'alternate_settings'), ('traceback', False), ('verbosity', 1)]"
  783. )
  784. self.assertNoOutput(err)
  785. def test_custom_command_with_environment(self):
  786. "alternate: manage.py can execute user commands if settings are provided in environment"
  787. args = ['noargs_command']
  788. out, err = self.run_manage(args, 'alternate_settings')
  789. self.assertOutput(
  790. out,
  791. "EXECUTE: noargs_command options=[('force_color', False), "
  792. "('no_color', False), ('pythonpath', None), ('settings', None), "
  793. "('traceback', False), ('verbosity', 1)]"
  794. )
  795. self.assertNoOutput(err)
  796. def test_custom_command_output_color(self):
  797. "alternate: manage.py output syntax color can be deactivated with the `--no-color` option"
  798. args = ['noargs_command', '--no-color', '--settings=alternate_settings']
  799. out, err = self.run_manage(args)
  800. self.assertOutput(
  801. out,
  802. "EXECUTE: noargs_command options=[('force_color', False), "
  803. "('no_color', True), ('pythonpath', None), ('settings', "
  804. "'alternate_settings'), ('traceback', False), ('verbosity', 1)]"
  805. )
  806. self.assertNoOutput(err)
  807. class ManageMultipleSettings(AdminScriptTestCase):
  808. """A series of tests for manage.py when multiple settings files
  809. (including the default 'settings.py') are available. The default settings
  810. file is insufficient for performing the operations described, so the
  811. alternate settings must be used by the running script.
  812. """
  813. def setUp(self):
  814. super().setUp()
  815. self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes'])
  816. self.write_settings('alternate_settings.py')
  817. def test_builtin_command(self):
  818. "multiple: manage.py builtin commands fail with an error when no settings provided"
  819. args = ['check', 'admin_scripts']
  820. out, err = self.run_manage(args)
  821. self.assertNoOutput(out)
  822. self.assertOutput(err, "No installed app with label 'admin_scripts'.")
  823. def test_builtin_with_settings(self):
  824. "multiple: manage.py builtin commands succeed if settings are provided as argument"
  825. args = ['check', '--settings=alternate_settings', 'admin_scripts']
  826. out, err = self.run_manage(args)
  827. self.assertNoOutput(err)
  828. self.assertOutput(out, SYSTEM_CHECK_MSG)
  829. def test_builtin_with_environment(self):
  830. "multiple: manage.py can execute builtin commands if settings are provided in the environment"
  831. args = ['check', 'admin_scripts']
  832. out, err = self.run_manage(args, 'alternate_settings')
  833. self.assertNoOutput(err)
  834. self.assertOutput(out, SYSTEM_CHECK_MSG)
  835. def test_builtin_with_bad_settings(self):
  836. "multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist"
  837. args = ['check', '--settings=bad_settings', 'admin_scripts']
  838. out, err = self.run_manage(args)
  839. self.assertNoOutput(out)
  840. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  841. def test_builtin_with_bad_environment(self):
  842. "multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist"
  843. args = ['check', 'admin_scripts']
  844. out, err = self.run_manage(args, 'bad_settings')
  845. self.assertNoOutput(out)
  846. self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
  847. def test_custom_command(self):
  848. "multiple: manage.py can't execute user commands using default settings"
  849. args = ['noargs_command']
  850. out, err = self.run_manage(args)
  851. self.assertNoOutput(out)
  852. self.assertOutput(err, "Unknown command: 'noargs_command'")
  853. def test_custom_command_with_settings(self):
  854. "multiple: manage.py can execute user commands if settings are provided as argument"
  855. args = ['noargs_command', '--settings=alternate_settings']
  856. out, err = self.run_manage(args)
  857. self.assertNoOutput(err)
  858. self.assertOutput(out, "EXECUTE: noargs_command")
  859. def test_custom_command_with_environment(self):
  860. "multiple: manage.py can execute user commands if settings are provided in environment"
  861. args = ['noargs_command']
  862. out, err = self.run_manage(args, 'alternate_settings')
  863. self.assertNoOutput(err)
  864. self.assertOutput(out, "EXECUTE: noargs_command")
  865. class ManageSettingsWithSettingsErrors(AdminScriptTestCase):
  866. """
  867. Tests for manage.py when using the default settings.py file containing
  868. runtime errors.
  869. """
  870. def write_settings_with_import_error(self, filename):
  871. settings_file_path = os.path.join(self.test_dir, filename)
  872. with open(settings_file_path, 'w') as settings_file:
  873. settings_file.write('# Settings file automatically generated by admin_scripts test case\n')
  874. settings_file.write('# The next line will cause an import error:\nimport foo42bar\n')
  875. def test_import_error(self):
  876. """
  877. import error: manage.py builtin commands shows useful diagnostic info
  878. when settings with import errors is provided (#14130).
  879. """
  880. self.write_settings_with_import_error('settings.py')
  881. args = ['check', 'admin_scripts']
  882. out, err = self.run_manage(args)
  883. self.assertNoOutput(out)
  884. self.assertOutput(err, "No module named")
  885. self.assertOutput(err, "foo42bar")
  886. def test_attribute_error(self):
  887. """
  888. manage.py builtin commands does not swallow attribute error due to bad
  889. settings (#18845).
  890. """
  891. self.write_settings('settings.py', sdict={'BAD_VAR': 'INSTALLED_APPS.crash'})
  892. args = ['collectstatic', 'admin_scripts']
  893. out, err = self.run_manage(args)
  894. self.assertNoOutput(out)
  895. self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'")
  896. def test_key_error(self):
  897. self.write_settings('settings.py', sdict={'BAD_VAR': 'DATABASES["blah"]'})
  898. args = ['collectstatic', 'admin_scripts']
  899. out, err = self.run_manage(args)
  900. self.assertNoOutput(out)
  901. self.assertOutput(err, "KeyError: 'blah'")
  902. def test_help(self):
  903. """
  904. Test listing available commands output note when only core commands are
  905. available.
  906. """
  907. self.write_settings(
  908. 'settings.py',
  909. extra='from django.core.exceptions import ImproperlyConfigured\n'
  910. 'raise ImproperlyConfigured()',
  911. )
  912. args = ['help']
  913. out, err = self.run_manage(args)
  914. self.assertOutput(out, 'only Django core commands are listed')
  915. self.assertNoOutput(err)
  916. class ManageCheck(AdminScriptTestCase):
  917. def test_nonexistent_app(self):
  918. """check reports an error on a nonexistent app in INSTALLED_APPS."""
  919. self.write_settings(
  920. 'settings.py',
  921. apps=['admin_scriptz.broken_app'],
  922. sdict={'USE_I18N': False},
  923. )
  924. args = ['check']
  925. out, err = self.run_manage(args)
  926. self.assertNoOutput(out)
  927. self.assertOutput(err, 'ModuleNotFoundError')
  928. self.assertOutput(err, 'No module named')
  929. self.assertOutput(err, 'admin_scriptz')
  930. def test_broken_app(self):
  931. """ manage.py check reports an ImportError if an app's models.py
  932. raises one on import """
  933. self.write_settings('settings.py', apps=['admin_scripts.broken_app'])
  934. args = ['check']
  935. out, err = self.run_manage(args)
  936. self.assertNoOutput(out)
  937. self.assertOutput(err, 'ImportError')
  938. def test_complex_app(self):
  939. """ manage.py check does not raise an ImportError validating a
  940. complex app with nested calls to load_app """
  941. self.write_settings(
  942. 'settings.py',
  943. apps=[
  944. 'admin_scripts.complex_app',
  945. 'admin_scripts.simple_app',
  946. 'django.contrib.admin.apps.SimpleAdminConfig',
  947. 'django.contrib.auth',
  948. 'django.contrib.contenttypes',
  949. 'django.contrib.messages',
  950. ],
  951. sdict={
  952. 'DEBUG': True,
  953. 'MIDDLEWARE': [
  954. 'django.contrib.messages.middleware.MessageMiddleware',
  955. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  956. 'django.contrib.sessions.middleware.SessionMiddleware',
  957. ],
  958. 'TEMPLATES': [
  959. {
  960. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  961. 'DIRS': [],
  962. 'APP_DIRS': True,
  963. 'OPTIONS': {
  964. 'context_processors': [
  965. 'django.contrib.auth.context_processors.auth',
  966. 'django.contrib.messages.context_processors.messages',
  967. ],
  968. },
  969. },
  970. ],
  971. }
  972. )
  973. args = ['check']
  974. out, err = self.run_manage(args)
  975. self.assertNoOutput(err)
  976. self.assertEqual(out, 'System check identified no issues (0 silenced).\n')
  977. def test_app_with_import(self):
  978. """ manage.py check does not raise errors when an app imports a base
  979. class that itself has an abstract base. """
  980. self.write_settings(
  981. 'settings.py',
  982. apps=[
  983. 'admin_scripts.app_with_import',
  984. 'django.contrib.auth',
  985. 'django.contrib.contenttypes',
  986. 'django.contrib.sites',
  987. ],
  988. sdict={'DEBUG': True},
  989. )
  990. args = ['check']
  991. out, err = self.run_manage(args)
  992. self.assertNoOutput(err)
  993. self.assertEqual(out, 'System check identified no issues (0 silenced).\n')
  994. def test_output_format(self):
  995. """ All errors/warnings should be sorted by level and by message. """
  996. self.write_settings(
  997. 'settings.py',
  998. apps=[
  999. 'admin_scripts.app_raising_messages',
  1000. 'django.contrib.auth',
  1001. 'django.contrib.contenttypes',
  1002. ],
  1003. sdict={'DEBUG': True},
  1004. )
  1005. args = ['check']
  1006. out, err = self.run_manage(args)
  1007. expected_err = (
  1008. "SystemCheckError: System check identified some issues:\n"
  1009. "\n"
  1010. "ERRORS:\n"
  1011. "?: An error\n"
  1012. "\tHINT: Error hint\n"
  1013. "\n"
  1014. "WARNINGS:\n"
  1015. "a: Second warning\n"
  1016. "obj: First warning\n"
  1017. "\tHINT: Hint\n"
  1018. "\n"
  1019. "System check identified 3 issues (0 silenced).\n"
  1020. )
  1021. self.assertEqual(err, expected_err)
  1022. self.assertNoOutput(out)
  1023. def test_warning_does_not_halt(self):
  1024. """
  1025. When there are only warnings or less serious messages, then Django
  1026. should not prevent user from launching their project, so `check`
  1027. command should not raise `CommandError` exception.
  1028. In this test we also test output format.
  1029. """
  1030. self.write_settings(
  1031. 'settings.py',
  1032. apps=[
  1033. 'admin_scripts.app_raising_warning',
  1034. 'django.contrib.auth',
  1035. 'django.contrib.contenttypes',
  1036. ],
  1037. sdict={'DEBUG': True},
  1038. )
  1039. args = ['check']
  1040. out, err = self.run_manage(args)
  1041. expected_err = (
  1042. "System check identified some issues:\n" # No "CommandError: " part
  1043. "\n"
  1044. "WARNINGS:\n"
  1045. "?: A warning\n"
  1046. "\n"
  1047. "System check identified 1 issue (0 silenced).\n"
  1048. )
  1049. self.assertEqual(err, expected_err)
  1050. self.assertNoOutput(out)
  1051. class ManageRunserver(SimpleTestCase):
  1052. def setUp(self):
  1053. def monkey_run(*args, **options):
  1054. return
  1055. self.output = StringIO()
  1056. self.cmd = RunserverCommand(stdout=self.output)
  1057. self.cmd.run = monkey_run
  1058. def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False):
  1059. self.assertEqual(self.cmd.addr, addr)
  1060. self.assertEqual(self.cmd.port, port)
  1061. self.assertEqual(self.cmd.use_ipv6, ipv6)
  1062. self.assertEqual(self.cmd._raw_ipv6, raw_ipv6)
  1063. def test_runserver_addrport(self):
  1064. call_command(self.cmd)
  1065. self.assertServerSettings('127.0.0.1', '8000')
  1066. call_command(self.cmd, addrport="1.2.3.4:8000")
  1067. self.assertServerSettings('1.2.3.4', '8000')
  1068. call_command(self.cmd, addrport="7000")
  1069. self.assertServerSettings('127.0.0.1', '7000')
  1070. @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
  1071. def test_runner_addrport_ipv6(self):
  1072. call_command(self.cmd, addrport="", use_ipv6=True)
  1073. self.assertServerSettings('::1', '8000', ipv6=True, raw_ipv6=True)
  1074. call_command(self.cmd, addrport="7000", use_ipv6=True)
  1075. self.assertServerSettings('::1', '7000', ipv6=True, raw_ipv6=True)
  1076. call_command(self.cmd, addrport="[2001:0db8:1234:5678::9]:7000")
  1077. self.assertServerSettings('2001:0db8:1234:5678::9', '7000', ipv6=True, raw_ipv6=True)
  1078. def test_runner_hostname(self):
  1079. call_command(self.cmd, addrport="localhost:8000")
  1080. self.assertServerSettings('localhost', '8000')
  1081. call_command(self.cmd, addrport="test.domain.local:7000")
  1082. self.assertServerSettings('test.domain.local', '7000')
  1083. @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
  1084. def test_runner_hostname_ipv6(self):
  1085. call_command(self.cmd, addrport="test.domain.local:7000", use_ipv6=True)
  1086. self.assertServerSettings('test.domain.local', '7000', ipv6=True)
  1087. def test_runner_custom_defaults(self):
  1088. self.cmd.default_addr = '0.0.0.0'
  1089. self.cmd.default_port = '5000'
  1090. call_command(self.cmd)
  1091. self.assertServerSettings('0.0.0.0', '5000')
  1092. @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
  1093. def test_runner_custom_defaults_ipv6(self):
  1094. self.cmd.default_addr_ipv6 = '::'
  1095. call_command(self.cmd, use_ipv6=True)
  1096. self.assertServerSettings('::', '8000', ipv6=True, raw_ipv6=True)
  1097. def test_runner_ambiguous(self):
  1098. # Only 4 characters, all of which could be in an ipv6 address
  1099. call_command(self.cmd, addrport="beef:7654")
  1100. self.assertServerSettings('beef', '7654')
  1101. # Uses only characters that could be in an ipv6 address
  1102. call_command(self.cmd, addrport="deadbeef:7654")
  1103. self.assertServerSettings('deadbeef', '7654')
  1104. def test_no_database(self):
  1105. """
  1106. Ensure runserver.check_migrations doesn't choke on empty DATABASES.
  1107. """
  1108. tested_connections = ConnectionHandler({})
  1109. with mock.patch('django.core.management.base.connections', new=tested_connections):
  1110. self.cmd.check_migrations()
  1111. def test_readonly_database(self):
  1112. """
  1113. runserver.check_migrations() doesn't choke when a database is read-only.
  1114. """
  1115. with mock.patch.object(MigrationRecorder, 'has_table', return_value=False):
  1116. self.cmd.check_migrations()
  1117. # You have # ...
  1118. self.assertIn('unapplied migration(s)', self.output.getvalue())
  1119. class ManageRunserverMigrationWarning(TestCase):
  1120. def setUp(self):
  1121. self.stdout = StringIO()
  1122. self.runserver_command = RunserverCommand(stdout=self.stdout)
  1123. @override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"])
  1124. def test_migration_warning_one_app(self):
  1125. self.runserver_command.check_migrations()
  1126. output = self.stdout.getvalue()
  1127. self.assertIn('You have 1 unapplied migration(s)', output)
  1128. self.assertIn('apply the migrations for app(s): app_waiting_migration.', output)
  1129. @override_settings(
  1130. INSTALLED_APPS=[
  1131. "admin_scripts.app_waiting_migration",
  1132. "admin_scripts.another_app_waiting_migration",
  1133. ],
  1134. )
  1135. def test_migration_warning_multiple_apps(self):
  1136. self.runserver_command.check_migrations()
  1137. output = self.stdout.getvalue()
  1138. self.assertIn('You have 2 unapplied migration(s)', output)
  1139. self.assertIn(
  1140. 'apply the migrations for app(s): another_app_waiting_migration, '
  1141. 'app_waiting_migration.', output
  1142. )
  1143. class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
  1144. def setUp(self):
  1145. super().setUp()
  1146. self.write_settings('settings.py', sdict={
  1147. 'ALLOWED_HOSTS': [],
  1148. 'DEBUG': False,
  1149. })
  1150. def test_empty_allowed_hosts_error(self):
  1151. out, err = self.run_manage(['runserver'])
  1152. self.assertNoOutput(out)
  1153. self.assertOutput(err, 'CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.')
  1154. class ManageTestserver(SimpleTestCase):
  1155. @mock.patch.object(TestserverCommand, 'handle', return_value='')
  1156. def test_testserver_handle_params(self, mock_handle):
  1157. out = StringIO()
  1158. call_command('testserver', 'blah.json', stdout=out)
  1159. mock_handle.assert_called_with(
  1160. 'blah.json',
  1161. stdout=out, settings=None, pythonpath=None, verbosity=1,
  1162. traceback=False, addrport='', no_color=False, use_ipv6=False,
  1163. skip_checks=True, interactive=True, force_color=False,
  1164. )
  1165. @mock.patch('django.db.connection.creation.create_test_db', return_value='test_db')
  1166. @mock.patch.object(LoaddataCommand, 'handle', return_value='')
  1167. @mock.patch.object(RunserverCommand, 'handle', return_value='')
  1168. def test_params_to_runserver(self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db):
  1169. out = StringIO()
  1170. call_command('testserver', 'blah.json', stdout=out)
  1171. mock_runserver_handle.assert_called_with(
  1172. addrport='',
  1173. force_color=False,
  1174. insecure_serving=False,
  1175. no_color=False,
  1176. pythonpath=None,
  1177. settings=None,
  1178. shutdown_message=(
  1179. "\nServer stopped.\nNote that the test database, 'test_db', "
  1180. "has not been deleted. You can explore it on your own."
  1181. ),
  1182. skip_checks=True,
  1183. traceback=False,
  1184. use_ipv6=False,
  1185. use_reloader=False,
  1186. use_static_handler=True,
  1187. use_threading=connection.features.test_db_allows_multiple_connections,
  1188. verbosity=1,
  1189. )
  1190. ##########################################################################
  1191. # COMMAND PROCESSING TESTS
  1192. # user-space commands are correctly handled - in particular, arguments to
  1193. # the commands are correctly parsed and processed.
  1194. ##########################################################################
  1195. class ColorCommand(BaseCommand):
  1196. requires_system_checks = False
  1197. def handle(self, *args, **options):
  1198. self.stdout.write('Hello, world!', self.style.ERROR)
  1199. self.stderr.write('Hello, world!', self.style.ERROR)
  1200. class CommandTypes(AdminScriptTestCase):
  1201. "Tests for the various types of base command types that can be defined."
  1202. def setUp(self):
  1203. super().setUp()
  1204. self.write_settings('settings.py')
  1205. def test_version(self):
  1206. "version is handled as a special case"
  1207. args = ['version']
  1208. out, err = self.run_manage(args)
  1209. self.assertNoOutput(err)
  1210. self.assertOutput(out, get_version())
  1211. def test_version_alternative(self):
  1212. "--version is equivalent to version"
  1213. args1, args2 = ['version'], ['--version']
  1214. # It's possible one outputs on stderr and the other on stdout, hence the set
  1215. self.assertEqual(set(self.run_manage(args1)), set(self.run_manage(args2)))
  1216. def test_help(self):
  1217. "help is handled as a special case"
  1218. args = ['help']
  1219. out, err = self.run_manage(args)
  1220. self.assertOutput(out, "Type 'manage.py help <subcommand>' for help on a specific subcommand.")
  1221. self.assertOutput(out, '[django]')
  1222. self.assertOutput(out, 'startapp')
  1223. self.assertOutput(out, 'startproject')
  1224. def test_help_commands(self):
  1225. "help --commands shows the list of all available commands"
  1226. args = ['help', '--commands']
  1227. out, err = self.run_manage(args)
  1228. self.assertNotInOutput(out, 'usage:')
  1229. self.assertNotInOutput(out, 'Options:')
  1230. self.assertNotInOutput(out, '[django]')
  1231. self.assertOutput(out, 'startapp')
  1232. self.assertOutput(out, 'startproject')
  1233. self.assertNotInOutput(out, '\n\n')
  1234. def test_help_alternative(self):
  1235. "--help is equivalent to help"
  1236. args1, args2 = ['help'], ['--help']
  1237. self.assertEqual(self.run_manage(args1), self.run_manage(args2))
  1238. def test_help_short_altert(self):
  1239. "-h is handled as a short form of --help"
  1240. args1, args2 = ['--help'], ['-h']
  1241. self.assertEqual(self.run_manage(args1), self.run_manage(args2))
  1242. def test_specific_help(self):
  1243. "--help can be used on a specific command"
  1244. args = ['check', '--help']
  1245. out, err = self.run_manage(args)
  1246. self.assertNoOutput(err)
  1247. # Command-specific options like --tag appear before options common to
  1248. # all commands like --version.
  1249. tag_location = out.find('--tag')
  1250. version_location = out.find('--version')
  1251. self.assertNotEqual(tag_location, -1)
  1252. self.assertNotEqual(version_location, -1)
  1253. self.assertLess(tag_location, version_location)
  1254. self.assertOutput(out, "Checks the entire Django project for potential problems.")
  1255. def test_color_style(self):
  1256. style = color.no_style()
  1257. self.assertEqual(style.ERROR('Hello, world!'), 'Hello, world!')
  1258. style = color.make_style('nocolor')
  1259. self.assertEqual(style.ERROR('Hello, world!'), 'Hello, world!')
  1260. style = color.make_style('dark')
  1261. self.assertIn('Hello, world!', style.ERROR('Hello, world!'))
  1262. self.assertNotEqual(style.ERROR('Hello, world!'), 'Hello, world!')
  1263. # Default palette has color.
  1264. style = color.make_style('')
  1265. self.assertIn('Hello, world!', style.ERROR('Hello, world!'))
  1266. self.assertNotEqual(style.ERROR('Hello, world!'), 'Hello, world!')
  1267. def test_command_color(self):
  1268. out = StringIO()
  1269. err = StringIO()
  1270. command = ColorCommand(stdout=out, stderr=err)
  1271. call_command(command)
  1272. if color.supports_color():
  1273. self.assertIn('Hello, world!\n', out.getvalue())
  1274. self.assertIn('Hello, world!\n', err.getvalue())
  1275. self.assertNotEqual(out.getvalue(), 'Hello, world!\n')
  1276. self.assertNotEqual(err.getvalue(), 'Hello, world!\n')
  1277. else:
  1278. self.assertEqual(out.getvalue(), 'Hello, world!\n')
  1279. self.assertEqual(err.getvalue(), 'Hello, world!\n')
  1280. def test_command_no_color(self):
  1281. "--no-color prevent colorization of the output"
  1282. out = StringIO()
  1283. err = StringIO()
  1284. command = ColorCommand(stdout=out, stderr=err, no_color=True)
  1285. call_command(command)
  1286. self.assertEqual(out.getvalue(), 'Hello, world!\n')
  1287. self.assertEqual(err.getvalue(), 'Hello, world!\n')
  1288. out = StringIO()
  1289. err = StringIO()
  1290. command = ColorCommand(stdout=out, stderr=err)
  1291. call_command(command, no_color=True)
  1292. self.assertEqual(out.getvalue(), 'Hello, world!\n')
  1293. self.assertEqual(err.getvalue(), 'Hello, world!\n')
  1294. def test_force_color_execute(self):
  1295. out = StringIO()
  1296. err = StringIO()
  1297. with mock.patch.object(sys.stdout, 'isatty', lambda: False):
  1298. command = ColorCommand(stdout=out, stderr=err)
  1299. call_command(command, force_color=True)
  1300. self.assertEqual(out.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m')
  1301. self.assertEqual(err.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m')
  1302. def test_force_color_command_init(self):
  1303. out = StringIO()
  1304. err = StringIO()
  1305. with mock.patch.object(sys.stdout, 'isatty', lambda: False):
  1306. command = ColorCommand(stdout=out, stderr=err, force_color=True)
  1307. call_command(command)
  1308. self.assertEqual(out.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m')
  1309. self.assertEqual(err.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m')
  1310. def test_no_color_force_color_mutually_exclusive_execute(self):
  1311. msg = "The --no-color and --force-color options can't be used together."
  1312. with self.assertRaisesMessage(CommandError, msg):
  1313. call_command(BaseCommand(), no_color=True, force_color=True)
  1314. def test_no_color_force_color_mutually_exclusive_command_init(self):
  1315. msg = "'no_color' and 'force_color' can't be used together."
  1316. with self.assertRaisesMessage(CommandError, msg):
  1317. call_command(BaseCommand(no_color=True, force_color=True))
  1318. def test_custom_stdout(self):
  1319. class Command(BaseCommand):
  1320. requires_system_checks = False
  1321. def handle(self, *args, **options):
  1322. self.stdout.write("Hello, World!")
  1323. out = StringIO()
  1324. command = Command(stdout=out)
  1325. call_command(command)
  1326. self.assertEqual(out.getvalue(), "Hello, World!\n")
  1327. out.truncate(0)
  1328. new_out = StringIO()
  1329. call_command(command, stdout=new_out)
  1330. self.assertEqual(out.getvalue(), "")
  1331. self.assertEqual(new_out.getvalue(), "Hello, World!\n")
  1332. def test_custom_stderr(self):
  1333. class Command(BaseCommand):
  1334. requires_system_checks = False
  1335. def handle(self, *args, **options):
  1336. self.stderr.write("Hello, World!")
  1337. err = StringIO()
  1338. command = Command(stderr=err)
  1339. call_command(command)
  1340. self.assertEqual(err.getvalue(), "Hello, World!\n")
  1341. err.truncate(0)
  1342. new_err = StringIO()
  1343. call_command(command, stderr=new_err)
  1344. self.assertEqual(err.getvalue(), "")
  1345. self.assertEqual(new_err.getvalue(), "Hello, World!\n")
  1346. def test_base_command(self):
  1347. "User BaseCommands can execute when a label is provided"
  1348. args = ['base_command', 'testlabel']
  1349. expected_labels = "('testlabel',)"
  1350. self._test_base_command(args, expected_labels)
  1351. def test_base_command_no_label(self):
  1352. "User BaseCommands can execute when no labels are provided"
  1353. args = ['base_command']
  1354. expected_labels = "()"
  1355. self._test_base_command(args, expected_labels)
  1356. def test_base_command_multiple_label(self):
  1357. "User BaseCommands can execute when no labels are provided"
  1358. args = ['base_command', 'testlabel', 'anotherlabel']
  1359. expected_labels = "('testlabel', 'anotherlabel')"
  1360. self._test_base_command(args, expected_labels)
  1361. def test_base_command_with_option(self):
  1362. "User BaseCommands can execute with options when a label is provided"
  1363. args = ['base_command', 'testlabel', '--option_a=x']
  1364. expected_labels = "('testlabel',)"
  1365. self._test_base_command(args, expected_labels, option_a="'x'")
  1366. def test_base_command_with_options(self):
  1367. "User BaseCommands can execute with multiple options when a label is provided"
  1368. args = ['base_command', 'testlabel', '-a', 'x', '--option_b=y']
  1369. expected_labels = "('testlabel',)"
  1370. self._test_base_command(args, expected_labels, option_a="'x'", option_b="'y'")
  1371. def test_base_command_with_wrong_option(self):
  1372. "User BaseCommands outputs command usage when wrong option is specified"
  1373. args = ['base_command', '--invalid']
  1374. out, err = self.run_manage(args)
  1375. self.assertNoOutput(out)
  1376. self.assertOutput(err, "usage: manage.py base_command")
  1377. self.assertOutput(err, "error: unrecognized arguments: --invalid")
  1378. def _test_base_command(self, args, labels, option_a="'1'", option_b="'2'"):
  1379. out, err = self.run_manage(args)
  1380. expected_out = (
  1381. "EXECUTE:BaseCommand labels=%s, "
  1382. "options=[('force_color', False), ('no_color', False), "
  1383. "('option_a', %s), ('option_b', %s), ('option_c', '3'), "
  1384. "('pythonpath', None), ('settings', None), ('traceback', False), "
  1385. "('verbosity', 1)]") % (labels, option_a, option_b)
  1386. self.assertNoOutput(err)
  1387. self.assertOutput(out, expected_out)
  1388. def test_base_run_from_argv(self):
  1389. """
  1390. Test run_from_argv properly terminates even with custom execute() (#19665)
  1391. Also test proper traceback display.
  1392. """
  1393. err = StringIO()
  1394. command = BaseCommand(stderr=err)
  1395. def raise_command_error(*args, **kwargs):
  1396. raise CommandError("Custom error")
  1397. command.execute = lambda args: args # This will trigger TypeError
  1398. # If the Exception is not CommandError it should always
  1399. # raise the original exception.
  1400. with self.assertRaises(TypeError):
  1401. command.run_from_argv(['', ''])
  1402. # If the Exception is CommandError and --traceback is not present
  1403. # this command should raise a SystemExit and don't print any
  1404. # traceback to the stderr.
  1405. command.execute = raise_command_error
  1406. err.truncate(0)
  1407. with self.assertRaises(SystemExit):
  1408. command.run_from_argv(['', ''])
  1409. err_message = err.getvalue()
  1410. self.assertNotIn("Traceback", err_message)
  1411. self.assertIn("CommandError", err_message)
  1412. # If the Exception is CommandError and --traceback is present
  1413. # this command should raise the original CommandError as if it
  1414. # were not a CommandError.
  1415. err.truncate(0)
  1416. with self.assertRaises(CommandError):
  1417. command.run_from_argv(['', '', '--traceback'])
  1418. def test_run_from_argv_non_ascii_error(self):
  1419. """
  1420. Non-ASCII message of CommandError does not raise any
  1421. UnicodeDecodeError in run_from_argv.
  1422. """
  1423. def raise_command_error(*args, **kwargs):
  1424. raise CommandError("Erreur personnalisée")
  1425. command = BaseCommand(stderr=StringIO())
  1426. command.execute = raise_command_error
  1427. with self.assertRaises(SystemExit):
  1428. command.run_from_argv(['', ''])
  1429. def test_run_from_argv_closes_connections(self):
  1430. """
  1431. A command called from the command line should close connections after
  1432. being executed (#21255).
  1433. """
  1434. command = BaseCommand(stderr=StringIO())
  1435. command.check = lambda: []
  1436. command.handle = lambda *args, **kwargs: args
  1437. with mock.patch('django.core.management.base.connections') as mock_connections:
  1438. command.run_from_argv(['', ''])
  1439. # Test connections have been closed
  1440. self.assertTrue(mock_connections.close_all.called)
  1441. def test_noargs(self):
  1442. "NoArg Commands can be executed"
  1443. args = ['noargs_command']
  1444. out, err = self.run_manage(args)
  1445. self.assertNoOutput(err)
  1446. self.assertOutput(
  1447. out,
  1448. "EXECUTE: noargs_command options=[('force_color', False), "
  1449. "('no_color', False), ('pythonpath', None), ('settings', None), "
  1450. "('traceback', False), ('verbosity', 1)]"
  1451. )
  1452. def test_noargs_with_args(self):
  1453. "NoArg Commands raise an error if an argument is provided"
  1454. args = ['noargs_command', 'argument']
  1455. out, err = self.run_manage(args)
  1456. self.assertOutput(err, "error: unrecognized arguments: argument")
  1457. def test_app_command(self):
  1458. "User AppCommands can execute when a single app name is provided"
  1459. args = ['app_command', 'auth']
  1460. out, err = self.run_manage(args)
  1461. self.assertNoOutput(err)
  1462. self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=")
  1463. self.assertOutput(
  1464. out,
  1465. ", options=[('force_color', False), ('no_color', False), "
  1466. "('pythonpath', None), ('settings', None), ('traceback', False), "
  1467. "('verbosity', 1)]"
  1468. )
  1469. def test_app_command_no_apps(self):
  1470. "User AppCommands raise an error when no app name is provided"
  1471. args = ['app_command']
  1472. out, err = self.run_manage(args)
  1473. self.assertOutput(err, 'error: Enter at least one application label.')
  1474. def test_app_command_multiple_apps(self):
  1475. "User AppCommands raise an error when multiple app names are provided"
  1476. args = ['app_command', 'auth', 'contenttypes']
  1477. out, err = self.run_manage(args)
  1478. self.assertNoOutput(err)
  1479. self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=")
  1480. self.assertOutput(
  1481. out,
  1482. ", options=[('force_color', False), ('no_color', False), "
  1483. "('pythonpath', None), ('settings', None), ('traceback', False), "
  1484. "('verbosity', 1)]"
  1485. )
  1486. self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options=")
  1487. self.assertOutput(
  1488. out,
  1489. ", options=[('force_color', False), ('no_color', False), "
  1490. "('pythonpath', None), ('settings', None), ('traceback', False), "
  1491. "('verbosity', 1)]"
  1492. )
  1493. def test_app_command_invalid_app_label(self):
  1494. "User AppCommands can execute when a single app name is provided"
  1495. args = ['app_command', 'NOT_AN_APP']
  1496. out, err = self.run_manage(args)
  1497. self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.")
  1498. def test_app_command_some_invalid_app_labels(self):
  1499. "User AppCommands can execute when some of the provided app names are invalid"
  1500. args = ['app_command', 'auth', 'NOT_AN_APP']
  1501. out, err = self.run_manage(args)
  1502. self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.")
  1503. def test_label_command(self):
  1504. "User LabelCommands can execute when a label is provided"
  1505. args = ['label_command', 'testlabel']
  1506. out, err = self.run_manage(args)
  1507. self.assertNoOutput(err)
  1508. self.assertOutput(
  1509. out,
  1510. "EXECUTE:LabelCommand label=testlabel, options=[('force_color', "
  1511. "False), ('no_color', False), ('pythonpath', None), ('settings', "
  1512. "None), ('traceback', False), ('verbosity', 1)]"
  1513. )
  1514. def test_label_command_no_label(self):
  1515. "User LabelCommands raise an error if no label is provided"
  1516. args = ['label_command']
  1517. out, err = self.run_manage(args)
  1518. self.assertOutput(err, 'Enter at least one label')
  1519. def test_label_command_multiple_label(self):
  1520. "User LabelCommands are executed multiple times if multiple labels are provided"
  1521. args = ['label_command', 'testlabel', 'anotherlabel']
  1522. out, err = self.run_manage(args)
  1523. self.assertNoOutput(err)
  1524. self.assertOutput(
  1525. out,
  1526. "EXECUTE:LabelCommand label=testlabel, options=[('force_color', "
  1527. "False), ('no_color', False), ('pythonpath', None), "
  1528. "('settings', None), ('traceback', False), ('verbosity', 1)]"
  1529. )
  1530. self.assertOutput(
  1531. out,
  1532. "EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', "
  1533. "False), ('no_color', False), ('pythonpath', None), "
  1534. "('settings', None), ('traceback', False), ('verbosity', 1)]"
  1535. )
  1536. class Discovery(SimpleTestCase):
  1537. def test_precedence(self):
  1538. """
  1539. Apps listed first in INSTALLED_APPS have precedence.
  1540. """
  1541. with self.settings(INSTALLED_APPS=['admin_scripts.complex_app',
  1542. 'admin_scripts.simple_app',
  1543. 'django.contrib.auth',
  1544. 'django.contrib.contenttypes']):
  1545. out = StringIO()
  1546. call_command('duplicate', stdout=out)
  1547. self.assertEqual(out.getvalue().strip(), 'complex_app')
  1548. with self.settings(INSTALLED_APPS=['admin_scripts.simple_app',
  1549. 'admin_scripts.complex_app',
  1550. 'django.contrib.auth',
  1551. 'django.contrib.contenttypes']):
  1552. out = StringIO()
  1553. call_command('duplicate', stdout=out)
  1554. self.assertEqual(out.getvalue().strip(), 'simple_app')
  1555. class ArgumentOrder(AdminScriptTestCase):
  1556. """Tests for 2-stage argument parsing scheme.
  1557. django-admin command arguments are parsed in 2 parts; the core arguments
  1558. (--settings, --traceback and --pythonpath) are parsed using a basic parser,
  1559. ignoring any unknown options. Then the full settings are
  1560. passed to the command parser, which extracts commands of interest to the
  1561. individual command.
  1562. """
  1563. def setUp(self):
  1564. super().setUp()
  1565. self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes'])
  1566. self.write_settings('alternate_settings.py')
  1567. def test_setting_then_option(self):
  1568. """ Options passed after settings are correctly handled. """
  1569. args = ['base_command', 'testlabel', '--settings=alternate_settings', '--option_a=x']
  1570. self._test(args)
  1571. def test_setting_then_short_option(self):
  1572. """ Short options passed after settings are correctly handled. """
  1573. args = ['base_command', 'testlabel', '--settings=alternate_settings', '-a', 'x']
  1574. self._test(args)
  1575. def test_option_then_setting(self):
  1576. """ Options passed before settings are correctly handled. """
  1577. args = ['base_command', 'testlabel', '--option_a=x', '--settings=alternate_settings']
  1578. self._test(args)
  1579. def test_short_option_then_setting(self):
  1580. """ Short options passed before settings are correctly handled. """
  1581. args = ['base_command', 'testlabel', '-a', 'x', '--settings=alternate_settings']
  1582. self._test(args)
  1583. def test_option_then_setting_then_option(self):
  1584. """ Options are correctly handled when they are passed before and after
  1585. a setting. """
  1586. args = ['base_command', 'testlabel', '--option_a=x', '--settings=alternate_settings', '--option_b=y']
  1587. self._test(args, option_b="'y'")
  1588. def _test(self, args, option_b="'2'"):
  1589. out, err = self.run_manage(args)
  1590. self.assertNoOutput(err)
  1591. self.assertOutput(
  1592. out,
  1593. "EXECUTE:BaseCommand labels=('testlabel',), options=["
  1594. "('force_color', False), ('no_color', False), ('option_a', 'x'), "
  1595. "('option_b', %s), ('option_c', '3'), ('pythonpath', None), "
  1596. "('settings', 'alternate_settings'), ('traceback', False), "
  1597. "('verbosity', 1)]" % option_b
  1598. )
  1599. @override_settings(ROOT_URLCONF='admin_scripts.urls')
  1600. class StartProject(LiveServerTestCase, AdminScriptTestCase):
  1601. available_apps = [
  1602. 'admin_scripts',
  1603. 'django.contrib.auth',
  1604. 'django.contrib.contenttypes',
  1605. 'django.contrib.sessions',
  1606. ]
  1607. def test_wrong_args(self):
  1608. "Make sure passing the wrong kinds of arguments outputs an error and prints usage"
  1609. out, err = self.run_django_admin(['startproject'])
  1610. self.assertNoOutput(out)
  1611. self.assertOutput(err, "usage:")
  1612. self.assertOutput(err, "You must provide a project name.")
  1613. def test_simple_project(self):
  1614. "Make sure the startproject management command creates a project"
  1615. args = ['startproject', 'testproject']
  1616. testproject_dir = os.path.join(self.test_dir, 'testproject')
  1617. out, err = self.run_django_admin(args)
  1618. self.assertNoOutput(err)
  1619. self.assertTrue(os.path.isdir(testproject_dir))
  1620. # running again..
  1621. out, err = self.run_django_admin(args)
  1622. self.assertNoOutput(out)
  1623. self.assertOutput(
  1624. err,
  1625. "CommandError: 'testproject' conflicts with the name of an "
  1626. "existing Python module and cannot be used as a project name. "
  1627. "Please try another name.",
  1628. )
  1629. def test_invalid_project_name(self):
  1630. "Make sure the startproject management command validates a project name"
  1631. for bad_name in ('7testproject', '../testproject'):
  1632. with self.subTest(project_name=bad_name):
  1633. args = ['startproject', bad_name]
  1634. testproject_dir = os.path.join(self.test_dir, bad_name)
  1635. out, err = self.run_django_admin(args)
  1636. self.assertOutput(
  1637. err,
  1638. "Error: '%s' is not a valid project name. Please make "
  1639. "sure the name is a valid identifier." % bad_name
  1640. )
  1641. self.assertFalse(os.path.exists(testproject_dir))
  1642. def test_importable_project_name(self):
  1643. """
  1644. startproject validates that project name doesn't clash with existing
  1645. Python modules.
  1646. """
  1647. bad_name = 'os'
  1648. args = ['startproject', bad_name]
  1649. testproject_dir = os.path.join(self.test_dir, bad_name)
  1650. out, err = self.run_django_admin(args)
  1651. self.assertOutput(
  1652. err,
  1653. "CommandError: 'os' conflicts with the name of an existing "
  1654. "Python module and cannot be used as a project name. Please try "
  1655. "another name."
  1656. )
  1657. self.assertFalse(os.path.exists(testproject_dir))
  1658. def test_simple_project_different_directory(self):
  1659. "Make sure the startproject management command creates a project in a specific directory"
  1660. args = ['startproject', 'testproject', 'othertestproject']
  1661. testproject_dir = os.path.join(self.test_dir, 'othertestproject')
  1662. os.mkdir(testproject_dir)
  1663. out, err = self.run_django_admin(args)
  1664. self.assertNoOutput(err)
  1665. self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'manage.py')))
  1666. # running again..
  1667. out, err = self.run_django_admin(args)
  1668. self.assertNoOutput(out)
  1669. self.assertOutput(
  1670. err,
  1671. "already exists. Overlaying a project into an existing directory "
  1672. "won't replace conflicting files."
  1673. )
  1674. def test_custom_project_template(self):
  1675. "Make sure the startproject management command is able to use a different project template"
  1676. template_path = os.path.join(custom_templates_dir, 'project_template')
  1677. args = ['startproject', '--template', template_path, 'customtestproject']
  1678. testproject_dir = os.path.join(self.test_dir, 'customtestproject')
  1679. out, err = self.run_django_admin(args)
  1680. self.assertNoOutput(err)
  1681. self.assertTrue(os.path.isdir(testproject_dir))
  1682. self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir')))
  1683. def test_template_dir_with_trailing_slash(self):
  1684. "Ticket 17475: Template dir passed has a trailing path separator"
  1685. template_path = os.path.join(custom_templates_dir, 'project_template' + os.sep)
  1686. args = ['startproject', '--template', template_path, 'customtestproject']
  1687. testproject_dir = os.path.join(self.test_dir, 'customtestproject')
  1688. out, err = self.run_django_admin(args)
  1689. self.assertNoOutput(err)
  1690. self.assertTrue(os.path.isdir(testproject_dir))
  1691. self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir')))
  1692. def test_custom_project_template_from_tarball_by_path(self):
  1693. "Make sure the startproject management command is able to use a different project template from a tarball"
  1694. template_path = os.path.join(custom_templates_dir, 'project_template.tgz')
  1695. args = ['startproject', '--template', template_path, 'tarballtestproject']
  1696. testproject_dir = os.path.join(self.test_dir, 'tarballtestproject')
  1697. out, err = self.run_django_admin(args)
  1698. self.assertNoOutput(err)
  1699. self.assertTrue(os.path.isdir(testproject_dir))
  1700. self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py')))
  1701. def test_custom_project_template_from_tarball_to_alternative_location(self):
  1702. "Startproject can use a project template from a tarball and create it in a specified location"
  1703. template_path = os.path.join(custom_templates_dir, 'project_template.tgz')
  1704. args = ['startproject', '--template', template_path, 'tarballtestproject', 'altlocation']
  1705. testproject_dir = os.path.join(self.test_dir, 'altlocation')
  1706. os.mkdir(testproject_dir)
  1707. out, err = self.run_django_admin(args)
  1708. self.assertNoOutput(err)
  1709. self.assertTrue(os.path.isdir(testproject_dir))
  1710. self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py')))
  1711. def test_custom_project_template_from_tarball_by_url(self):
  1712. """
  1713. The startproject management command is able to use a different project
  1714. template from a tarball via a URL.
  1715. """
  1716. template_url = '%s/custom_templates/project_template.tgz' % self.live_server_url
  1717. args = ['startproject', '--template', template_url, 'urltestproject']
  1718. testproject_dir = os.path.join(self.test_dir, 'urltestproject')
  1719. out, err = self.run_django_admin(args)
  1720. self.assertNoOutput(err)
  1721. self.assertTrue(os.path.isdir(testproject_dir))
  1722. self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py')))
  1723. def test_project_template_tarball_url(self):
  1724. "Startproject management command handles project template tar/zip balls from non-canonical urls"
  1725. template_url = '%s/custom_templates/project_template.tgz/' % self.live_server_url
  1726. args = ['startproject', '--template', template_url, 'urltestproject']
  1727. testproject_dir = os.path.join(self.test_dir, 'urltestproject')
  1728. out, err = self.run_django_admin(args)
  1729. self.assertNoOutput(err)
  1730. self.assertTrue(os.path.isdir(testproject_dir))
  1731. self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py')))
  1732. def test_file_without_extension(self):
  1733. "Make sure the startproject management command is able to render custom files"
  1734. template_path = os.path.join(custom_templates_dir, 'project_template')
  1735. args = ['startproject', '--template', template_path, 'customtestproject', '-e', 'txt', '-n', 'Procfile']
  1736. testproject_dir = os.path.join(self.test_dir, 'customtestproject')
  1737. out, err = self.run_django_admin(args)
  1738. self.assertNoOutput(err)
  1739. self.assertTrue(os.path.isdir(testproject_dir))
  1740. self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir')))
  1741. base_path = os.path.join(testproject_dir, 'additional_dir')
  1742. for f in ('Procfile', 'additional_file.py', 'requirements.txt'):
  1743. self.assertTrue(os.path.exists(os.path.join(base_path, f)))
  1744. with open(os.path.join(base_path, f)) as fh:
  1745. self.assertEqual(fh.read().strip(), '# some file for customtestproject test project')
  1746. def test_custom_project_template_context_variables(self):
  1747. "Make sure template context variables are rendered with proper values"
  1748. template_path = os.path.join(custom_templates_dir, 'project_template')
  1749. args = ['startproject', '--template', template_path, 'another_project', 'project_dir']
  1750. testproject_dir = os.path.join(self.test_dir, 'project_dir')
  1751. os.mkdir(testproject_dir)
  1752. out, err = self.run_django_admin(args)
  1753. self.assertNoOutput(err)
  1754. test_manage_py = os.path.join(testproject_dir, 'manage.py')
  1755. with open(test_manage_py) as fp:
  1756. content = fp.read()
  1757. self.assertIn("project_name = 'another_project'", content)
  1758. self.assertIn("project_directory = '%s'" % testproject_dir, content)
  1759. def test_no_escaping_of_project_variables(self):
  1760. "Make sure template context variables are not html escaped"
  1761. # We're using a custom command so we need the alternate settings
  1762. self.write_settings('alternate_settings.py')
  1763. template_path = os.path.join(custom_templates_dir, 'project_template')
  1764. args = [
  1765. 'custom_startproject', '--template', template_path,
  1766. 'another_project', 'project_dir', '--extra', '<&>',
  1767. '--settings=alternate_settings',
  1768. ]
  1769. testproject_dir = os.path.join(self.test_dir, 'project_dir')
  1770. os.mkdir(testproject_dir)
  1771. out, err = self.run_manage(args)
  1772. self.assertNoOutput(err)
  1773. test_manage_py = os.path.join(testproject_dir, 'additional_dir', 'extra.py')
  1774. with open(test_manage_py) as fp:
  1775. content = fp.read()
  1776. self.assertIn("<&>", content)
  1777. def test_custom_project_destination_missing(self):
  1778. """
  1779. Make sure an exception is raised when the provided
  1780. destination directory doesn't exist
  1781. """
  1782. template_path = os.path.join(custom_templates_dir, 'project_template')
  1783. args = ['startproject', '--template', template_path, 'yet_another_project', 'project_dir2']
  1784. testproject_dir = os.path.join(self.test_dir, 'project_dir2')
  1785. out, err = self.run_django_admin(args)
  1786. self.assertNoOutput(out)
  1787. self.assertOutput(err, "Destination directory '%s' does not exist, please create it first." % testproject_dir)
  1788. self.assertFalse(os.path.exists(testproject_dir))
  1789. def test_custom_project_template_with_non_ascii_templates(self):
  1790. """
  1791. The startproject management command is able to render templates with
  1792. non-ASCII content.
  1793. """
  1794. template_path = os.path.join(custom_templates_dir, 'project_template')
  1795. args = ['startproject', '--template', template_path, '--extension=txt', 'customtestproject']
  1796. testproject_dir = os.path.join(self.test_dir, 'customtestproject')
  1797. out, err = self.run_django_admin(args)
  1798. self.assertNoOutput(err)
  1799. self.assertTrue(os.path.isdir(testproject_dir))
  1800. path = os.path.join(testproject_dir, 'ticket-18091-non-ascii-template.txt')
  1801. with open(path, encoding='utf-8') as f:
  1802. self.assertEqual(f.read().splitlines(False), [
  1803. 'Some non-ASCII text for testing ticket #18091:',
  1804. 'üäö €'])
  1805. class StartApp(AdminScriptTestCase):
  1806. def test_invalid_name(self):
  1807. """startapp validates that app name is a valid Python identifier."""
  1808. for bad_name in ('7testproject', '../testproject'):
  1809. with self.subTest(app_name=bad_name):
  1810. args = ['startapp', bad_name]
  1811. testproject_dir = os.path.join(self.test_dir, bad_name)
  1812. out, err = self.run_django_admin(args)
  1813. self.assertOutput(
  1814. err,
  1815. "CommandError: '{}' is not a valid app name. Please make "
  1816. "sure the name is a valid identifier.".format(bad_name)
  1817. )
  1818. self.assertFalse(os.path.exists(testproject_dir))
  1819. def test_importable_name(self):
  1820. """
  1821. startapp validates that app name doesn't clash with existing Python
  1822. modules.
  1823. """
  1824. bad_name = 'os'
  1825. args = ['startapp', bad_name]
  1826. testproject_dir = os.path.join(self.test_dir, bad_name)
  1827. out, err = self.run_django_admin(args)
  1828. self.assertOutput(
  1829. err,
  1830. "CommandError: 'os' conflicts with the name of an existing "
  1831. "Python module and cannot be used as an app name. Please try "
  1832. "another name."
  1833. )
  1834. self.assertFalse(os.path.exists(testproject_dir))
  1835. def test_invalid_target_name(self):
  1836. for bad_target in ('invalid.dir_name', '7invalid_dir_name', '.invalid_dir_name'):
  1837. with self.subTest(bad_target):
  1838. _, err = self.run_django_admin(['startapp', 'app', bad_target])
  1839. self.assertOutput(
  1840. err,
  1841. "CommandError: '%s' is not a valid app directory. Please "
  1842. "make sure the directory is a valid identifier." % bad_target
  1843. )
  1844. def test_importable_target_name(self):
  1845. _, err = self.run_django_admin(['startapp', 'app', 'os'])
  1846. self.assertOutput(
  1847. err,
  1848. "CommandError: 'os' conflicts with the name of an existing Python "
  1849. "module and cannot be used as an app directory. Please try "
  1850. "another directory."
  1851. )
  1852. def test_overlaying_app(self):
  1853. # Use a subdirectory so it is outside the PYTHONPATH.
  1854. os.makedirs(os.path.join(self.test_dir, 'apps/app1'))
  1855. self.run_django_admin(['startapp', 'app1', 'apps/app1'])
  1856. out, err = self.run_django_admin(['startapp', 'app2', 'apps/app1'])
  1857. self.assertOutput(
  1858. err,
  1859. "already exists. Overlaying an app into an existing directory "
  1860. "won't replace conflicting files."
  1861. )
  1862. class DiffSettings(AdminScriptTestCase):
  1863. """Tests for diffsettings management command."""
  1864. def test_basic(self):
  1865. """Runs without error and emits settings diff."""
  1866. self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'})
  1867. args = ['diffsettings', '--settings=settings_to_diff']
  1868. out, err = self.run_manage(args)
  1869. self.assertNoOutput(err)
  1870. self.assertOutput(out, "FOO = 'bar' ###")
  1871. # Attributes from django.conf.Settings don't appear.
  1872. self.assertNotInOutput(out, 'is_overridden = ')
  1873. def test_settings_configured(self):
  1874. out, err = self.run_manage(['diffsettings'], manage_py='configured_settings_manage.py')
  1875. self.assertNoOutput(err)
  1876. self.assertOutput(out, 'CUSTOM = 1 ###\nDEBUG = True')
  1877. # Attributes from django.conf.UserSettingsHolder don't appear.
  1878. self.assertNotInOutput(out, 'default_settings = ')
  1879. def test_dynamic_settings_configured(self):
  1880. # Custom default settings appear.
  1881. out, err = self.run_manage(['diffsettings'], manage_py='configured_dynamic_settings_manage.py')
  1882. self.assertNoOutput(err)
  1883. self.assertOutput(out, "FOO = 'bar' ###")
  1884. def test_all(self):
  1885. """The all option also shows settings with the default value."""
  1886. self.write_settings('settings_to_diff.py', sdict={'STATIC_URL': 'None'})
  1887. args = ['diffsettings', '--settings=settings_to_diff', '--all']
  1888. out, err = self.run_manage(args)
  1889. self.assertNoOutput(err)
  1890. self.assertOutput(out, "### STATIC_URL = None")
  1891. def test_custom_default(self):
  1892. """
  1893. The --default option specifies an alternate settings module for
  1894. comparison.
  1895. """
  1896. self.write_settings('settings_default.py', sdict={'FOO': '"foo"', 'BAR': '"bar1"'})
  1897. self.write_settings('settings_to_diff.py', sdict={'FOO': '"foo"', 'BAR': '"bar2"'})
  1898. out, err = self.run_manage(['diffsettings', '--settings=settings_to_diff', '--default=settings_default'])
  1899. self.assertNoOutput(err)
  1900. self.assertNotInOutput(out, "FOO")
  1901. self.assertOutput(out, "BAR = 'bar2'")
  1902. def test_unified(self):
  1903. """--output=unified emits settings diff in unified mode."""
  1904. self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'})
  1905. args = ['diffsettings', '--settings=settings_to_diff', '--output=unified']
  1906. out, err = self.run_manage(args)
  1907. self.assertNoOutput(err)
  1908. self.assertOutput(out, "+ FOO = 'bar'")
  1909. self.assertOutput(out, "- SECRET_KEY = ''")
  1910. self.assertOutput(out, "+ SECRET_KEY = 'django_tests_secret_key'")
  1911. self.assertNotInOutput(out, " APPEND_SLASH = True")
  1912. def test_unified_all(self):
  1913. """
  1914. --output=unified --all emits settings diff in unified mode and includes
  1915. settings with the default value.
  1916. """
  1917. self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'})
  1918. args = ['diffsettings', '--settings=settings_to_diff', '--output=unified', '--all']
  1919. out, err = self.run_manage(args)
  1920. self.assertNoOutput(err)
  1921. self.assertOutput(out, " APPEND_SLASH = True")
  1922. self.assertOutput(out, "+ FOO = 'bar'")
  1923. self.assertOutput(out, "- SECRET_KEY = ''")
  1924. class Dumpdata(AdminScriptTestCase):
  1925. """Tests for dumpdata management command."""
  1926. def setUp(self):
  1927. super().setUp()
  1928. self.write_settings('settings.py')
  1929. def test_pks_parsing(self):
  1930. """Regression for #20509
  1931. Test would raise an exception rather than printing an error message.
  1932. """
  1933. args = ['dumpdata', '--pks=1']
  1934. out, err = self.run_manage(args)
  1935. self.assertOutput(err, "You can only use --pks option with one model")
  1936. self.assertNoOutput(out)
  1937. class MainModule(AdminScriptTestCase):
  1938. """python -m django works like django-admin."""
  1939. def test_program_name_in_help(self):
  1940. out, err = self.run_test(['-m', 'django', 'help'])
  1941. self.assertOutput(out, "Type 'python -m django help <subcommand>' for help on a specific subcommand.")
  1942. class DjangoAdminSuggestions(AdminScriptTestCase):
  1943. def setUp(self):
  1944. super().setUp()
  1945. self.write_settings('settings.py')
  1946. def test_suggestions(self):
  1947. args = ['rnserver', '--settings=test_project.settings']
  1948. out, err = self.run_django_admin(args)
  1949. self.assertNoOutput(out)
  1950. self.assertOutput(err, "Unknown command: 'rnserver'. Did you mean runserver?")
  1951. def test_no_suggestions(self):
  1952. args = ['abcdef', '--settings=test_project.settings']
  1953. out, err = self.run_django_admin(args)
  1954. self.assertNoOutput(out)
  1955. self.assertNotInOutput(err, 'Did you mean')