tests.py 11 KB

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