tests.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import os
  2. from io import StringIO
  3. from unittest import mock
  4. from admin_scripts.tests import AdminScriptTestCase
  5. from django.apps import apps
  6. from django.core import management
  7. from django.core.management import BaseCommand, CommandError, find_commands
  8. from django.core.management.utils import (
  9. find_command, get_random_secret_key, popen_wrapper,
  10. )
  11. from django.db import connection
  12. from django.test import SimpleTestCase, override_settings
  13. from django.test.utils import captured_stderr, extend_sys_path
  14. from django.utils import translation
  15. from .management.commands import dance
  16. # A minimal set of apps to avoid system checks running on all apps.
  17. @override_settings(
  18. INSTALLED_APPS=[
  19. 'django.contrib.auth',
  20. 'django.contrib.contenttypes',
  21. 'user_commands',
  22. ],
  23. )
  24. class CommandTests(SimpleTestCase):
  25. def test_command(self):
  26. out = StringIO()
  27. management.call_command('dance', stdout=out)
  28. self.assertIn("I don't feel like dancing Rock'n'Roll.\n", out.getvalue())
  29. def test_command_style(self):
  30. out = StringIO()
  31. management.call_command('dance', style='Jive', stdout=out)
  32. self.assertIn("I don't feel like dancing Jive.\n", out.getvalue())
  33. # Passing options as arguments also works (thanks argparse)
  34. management.call_command('dance', '--style', 'Jive', stdout=out)
  35. self.assertIn("I don't feel like dancing Jive.\n", out.getvalue())
  36. def test_language_preserved(self):
  37. out = StringIO()
  38. with translation.override('fr'):
  39. management.call_command('dance', stdout=out)
  40. self.assertEqual(translation.get_language(), 'fr')
  41. def test_explode(self):
  42. """ An unknown command raises CommandError """
  43. with self.assertRaisesMessage(CommandError, "Unknown command: 'explode'"):
  44. management.call_command(('explode',))
  45. def test_system_exit(self):
  46. """ Exception raised in a command should raise CommandError with
  47. call_command, but SystemExit when run from command line
  48. """
  49. with self.assertRaises(CommandError):
  50. management.call_command('dance', example="raise")
  51. dance.Command.requires_system_checks = False
  52. try:
  53. with captured_stderr() as stderr, self.assertRaises(SystemExit):
  54. management.ManagementUtility(['manage.py', 'dance', '--example=raise']).execute()
  55. finally:
  56. dance.Command.requires_system_checks = True
  57. self.assertIn("CommandError", stderr.getvalue())
  58. def test_no_translations_deactivate_translations(self):
  59. """
  60. When the Command handle method is decorated with @no_translations,
  61. translations are deactivated inside the command.
  62. """
  63. current_locale = translation.get_language()
  64. with translation.override('pl'):
  65. result = management.call_command('no_translations', stdout=StringIO())
  66. self.assertIsNone(result)
  67. self.assertEqual(translation.get_language(), current_locale)
  68. def test_find_command_without_PATH(self):
  69. """
  70. find_command should still work when the PATH environment variable
  71. doesn't exist (#22256).
  72. """
  73. current_path = os.environ.pop('PATH', None)
  74. try:
  75. self.assertIsNone(find_command('_missing_'))
  76. finally:
  77. if current_path is not None:
  78. os.environ['PATH'] = current_path
  79. def test_discover_commands_in_eggs(self):
  80. """
  81. Management commands can also be loaded from Python eggs.
  82. """
  83. egg_dir = '%s/eggs' % os.path.dirname(__file__)
  84. egg_name = '%s/basic.egg' % egg_dir
  85. with extend_sys_path(egg_name):
  86. with self.settings(INSTALLED_APPS=['commandegg']):
  87. cmds = find_commands(os.path.join(apps.get_app_config('commandegg').path, 'management'))
  88. self.assertEqual(cmds, ['eggcommand'])
  89. def test_call_command_option_parsing(self):
  90. """
  91. When passing the long option name to call_command, the available option
  92. key is the option dest name (#22985).
  93. """
  94. out = StringIO()
  95. management.call_command('dance', stdout=out, opt_3=True)
  96. self.assertIn("option3", out.getvalue())
  97. self.assertNotIn("opt_3", out.getvalue())
  98. self.assertNotIn("opt-3", out.getvalue())
  99. def test_call_command_option_parsing_non_string_arg(self):
  100. """
  101. It should be possible to pass non-string arguments to call_command.
  102. """
  103. out = StringIO()
  104. management.call_command('dance', 1, verbosity=0, stdout=out)
  105. self.assertIn("You passed 1 as a positional argument.", out.getvalue())
  106. def test_calling_a_command_with_only_empty_parameter_should_ends_gracefully(self):
  107. out = StringIO()
  108. management.call_command('hal', "--empty", stdout=out)
  109. self.assertIn("Dave, I can't do that.\n", out.getvalue())
  110. def test_calling_command_with_app_labels_and_parameters_should_be_ok(self):
  111. out = StringIO()
  112. management.call_command('hal', 'myapp', "--verbosity", "3", stdout=out)
  113. self.assertIn("Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue())
  114. def test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok(self):
  115. out = StringIO()
  116. management.call_command('hal', "--verbosity", "3", "myapp", stdout=out)
  117. self.assertIn("Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue())
  118. def test_calling_a_command_with_no_app_labels_and_parameters_should_raise_a_command_error(self):
  119. with self.assertRaises(CommandError):
  120. management.call_command('hal', stdout=StringIO())
  121. def test_output_transaction(self):
  122. output = management.call_command('transaction', stdout=StringIO(), no_color=True)
  123. self.assertTrue(output.strip().startswith(connection.ops.start_transaction_sql()))
  124. self.assertTrue(output.strip().endswith(connection.ops.end_transaction_sql()))
  125. def test_call_command_no_checks(self):
  126. """
  127. By default, call_command should not trigger the check framework, unless
  128. specifically asked.
  129. """
  130. self.counter = 0
  131. def patched_check(self_, **kwargs):
  132. self.counter += 1
  133. saved_check = BaseCommand.check
  134. BaseCommand.check = patched_check
  135. try:
  136. management.call_command("dance", verbosity=0)
  137. self.assertEqual(self.counter, 0)
  138. management.call_command("dance", verbosity=0, skip_checks=False)
  139. self.assertEqual(self.counter, 1)
  140. finally:
  141. BaseCommand.check = saved_check
  142. def test_check_migrations(self):
  143. requires_migrations_checks = dance.Command.requires_migrations_checks
  144. self.assertIs(requires_migrations_checks, False)
  145. try:
  146. with mock.patch.object(BaseCommand, 'check_migrations') as check_migrations:
  147. management.call_command('dance', verbosity=0)
  148. self.assertFalse(check_migrations.called)
  149. dance.Command.requires_migrations_checks = True
  150. management.call_command('dance', verbosity=0)
  151. self.assertTrue(check_migrations.called)
  152. finally:
  153. dance.Command.requires_migrations_checks = requires_migrations_checks
  154. def test_call_command_unrecognized_option(self):
  155. msg = (
  156. 'Unknown option(s) for dance command: unrecognized. Valid options '
  157. 'are: example, force_color, help, integer, no_color, opt_3, '
  158. 'option3, pythonpath, settings, skip_checks, stderr, stdout, '
  159. 'style, traceback, verbosity, version.'
  160. )
  161. with self.assertRaisesMessage(TypeError, msg):
  162. management.call_command('dance', unrecognized=1)
  163. msg = (
  164. 'Unknown option(s) for dance command: unrecognized, unrecognized2. '
  165. 'Valid options are: example, force_color, help, integer, no_color, '
  166. 'opt_3, option3, pythonpath, settings, skip_checks, stderr, '
  167. 'stdout, style, traceback, verbosity, version.'
  168. )
  169. with self.assertRaisesMessage(TypeError, msg):
  170. management.call_command('dance', unrecognized=1, unrecognized2=1)
  171. def test_call_command_with_required_parameters_in_options(self):
  172. out = StringIO()
  173. management.call_command('required_option', need_me='foo', needme2='bar', stdout=out)
  174. self.assertIn('need_me', out.getvalue())
  175. self.assertIn('needme2', out.getvalue())
  176. def test_call_command_with_required_parameters_in_mixed_options(self):
  177. out = StringIO()
  178. management.call_command('required_option', '--need-me=foo', needme2='bar', stdout=out)
  179. self.assertIn('need_me', out.getvalue())
  180. self.assertIn('needme2', out.getvalue())
  181. def test_command_add_arguments_after_common_arguments(self):
  182. out = StringIO()
  183. management.call_command('common_args', stdout=out)
  184. self.assertIn('Detected that --version already exists', out.getvalue())
  185. def test_subparser(self):
  186. out = StringIO()
  187. management.call_command('subparser', 'foo', 12, stdout=out)
  188. self.assertIn('bar', out.getvalue())
  189. def test_subparser_invalid_option(self):
  190. msg = "Error: invalid choice: 'test' (choose from 'foo')"
  191. with self.assertRaisesMessage(CommandError, msg):
  192. management.call_command('subparser', 'test', 12)
  193. def test_create_parser_kwargs(self):
  194. """BaseCommand.create_parser() passes kwargs to CommandParser."""
  195. epilog = 'some epilog text'
  196. parser = BaseCommand().create_parser('prog_name', 'subcommand', epilog=epilog)
  197. self.assertEqual(parser.epilog, epilog)
  198. class CommandRunTests(AdminScriptTestCase):
  199. """
  200. Tests that need to run by simulating the command line, not by call_command.
  201. """
  202. def tearDown(self):
  203. self.remove_settings('settings.py')
  204. def test_script_prefix_set_in_commands(self):
  205. self.write_settings('settings.py', apps=['user_commands'], sdict={
  206. 'ROOT_URLCONF': '"user_commands.urls"',
  207. 'FORCE_SCRIPT_NAME': '"/PREFIX/"',
  208. })
  209. out, err = self.run_manage(['reverse_url'])
  210. self.assertNoOutput(err)
  211. self.assertEqual(out.strip(), '/PREFIX/some/url/')
  212. def test_disallowed_abbreviated_options(self):
  213. """
  214. To avoid conflicts with custom options, commands don't allow
  215. abbreviated forms of the --setting and --pythonpath options.
  216. """
  217. self.write_settings('settings.py', apps=['user_commands'])
  218. out, err = self.run_manage(['set_option', '--set', 'foo'])
  219. self.assertNoOutput(err)
  220. self.assertEqual(out.strip(), 'Set foo')
  221. class UtilsTests(SimpleTestCase):
  222. def test_no_existent_external_program(self):
  223. msg = 'Error executing a_42_command_that_doesnt_exist_42'
  224. with self.assertRaisesMessage(CommandError, msg):
  225. popen_wrapper(['a_42_command_that_doesnt_exist_42'])
  226. def test_get_random_secret_key(self):
  227. key = get_random_secret_key()
  228. self.assertEqual(len(key), 50)
  229. for char in key:
  230. self.assertIn(char, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')