2
0

tests.py 103 KB

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