tests.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import os
  2. from django.apps import apps
  3. from django.db import connection
  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.test import SimpleTestCase, ignore_warnings
  8. from django.test.utils import captured_stderr, captured_stdout, extend_sys_path
  9. from django.utils import translation
  10. from django.utils.deprecation import RemovedInDjango20Warning
  11. from django.utils._os import upath
  12. from django.utils.six import StringIO
  13. class CommandTests(SimpleTestCase):
  14. def test_command(self):
  15. out = StringIO()
  16. management.call_command('dance', stdout=out)
  17. self.assertIn("I don't feel like dancing Rock'n'Roll.\n", out.getvalue())
  18. def test_command_style(self):
  19. out = StringIO()
  20. management.call_command('dance', style='Jive', stdout=out)
  21. self.assertIn("I don't feel like dancing Jive.\n", out.getvalue())
  22. # Passing options as arguments also works (thanks argparse)
  23. management.call_command('dance', '--style', 'Jive', stdout=out)
  24. self.assertIn("I don't feel like dancing Jive.\n", out.getvalue())
  25. def test_language_preserved(self):
  26. out = StringIO()
  27. with translation.override('fr'):
  28. management.call_command('dance', stdout=out)
  29. self.assertEqual(translation.get_language(), 'fr')
  30. def test_explode(self):
  31. """ Test that an unknown command raises CommandError """
  32. self.assertRaises(CommandError, management.call_command, ('explode',))
  33. def test_system_exit(self):
  34. """ Exception raised in a command should raise CommandError with
  35. call_command, but SystemExit when run from command line
  36. """
  37. with self.assertRaises(CommandError):
  38. management.call_command('dance', example="raise")
  39. with captured_stderr() as stderr, self.assertRaises(SystemExit):
  40. management.ManagementUtility(['manage.py', 'dance', '--example=raise']).execute()
  41. self.assertIn("CommandError", stderr.getvalue())
  42. def test_deactivate_locale_set(self):
  43. # Deactivate translation when set to true
  44. out = StringIO()
  45. with translation.override('pl'):
  46. management.call_command('leave_locale_alone_false', stdout=out)
  47. self.assertEqual(out.getvalue(), "")
  48. def test_configured_locale_preserved(self):
  49. # Leaves locale from settings when set to false
  50. out = StringIO()
  51. with translation.override('pl'):
  52. management.call_command('leave_locale_alone_true', stdout=out)
  53. self.assertEqual(out.getvalue(), "pl\n")
  54. def test_find_command_without_PATH(self):
  55. """
  56. find_command should still work when the PATH environment variable
  57. doesn't exist (#22256).
  58. """
  59. current_path = os.environ.pop('PATH', None)
  60. try:
  61. self.assertIsNone(find_command('_missing_'))
  62. finally:
  63. if current_path is not None:
  64. os.environ['PATH'] = current_path
  65. def test_discover_commands_in_eggs(self):
  66. """
  67. Test that management commands can also be loaded from Python eggs.
  68. """
  69. egg_dir = '%s/eggs' % os.path.dirname(upath(__file__))
  70. egg_name = '%s/basic.egg' % egg_dir
  71. with extend_sys_path(egg_name):
  72. with self.settings(INSTALLED_APPS=['commandegg']):
  73. cmds = find_commands(os.path.join(apps.get_app_config('commandegg').path, 'management'))
  74. self.assertEqual(cmds, ['eggcommand'])
  75. def test_call_command_option_parsing(self):
  76. """
  77. When passing the long option name to call_command, the available option
  78. key is the option dest name (#22985).
  79. """
  80. out = StringIO()
  81. management.call_command('dance', stdout=out, opt_3=True)
  82. self.assertIn("option3", out.getvalue())
  83. self.assertNotIn("opt_3", out.getvalue())
  84. self.assertNotIn("opt-3", out.getvalue())
  85. @ignore_warnings(category=RemovedInDjango20Warning)
  86. def test_optparse_compatibility(self):
  87. """
  88. optparse should be supported during Django 1.8/1.9 releases.
  89. """
  90. out = StringIO()
  91. management.call_command('optparse_cmd', stdout=out)
  92. self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n")
  93. # Simulate command line execution
  94. with captured_stdout() as stdout, captured_stderr():
  95. management.execute_from_command_line(['django-admin', 'optparse_cmd'])
  96. self.assertEqual(stdout.getvalue(), "All right, let's dance Rock'n'Roll.\n")
  97. def test_calling_a_command_with_only_empty_parameter_should_ends_gracefully(self):
  98. out = StringIO()
  99. management.call_command('hal', "--empty", stdout=out)
  100. self.assertIn("Dave, I can't do that.\n", out.getvalue())
  101. def test_calling_command_with_app_labels_and_parameters_should_be_ok(self):
  102. out = StringIO()
  103. management.call_command('hal', 'myapp', "--verbosity", "3", stdout=out)
  104. self.assertIn("Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue())
  105. def test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok(self):
  106. out = StringIO()
  107. management.call_command('hal', "--verbosity", "3", "myapp", stdout=out)
  108. self.assertIn("Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue())
  109. def test_calling_a_command_with_no_app_labels_and_parameters_should_raise_a_command_error(self):
  110. out = StringIO()
  111. with self.assertRaises(CommandError):
  112. management.call_command('hal', stdout=out)
  113. def test_output_transaction(self):
  114. out = StringIO()
  115. management.call_command('transaction', stdout=out, no_color=True)
  116. output = out.getvalue().strip()
  117. self.assertTrue(output.startswith(connection.ops.start_transaction_sql()))
  118. self.assertTrue(output.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. class UtilsTests(SimpleTestCase):
  137. def test_no_existent_external_program(self):
  138. self.assertRaises(CommandError, popen_wrapper, ['a_42_command_that_doesnt_exist_42'])