Debian Codegraph @

tests/user_commands/tests.py

raw
1 import os
2 import sys
3 import unittest
4 from argparse import ArgumentDefaultsHelpFormatter
5 from io import BytesIO, StringIO, TextIOWrapper
6 from pathlib import Path
7 from unittest import mock
8
9 from admin_scripts.tests import AdminScriptTestCase
10
11 from django.apps import apps
12 from django.core import management
13 from django.core.checks import Tags
14 from django.core.management import BaseCommand, CommandError, find_commands
15 from django.core.management.base import OutputWrapper
16 from django.core.management.utils import (
17 find_command,
18 get_random_secret_key,
19 is_ignored_path,
20 normalize_path_patterns,
21 popen_wrapper,
22 run_formatters,
23 )
24 from django.db import connection
25 from django.test import SimpleTestCase, override_settings
26 from django.test.utils import captured_stderr, extend_sys_path
27 from django.utils import translation
28 from django.utils.version import PY314
29
30 from .management.commands import dance
31 from .utils import AssertFormatterFailureCaughtContext
32
33
34 class OutputWrapperTests(SimpleTestCase):
35 def test_unhandled_exceptions(self):
36 cases = [
37 StringIO("Hello world"),
38 TextIOWrapper(BytesIO(b"Hello world")),
39 ]
40 for out in cases:
41 with self.subTest(out=out):
42 wrapper = OutputWrapper(out)
43 out.close()
44
45 unraisable_exceptions = []
46
47 def unraisablehook(unraisable):
48 unraisable_exceptions.append(unraisable)
49 sys.__unraisablehook__(unraisable)
50
51 with mock.patch.object(sys, "unraisablehook", unraisablehook):
52 del wrapper
53
54 self.assertEqual(unraisable_exceptions, [])
55
56
57 # A minimal set of apps to avoid system checks running on all apps.
58 @override_settings(
59 INSTALLED_APPS=[
60 "django.contrib.auth",
61 "django.contrib.contenttypes",
62 "user_commands",
63 ],
64 )
65 class CommandTests(SimpleTestCase):
66 def test_command(self):
67 out = StringIO()
68 management.call_command("dance", stdout=out)
69 self.assertIn("I don't feel like dancing Rock'n'Roll.\n", out.getvalue())
70
71 def test_command_style(self):
72 out = StringIO()
73 management.call_command("dance", style="Jive", stdout=out)
74 self.assertIn("I don't feel like dancing Jive.\n", out.getvalue())
75 # Passing options as arguments also works (thanks argparse)
76 management.call_command("dance", "--style", "Jive", stdout=out)
77 self.assertIn("I don't feel like dancing Jive.\n", out.getvalue())
78
79 def test_language_preserved(self):
80 with translation.override("fr"):
81 management.call_command("dance", verbosity=0)
82 self.assertEqual(translation.get_language(), "fr")
83
84 def test_explode(self):
85 """An unknown command raises CommandError"""
86 with self.assertRaisesMessage(CommandError, "Unknown command: 'explode'"):
87 management.call_command(("explode",))
88
89 def test_system_exit(self):
90 """Exception raised in a command should raise CommandError with
91 call_command, but SystemExit when run from command line
92 """
93 with self.assertRaises(CommandError) as cm:
94 management.call_command("dance", example="raise")
95 self.assertEqual(cm.exception.returncode, 3)
96 dance.Command.requires_system_checks = []
97 try:
98 with captured_stderr() as stderr, self.assertRaises(SystemExit) as cm:
99 management.ManagementUtility(
100 ["manage.py", "dance", "--example=raise"]
101 ).execute()
102 self.assertEqual(cm.exception.code, 3)
103 finally:
104 dance.Command.requires_system_checks = "__all__"
105 self.assertIn("CommandError", stderr.getvalue())
106
107 def test_no_translations_deactivate_translations(self):
108 """
109 When the Command handle method is decorated with @no_translations,
110 translations are deactivated inside the command.
111 """
112 current_locale = translation.get_language()
113 with translation.override("pl"):
114 result = management.call_command("no_translations")
115 self.assertIsNone(result)
116 self.assertEqual(translation.get_language(), current_locale)
117
118 def test_find_command_without_PATH(self):
119 """
120 find_command should still work when the PATH environment variable
121 doesn't exist (#22256).
122 """
123 current_path = os.environ.pop("PATH", None)
124
125 try:
126 self.assertIsNone(find_command("_missing_"))
127 finally:
128 if current_path is not None:
129 os.environ["PATH"] = current_path
130
131 def test_discover_commands_in_eggs(self):
132 """
133 Management commands can also be loaded from Python eggs.
134 """
135 egg_dir = "%s/eggs" % os.path.dirname(__file__)
136 egg_name = "%s/basic.egg" % egg_dir
137 with extend_sys_path(egg_name):
138 with self.settings(INSTALLED_APPS=["commandegg"]):
139 cmds = find_commands(
140 os.path.join(apps.get_app_config("commandegg").path, "management")
141 )
142 self.assertEqual(cmds, ["eggcommand"])
143
144 def test_call_command_option_parsing(self):
145 """
146 When passing the long option name to call_command, the available option
147 key is the option dest name (#22985).
148 """
149 out = StringIO()
150 management.call_command("dance", stdout=out, opt_3=True)
151 self.assertIn("option3", out.getvalue())
152 self.assertNotIn("opt_3", out.getvalue())
153 self.assertNotIn("opt-3", out.getvalue())
154
155 def test_call_command_option_parsing_non_string_arg(self):
156 """
157 It should be possible to pass non-string arguments to call_command.
158 """
159 out = StringIO()
160 management.call_command("dance", 1, verbosity=0, stdout=out)
161 self.assertIn("You passed 1 as a positional argument.", out.getvalue())
162
163 def test_calling_a_command_with_only_empty_parameter_should_ends_gracefully(self):
164 out = StringIO()
165 management.call_command("hal", "--empty", stdout=out)
166 self.assertEqual(out.getvalue(), "\nDave, I can't do that.\n")
167
168 def test_calling_command_with_app_labels_and_parameters_should_be_ok(self):
169 out = StringIO()
170 management.call_command("hal", "myapp", "--verbosity", "3", stdout=out)
171 self.assertIn(
172 "Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue()
173 )
174
175 def test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok(
176 self,
177 ):
178 out = StringIO()
179 management.call_command("hal", "--verbosity", "3", "myapp", stdout=out)
180 self.assertIn(
181 "Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue()
182 )
183
184 def test_calling_a_command_with_no_app_labels_and_parameters_raise_command_error(
185 self,
186 ):
187 with self.assertRaises(CommandError):
188 management.call_command("hal")
189
190 def test_output_transaction(self):
191 output = management.call_command(
192 "transaction", stdout=StringIO(), no_color=True
193 )
194 self.assertTrue(
195 output.strip().startswith(connection.ops.start_transaction_sql())
196 )
197 self.assertTrue(output.strip().endswith(connection.ops.end_transaction_sql()))
198
199 def test_call_command_no_checks(self):
200 """
201 By default, call_command should not trigger the check framework, unless
202 specifically asked.
203 """
204 self.counter = 0
205
206 def patched_check(self_, **kwargs):
207 self.counter += 1
208 self.kwargs = kwargs
209
210 saved_check = BaseCommand.check
211 BaseCommand.check = patched_check
212 try:
213 management.call_command("dance", verbosity=0)
214 self.assertEqual(self.counter, 0)
215 management.call_command("dance", verbosity=0, skip_checks=False)
216 self.assertEqual(self.counter, 1)
217 self.assertEqual(self.kwargs, {})
218 finally:
219 BaseCommand.check = saved_check
220
221 def test_requires_system_checks_empty(self):
222 with mock.patch(
223 "django.core.management.base.BaseCommand.check"
224 ) as mocked_check:
225 management.call_command("no_system_checks")
226 self.assertIs(mocked_check.called, False)
227
228 def test_requires_system_checks_specific(self):
229 with mock.patch(
230 "django.core.management.base.BaseCommand.check"
231 ) as mocked_check:
232 management.call_command("specific_system_checks", skip_checks=False)
233 mocked_check.assert_called_once_with(tags=[Tags.staticfiles, Tags.models])
234
235 def test_requires_system_checks_invalid(self):
236 class Command(BaseCommand):
237 requires_system_checks = "x"
238
239 msg = "requires_system_checks must be a list or tuple."
240 with self.assertRaisesMessage(TypeError, msg):
241 Command()
242
243 def test_check_migrations(self):
244 requires_migrations_checks = dance.Command.requires_migrations_checks
245 self.assertIs(requires_migrations_checks, False)
246 try:
247 with mock.patch.object(BaseCommand, "check_migrations") as check_migrations:
248 management.call_command("dance", verbosity=0)
249 self.assertFalse(check_migrations.called)
250 dance.Command.requires_migrations_checks = True
251 management.call_command("dance", verbosity=0)
252 self.assertTrue(check_migrations.called)
253 finally:
254 dance.Command.requires_migrations_checks = requires_migrations_checks
255
256 def test_call_command_unrecognized_option(self):
257 msg = (
258 "Unknown option(s) for dance command: unrecognized. Valid options "
259 "are: example, force_color, help, integer, no_color, opt_3, "
260 "option3, pythonpath, settings, skip_checks, stderr, stdout, "
261 "style, traceback, verbosity, version."
262 )
263 with self.assertRaisesMessage(TypeError, msg):
264 management.call_command("dance", unrecognized=1)
265
266 msg = (
267 "Unknown option(s) for dance command: unrecognized, unrecognized2. "
268 "Valid options are: example, force_color, help, integer, no_color, "
269 "opt_3, option3, pythonpath, settings, skip_checks, stderr, "
270 "stdout, style, traceback, verbosity, version."
271 )
272 with self.assertRaisesMessage(TypeError, msg):
273 management.call_command("dance", unrecognized=1, unrecognized2=1)
274
275 def test_call_command_with_required_parameters_in_options(self):
276 out = StringIO()
277 management.call_command(
278 "required_option", need_me="foo", needme2="bar", stdout=out
279 )
280 self.assertIn("need_me", out.getvalue())
281 self.assertIn("needme2", out.getvalue())
282
283 def test_call_command_with_required_parameters_in_mixed_options(self):
284 out = StringIO()
285 management.call_command(
286 "required_option", "--need-me=foo", needme2="bar", stdout=out
287 )
288 self.assertIn("need_me", out.getvalue())
289 self.assertIn("needme2", out.getvalue())
290
291 def test_command_add_arguments_after_common_arguments(self):
292 out = StringIO()
293 management.call_command("common_args", stdout=out)
294 self.assertIn("Detected that --version already exists", out.getvalue())
295
296 def test_mutually_exclusive_group_required_options(self):
297 out = StringIO()
298 management.call_command("mutually_exclusive_required", foo_id=1, stdout=out)
299 self.assertIn("foo_id", out.getvalue())
300 management.call_command(
301 "mutually_exclusive_required", foo_name="foo", stdout=out
302 )
303 self.assertIn("foo_name", out.getvalue())
304 msg = (
305 "Error: one of the arguments --foo-id --foo-name --foo-list "
306 "--append_const --const --count --flag_false --flag_true is "
307 "required"
308 )
309 with self.assertRaisesMessage(CommandError, msg):
310 management.call_command("mutually_exclusive_required", stdout=out)
311
312 def test_mutually_exclusive_group_required_const_options(self):
313 tests = [
314 ("append_const", [42]),
315 ("const", 31),
316 ("count", 1),
317 ("flag_false", False),
318 ("flag_true", True),
319 ]
320 for arg, value in tests:
321 out = StringIO()
322 expected_output = "%s=%s" % (arg, value)
323 with self.subTest(arg=arg):
324 management.call_command(
325 "mutually_exclusive_required",
326 "--%s" % arg,
327 stdout=out,
328 )
329 self.assertIn(expected_output, out.getvalue())
330 out.truncate(0)
331 management.call_command(
332 "mutually_exclusive_required",
333 **{arg: value, "stdout": out},
334 )
335 self.assertIn(expected_output, out.getvalue())
336
337 def test_mutually_exclusive_group_required_with_same_dest_options(self):
338 tests = [
339 {"until": "2"},
340 {"for": "1", "until": "2"},
341 ]
342 msg = (
343 "Cannot pass the dest 'until' that matches multiple arguments via "
344 "**options."
345 )
346 for options in tests:
347 with self.subTest(options=options):
348 with self.assertRaisesMessage(TypeError, msg):
349 management.call_command(
350 "mutually_exclusive_required_with_same_dest",
351 **options,
352 )
353
354 def test_mutually_exclusive_group_required_with_same_dest_args(self):
355 tests = [
356 ("--until=1",),
357 ("--until", 1),
358 ("--for=1",),
359 ("--for", 1),
360 ]
361 for args in tests:
362 out = StringIO()
363 with self.subTest(options=args):
364 management.call_command(
365 "mutually_exclusive_required_with_same_dest",
366 *args,
367 stdout=out,
368 )
369 output = out.getvalue()
370 self.assertIn("until=1", output)
371
372 def test_required_list_option(self):
373 tests = [
374 (("--foo-list", [1, 2]), {}),
375 ((), {"foo_list": [1, 2]}),
376 ]
377 for command in ["mutually_exclusive_required", "required_list_option"]:
378 for args, kwargs in tests:
379 with self.subTest(command=command, args=args, kwargs=kwargs):
380 out = StringIO()
381 management.call_command(
382 command,
383 *args,
384 **kwargs,
385 stdout=out,
386 )
387 self.assertIn("foo_list=[1, 2]", out.getvalue())
388
389 def test_required_const_options(self):
390 args = {
391 "append_const": [42],
392 "const": 31,
393 "count": 1,
394 "flag_false": False,
395 "flag_true": True,
396 }
397 expected_output = "\n".join(
398 "%s=%s" % (arg, value) for arg, value in args.items()
399 )
400 out = StringIO()
401 management.call_command(
402 "required_constant_option",
403 "--append_const",
404 "--const",
405 "--count",
406 "--flag_false",
407 "--flag_true",
408 stdout=out,
409 )
410 self.assertIn(expected_output, out.getvalue())
411 out.truncate(0)
412 management.call_command("required_constant_option", **args, stdout=out)
413 self.assertIn(expected_output, out.getvalue())
414
415 def test_subparser(self):
416 out = StringIO()
417 management.call_command("subparser", "foo", 12, stdout=out)
418 self.assertIn("bar", out.getvalue())
419
420 def test_subparser_dest_args(self):
421 out = StringIO()
422 management.call_command("subparser_dest", "foo", bar=12, stdout=out)
423 self.assertIn("bar", out.getvalue())
424
425 def test_subparser_dest_required_args(self):
426 out = StringIO()
427 management.call_command(
428 "subparser_required", "foo_1", "foo_2", bar=12, stdout=out
429 )
430 self.assertIn("bar", out.getvalue())
431
432 def test_subparser_invalid_option(self):
433 msg = r"invalid choice: 'test' \(choose from '?foo'?\)"
434 with self.assertRaisesRegex(CommandError, msg):
435 management.call_command("subparser", "test", 12)
436 msg = "Error: the following arguments are required: subcommand"
437 with self.assertRaisesMessage(CommandError, msg):
438 management.call_command("subparser_dest", subcommand="foo", bar=12)
439
440 def test_create_parser_kwargs(self):
441 """BaseCommand.create_parser() passes kwargs to CommandParser."""
442 epilog = "some epilog text"
443 parser = BaseCommand().create_parser(
444 "prog_name",
445 "subcommand",
446 epilog=epilog,
447 formatter_class=ArgumentDefaultsHelpFormatter,
448 )
449 self.assertEqual(parser.epilog, epilog)
450 self.assertEqual(parser.formatter_class, ArgumentDefaultsHelpFormatter)
451
452 def test_outputwrapper_flush(self):
453 out = StringIO()
454 with mock.patch.object(out, "flush") as mocked_flush:
455 management.call_command("outputwrapper", stdout=out)
456 self.assertIn("Working...", out.getvalue())
457 self.assertIs(mocked_flush.called, True)
458
459 @unittest.skipUnless(PY314, "Only relevant for Python 3.14+")
460 def test_color_enabled_by_default(self):
461 with mock.patch.dict(os.environ, {}, clear=True):
462 command = BaseCommand()
463 parser = command.create_parser("prog_name", "subcommand")
464 self.assertTrue(parser.color)
465
466 @unittest.skipUnless(PY314, "Only relevant for Python 3.14+")
467 def test_color_disabled_with_django_colors_nocolor(self):
468 with mock.patch.dict(os.environ, {"DJANGO_COLORS": "nocolor"}):
469 command = BaseCommand()
470 parser = command.create_parser("prog_name", "subcommand")
471 self.assertFalse(parser.color)
472
473 @unittest.skipUnless(PY314, "Only relevant for Python 3.14+")
474 def test_force_color_does_not_affect_argparse_color(self):
475 with mock.patch.dict(os.environ, {}, clear=True):
476 command = BaseCommand(force_color=True)
477 parser = command.create_parser("prog_name", "subcommand")
478 self.assertTrue(parser.color)
479
480 @unittest.skipUnless(PY314, "Only relevant for Python 3.14+")
481 def test_no_color_flag_disables_color(self):
482 with mock.patch.object(sys, "argv", ["manage.py", "mycommand", "--no-color"]):
483 command = BaseCommand()
484 parser = command.create_parser("manage.py", "mycommand")
485 self.assertFalse(parser.color)
486
487
488 class CommandRunTests(AdminScriptTestCase):
489 """
490 Tests that need to run by simulating the command line, not by call_command.
491 """
492
493 def test_script_prefix_set_in_commands(self):
494 self.write_settings(
495 "settings.py",
496 apps=["user_commands"],
497 sdict={
498 "ROOT_URLCONF": '"user_commands.urls"',
499 "FORCE_SCRIPT_NAME": '"/PREFIX/"',
500 },
501 )
502 out, err = self.run_manage(["reverse_url"])
503 self.assertNoOutput(err)
504 self.assertEqual(out.strip(), "/PREFIX/some/url/")
505
506 def test_disallowed_abbreviated_options(self):
507 """
508 To avoid conflicts with custom options, commands don't allow
509 abbreviated forms of the --setting and --pythonpath options.
510 """
511 self.write_settings("settings.py", apps=["user_commands"])
512 out, err = self.run_manage(["set_option", "--set", "foo"])
513 self.assertNoOutput(err)
514 self.assertEqual(out.strip(), "Set foo")
515
516 def test_skip_checks(self):
517 self.write_settings(
518 "settings.py",
519 apps=["django.contrib.staticfiles", "user_commands"],
520 sdict={
521 # (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or
522 # list.
523 "STATICFILES_DIRS": '"foo"',
524 },
525 )
526 out, err = self.run_manage(["set_option", "--skip-checks", "--set", "foo"])
527 self.assertNoOutput(err)
528 self.assertEqual(out.strip(), "Set foo")
529
530 def test_subparser_error_formatting(self):
531 self.write_settings("settings.py", apps=["user_commands"])
532 out, err = self.run_manage(["subparser", "foo", "twelve"])
533 self.maxDiff = None
534 self.assertNoOutput(out)
535 err_lines = err.splitlines()
536 self.assertEqual(len(err_lines), 2)
537 self.assertEqual(
538 err_lines[1],
539 "manage.py subparser foo: error: argument bar: invalid int value: 'twelve'",
540 )
541
542 def test_subparser_non_django_error_formatting(self):
543 self.write_settings("settings.py", apps=["user_commands"])
544 out, err = self.run_manage(["subparser_vanilla", "foo", "seven"])
545 self.assertNoOutput(out)
546 err_lines = err.splitlines()
547 self.assertEqual(len(err_lines), 2)
548 self.assertEqual(
549 err_lines[1],
550 "manage.py subparser_vanilla foo: error: argument bar: invalid int value: "
551 "'seven'",
552 )
553
554
555 class UtilsTests(SimpleTestCase):
556 def test_no_existent_external_program(self):
557 msg = "Error executing a_42_command_that_doesnt_exist_42"
558 with self.assertRaisesMessage(CommandError, msg):
559 popen_wrapper(["a_42_command_that_doesnt_exist_42"])
560
561 def test_get_random_secret_key(self):
562 key = get_random_secret_key()
563 self.assertEqual(len(key), 50)
564 for char in key:
565 self.assertIn(char, "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)")
566
567 def test_is_ignored_path_true(self):
568 patterns = (
569 ["foo/bar/baz"],
570 ["baz"],
571 ["foo/bar/baz"],
572 ["*/baz"],
573 ["*"],
574 ["b?z"],
575 ["[abc]az"],
576 ["*/ba[!z]/baz"],
577 )
578 for ignore_patterns in patterns:
579 with self.subTest(ignore_patterns=ignore_patterns):
580 self.assertIs(
581 is_ignored_path("foo/bar/baz", ignore_patterns=ignore_patterns),
582 True,
583 )
584
585 def test_is_ignored_path_false(self):
586 self.assertIs(
587 is_ignored_path(
588 "foo/bar/baz", ignore_patterns=["foo/bar/bat", "bar", "flub/blub"]
589 ),
590 False,
591 )
592
593 def test_normalize_path_patterns_truncates_wildcard_base(self):
594 expected = [os.path.normcase(p) for p in ["foo/bar", "bar/*/"]]
595 self.assertEqual(normalize_path_patterns(["foo/bar/*", "bar/*/"]), expected)
596
597 def test_run_formatters_handles_oserror_for_black_path(self):
598 cases = [
599 (FileNotFoundError, "nonexistent"),
600 (
601 OSError if sys.platform == "win32" else PermissionError,
602 str(Path(__file__).parent / "test_files" / "black"),
603 ),
604 ]
605 for exception, location in cases:
606 with (
607 self.subTest(exception.__qualname__),
608 AssertFormatterFailureCaughtContext(
609 self, shutil_which_result=location
610 ) as ctx,
611 ):
612 run_formatters([], stderr=ctx.stderr)
613 parsed_error = ctx.stderr.getvalue()
614 self.assertIn(exception.__qualname__, parsed_error)
615 if sys.platform != "win32":
616 self.assertIn(location, parsed_error)