tests.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import os
  2. from admin_scripts.tests import AdminScriptTestCase
  3. from django.apps import apps
  4. from django.core import management
  5. from django.core.management import BaseCommand, CommandError, find_commands
  6. from django.core.management.utils import find_command, popen_wrapper
  7. from django.db import connection
  8. from django.test import SimpleTestCase, mock, override_settings
  9. from django.test.utils import captured_stderr, extend_sys_path
  10. from django.utils import translation
  11. from django.utils._os import upath
  12. from django.utils.six import StringIO
  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. """ Test that an unknown command raises CommandError """
  41. with self.assertRaises(CommandError):
  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. with captured_stderr() as stderr, self.assertRaises(SystemExit):
  50. management.ManagementUtility(['manage.py', 'dance', '--example=raise']).execute()
  51. self.assertIn("CommandError", stderr.getvalue())
  52. def test_deactivate_locale_set(self):
  53. # Deactivate translation when set to true
  54. with translation.override('pl'):
  55. result = management.call_command('leave_locale_alone_false', stdout=StringIO())
  56. self.assertIsNone(result)
  57. def test_configured_locale_preserved(self):
  58. # Leaves locale from settings when set to false
  59. with translation.override('pl'):
  60. result = management.call_command('leave_locale_alone_true', stdout=StringIO())
  61. self.assertEqual(result, "pl")
  62. def test_find_command_without_PATH(self):
  63. """
  64. find_command should still work when the PATH environment variable
  65. doesn't exist (#22256).
  66. """
  67. current_path = os.environ.pop('PATH', None)
  68. try:
  69. self.assertIsNone(find_command('_missing_'))
  70. finally:
  71. if current_path is not None:
  72. os.environ['PATH'] = current_path
  73. def test_discover_commands_in_eggs(self):
  74. """
  75. Test that management commands can also be loaded from Python eggs.
  76. """
  77. egg_dir = '%s/eggs' % os.path.dirname(upath(__file__))
  78. egg_name = '%s/basic.egg' % egg_dir
  79. with extend_sys_path(egg_name):
  80. with self.settings(INSTALLED_APPS=['commandegg']):
  81. cmds = find_commands(os.path.join(apps.get_app_config('commandegg').path, 'management'))
  82. self.assertEqual(cmds, ['eggcommand'])
  83. def test_call_command_option_parsing(self):
  84. """
  85. When passing the long option name to call_command, the available option
  86. key is the option dest name (#22985).
  87. """
  88. out = StringIO()
  89. management.call_command('dance', stdout=out, opt_3=True)
  90. self.assertIn("option3", out.getvalue())
  91. self.assertNotIn("opt_3", out.getvalue())
  92. self.assertNotIn("opt-3", out.getvalue())
  93. def test_call_command_option_parsing_non_string_arg(self):
  94. """
  95. It should be possible to pass non-string arguments to call_command.
  96. """
  97. out = StringIO()
  98. management.call_command('dance', 1, verbosity=0, stdout=out)
  99. self.assertIn("You passed 1 as a positional argument.", out.getvalue())
  100. def test_calling_a_command_with_only_empty_parameter_should_ends_gracefully(self):
  101. out = StringIO()
  102. management.call_command('hal', "--empty", stdout=out)
  103. self.assertIn("Dave, I can't do that.\n", out.getvalue())
  104. def test_calling_command_with_app_labels_and_parameters_should_be_ok(self):
  105. out = StringIO()
  106. management.call_command('hal', 'myapp', "--verbosity", "3", stdout=out)
  107. self.assertIn("Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue())
  108. def test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok(self):
  109. out = StringIO()
  110. management.call_command('hal', "--verbosity", "3", "myapp", 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_a_command_with_no_app_labels_and_parameters_should_raise_a_command_error(self):
  113. with self.assertRaises(CommandError):
  114. management.call_command('hal', stdout=StringIO())
  115. def test_output_transaction(self):
  116. output = management.call_command('transaction', stdout=StringIO(), no_color=True)
  117. self.assertTrue(output.strip().startswith(connection.ops.start_transaction_sql()))
  118. self.assertTrue(output.strip().endswith(connection.ops.end_transaction_sql()))
  119. def test_call_command_no_checks(self):
  120. """
  121. By default, call_command should not trigger the check framework, unless
  122. specifically asked.
  123. """
  124. self.counter = 0
  125. def patched_check(self_, **kwargs):
  126. self.counter = self.counter + 1
  127. saved_check = BaseCommand.check
  128. BaseCommand.check = patched_check
  129. try:
  130. management.call_command("dance", verbosity=0)
  131. self.assertEqual(self.counter, 0)
  132. management.call_command("dance", verbosity=0, skip_checks=False)
  133. self.assertEqual(self.counter, 1)
  134. finally:
  135. BaseCommand.check = saved_check
  136. def test_check_migrations(self):
  137. requires_migrations_checks = dance.Command.requires_migrations_checks
  138. self.assertIs(requires_migrations_checks, False)
  139. try:
  140. with mock.patch.object(BaseCommand, 'check_migrations') as check_migrations:
  141. management.call_command('dance', verbosity=0)
  142. self.assertFalse(check_migrations.called)
  143. dance.Command.requires_migrations_checks = True
  144. management.call_command('dance', verbosity=0)
  145. self.assertTrue(check_migrations.called)
  146. finally:
  147. dance.Command.requires_migrations_checks = requires_migrations_checks
  148. class CommandRunTests(AdminScriptTestCase):
  149. """
  150. Tests that need to run by simulating the command line, not by call_command.
  151. """
  152. def tearDown(self):
  153. self.remove_settings('settings.py')
  154. def test_script_prefix_set_in_commands(self):
  155. self.write_settings('settings.py', apps=['user_commands'], sdict={
  156. 'ROOT_URLCONF': '"user_commands.urls"',
  157. 'FORCE_SCRIPT_NAME': '"/PREFIX/"',
  158. })
  159. out, err = self.run_manage(['reverse_url'])
  160. self.assertNoOutput(err)
  161. self.assertEqual(out.strip(), '/PREFIX/some/url/')
  162. class UtilsTests(SimpleTestCase):
  163. def test_no_existent_external_program(self):
  164. with self.assertRaises(CommandError):
  165. popen_wrapper(['a_42_command_that_doesnt_exist_42'])