| 1 |
import os |
| 2 |
import subprocess |
| 3 |
import sys |
| 4 |
import unittest |
| 5 |
from unittest import mock |
| 6 |
|
| 7 |
from django import __version__ |
| 8 |
from django.contrib.auth.models import Group, Permission, User |
| 9 |
from django.contrib.contenttypes.models import ContentType |
| 10 |
from django.core.management import CommandError, call_command |
| 11 |
from django.core.management.commands import shell |
| 12 |
from django.db import connection |
| 13 |
from django.test import SimpleTestCase |
| 14 |
from django.test.utils import captured_stdin, captured_stdout, override_settings |
| 15 |
from django.urls import resolve, reverse |
| 16 |
|
| 17 |
from .models import Marker, Phone |
| 18 |
|
| 19 |
|
| 20 |
class ShellCommandTestCase(SimpleTestCase): |
| 21 |
script_globals = 'print("__name__" in globals() and "Phone" in globals())' |
| 22 |
script_with_inline_function = ( |
| 23 |
"import django\ndef f():\n print(django.__version__)\nf()" |
| 24 |
) |
| 25 |
|
| 26 |
def test_command_option(self): |
| 27 |
with self.assertLogs("test", "INFO") as cm: |
| 28 |
with captured_stdout(): |
| 29 |
call_command( |
| 30 |
"shell", |
| 31 |
command=( |
| 32 |
"import django; from logging import getLogger; " |
| 33 |
'getLogger("test").info(django.__version__)' |
| 34 |
), |
| 35 |
) |
| 36 |
self.assertEqual(cm.records[0].getMessage(), __version__) |
| 37 |
|
| 38 |
def test_command_option_globals(self): |
| 39 |
with captured_stdout() as stdout: |
| 40 |
call_command("shell", command=self.script_globals, verbosity=0) |
| 41 |
self.assertEqual(stdout.getvalue().strip(), "True") |
| 42 |
|
| 43 |
def test_command_option_inline_function_call(self): |
| 44 |
with captured_stdout() as stdout: |
| 45 |
call_command("shell", command=self.script_with_inline_function, verbosity=0) |
| 46 |
self.assertEqual(stdout.getvalue().strip(), __version__) |
| 47 |
|
| 48 |
@override_settings(INSTALLED_APPS=["shell"]) |
| 49 |
def test_no_settings(self): |
| 50 |
test_environ = os.environ.copy() |
| 51 |
if "DJANGO_SETTINGS_MODULE" in test_environ: |
| 52 |
del test_environ["DJANGO_SETTINGS_MODULE"] |
| 53 |
error = ( |
| 54 |
"Automatic imports are disabled since settings are not configured.\n" |
| 55 |
"DJANGO_SETTINGS_MODULE value is None.\n" |
| 56 |
"HINT: Ensure that the settings module is configured and set.\n\n" |
| 57 |
) |
| 58 |
for verbosity, assertError in [ |
| 59 |
("0", self.assertNotIn), |
| 60 |
("1", self.assertIn), |
| 61 |
("2", self.assertIn), |
| 62 |
]: |
| 63 |
with self.subTest(verbosity=verbosity, get_auto_imports="models"): |
| 64 |
p = subprocess.run( |
| 65 |
[ |
| 66 |
sys.executable, |
| 67 |
"-m", |
| 68 |
"django", |
| 69 |
"shell", |
| 70 |
"-c", |
| 71 |
"print(globals())", |
| 72 |
"-v", |
| 73 |
verbosity, |
| 74 |
], |
| 75 |
capture_output=True, |
| 76 |
env=test_environ, |
| 77 |
text=True, |
| 78 |
umask=-1, |
| 79 |
) |
| 80 |
assertError(error, p.stdout) |
| 81 |
self.assertNotIn("Marker", p.stdout) |
| 82 |
|
| 83 |
with self.subTest(verbosity=verbosity, get_auto_imports="without-models"): |
| 84 |
with mock.patch( |
| 85 |
"django.core.management.commands.shell.Command.get_auto_imports", |
| 86 |
return_value=["django.urls.resolve"], |
| 87 |
): |
| 88 |
p = subprocess.run( |
| 89 |
[ |
| 90 |
sys.executable, |
| 91 |
"-m", |
| 92 |
"django", |
| 93 |
"shell", |
| 94 |
"-c", |
| 95 |
"print(globals())", |
| 96 |
"-v", |
| 97 |
verbosity, |
| 98 |
], |
| 99 |
capture_output=True, |
| 100 |
env=test_environ, |
| 101 |
text=True, |
| 102 |
umask=-1, |
| 103 |
) |
| 104 |
assertError(error, p.stdout) |
| 105 |
self.assertNotIn("resolve", p.stdout) |
| 106 |
|
| 107 |
@unittest.skipIf( |
| 108 |
sys.platform == "win32", "Windows select() doesn't support file descriptors." |
| 109 |
) |
| 110 |
@mock.patch("django.core.management.commands.shell.select") |
| 111 |
def test_stdin_read(self, select): |
| 112 |
with captured_stdin() as stdin, captured_stdout() as stdout: |
| 113 |
stdin.write("print(100)\n") |
| 114 |
stdin.seek(0) |
| 115 |
call_command("shell", verbosity=0) |
| 116 |
self.assertEqual(stdout.getvalue().strip(), "100") |
| 117 |
|
| 118 |
@unittest.skipIf( |
| 119 |
sys.platform == "win32", |
| 120 |
"Windows select() doesn't support file descriptors.", |
| 121 |
) |
| 122 |
@mock.patch("django.core.management.commands.shell.select") # [1] |
| 123 |
def test_stdin_read_globals(self, select): |
| 124 |
with captured_stdin() as stdin, captured_stdout() as stdout: |
| 125 |
stdin.write(self.script_globals) |
| 126 |
stdin.seek(0) |
| 127 |
call_command("shell", verbosity=0) |
| 128 |
self.assertEqual(stdout.getvalue().strip(), "True") |
| 129 |
|
| 130 |
@unittest.skipIf( |
| 131 |
sys.platform == "win32", |
| 132 |
"Windows select() doesn't support file descriptors.", |
| 133 |
) |
| 134 |
@mock.patch("django.core.management.commands.shell.select") # [1] |
| 135 |
def test_stdin_read_inline_function_call(self, select): |
| 136 |
with captured_stdin() as stdin, captured_stdout() as stdout: |
| 137 |
stdin.write(self.script_with_inline_function) |
| 138 |
stdin.seek(0) |
| 139 |
call_command("shell", verbosity=0) |
| 140 |
self.assertEqual(stdout.getvalue().strip(), __version__) |
| 141 |
|
| 142 |
def test_ipython(self): |
| 143 |
cmd = shell.Command() |
| 144 |
mock_ipython = mock.Mock(start_ipython=mock.MagicMock()) |
| 145 |
options = {"verbosity": 0, "no_imports": False} |
| 146 |
|
| 147 |
with mock.patch.dict(sys.modules, {"IPython": mock_ipython}): |
| 148 |
cmd.ipython(options) |
| 149 |
|
| 150 |
self.assertEqual( |
| 151 |
mock_ipython.start_ipython.mock_calls, |
| 152 |
[mock.call(argv=[], user_ns=cmd.get_namespace(**options))], |
| 153 |
) |
| 154 |
|
| 155 |
@mock.patch("django.core.management.commands.shell.select.select") # [1] |
| 156 |
@mock.patch.dict("sys.modules", {"IPython": None}) |
| 157 |
def test_shell_with_ipython_not_installed(self, select): |
| 158 |
select.return_value = ([], [], []) |
| 159 |
with self.assertRaisesMessage( |
| 160 |
CommandError, "Couldn't import ipython interface." |
| 161 |
): |
| 162 |
call_command("shell", interface="ipython") |
| 163 |
|
| 164 |
def test_bpython(self): |
| 165 |
cmd = shell.Command() |
| 166 |
mock_bpython = mock.Mock(embed=mock.MagicMock()) |
| 167 |
options = {"verbosity": 0, "no_imports": False} |
| 168 |
|
| 169 |
with mock.patch.dict(sys.modules, {"bpython": mock_bpython}): |
| 170 |
cmd.bpython(options) |
| 171 |
|
| 172 |
self.assertEqual( |
| 173 |
mock_bpython.embed.mock_calls, [mock.call(cmd.get_namespace(**options))] |
| 174 |
) |
| 175 |
|
| 176 |
@mock.patch("django.core.management.commands.shell.select.select") # [1] |
| 177 |
@mock.patch.dict("sys.modules", {"bpython": None}) |
| 178 |
def test_shell_with_bpython_not_installed(self, select): |
| 179 |
select.return_value = ([], [], []) |
| 180 |
with self.assertRaisesMessage( |
| 181 |
CommandError, "Couldn't import bpython interface." |
| 182 |
): |
| 183 |
call_command("shell", interface="bpython") |
| 184 |
|
| 185 |
def test_python(self): |
| 186 |
cmd = shell.Command() |
| 187 |
mock_code = mock.Mock(interact=mock.MagicMock()) |
| 188 |
options = {"verbosity": 0, "no_startup": True, "no_imports": False} |
| 189 |
|
| 190 |
with mock.patch.dict(sys.modules, {"code": mock_code}): |
| 191 |
cmd.python(options) |
| 192 |
|
| 193 |
self.assertEqual( |
| 194 |
mock_code.interact.mock_calls, |
| 195 |
[mock.call(local=cmd.get_namespace(**options))], |
| 196 |
) |
| 197 |
|
| 198 |
# [1] Patch select to prevent tests failing when the test suite is run |
| 199 |
# in parallel mode. The tests are run in a subprocess and the subprocess's |
| 200 |
# stdin is closed and replaced by /dev/null. Reading from /dev/null always |
| 201 |
# returns EOF and so select always shows that sys.stdin is ready to read. |
| 202 |
# This causes problems because of the call to select.select() toward the |
| 203 |
# end of shell's handle() method. |
| 204 |
|
| 205 |
|
| 206 |
class ShellCommandAutoImportsTestCase(SimpleTestCase): |
| 207 |
|
| 208 |
@override_settings( |
| 209 |
INSTALLED_APPS=["shell", "django.contrib.auth", "django.contrib.contenttypes"] |
| 210 |
) |
| 211 |
def test_get_namespace(self): |
| 212 |
namespace = shell.Command().get_namespace() |
| 213 |
|
| 214 |
self.assertEqual( |
| 215 |
namespace, |
| 216 |
{ |
| 217 |
"Marker": Marker, |
| 218 |
"Phone": Phone, |
| 219 |
"ContentType": ContentType, |
| 220 |
"Group": Group, |
| 221 |
"Permission": Permission, |
| 222 |
"User": User, |
| 223 |
}, |
| 224 |
) |
| 225 |
|
| 226 |
@override_settings( |
| 227 |
INSTALLED_APPS=["model_forms", "contenttypes_tests", "forms_tests"] |
| 228 |
) |
| 229 |
def test_get_namespace_precedence(self): |
| 230 |
# All of these apps define an `Article` model. The one defined first in |
| 231 |
# INSTALLED_APPS, takes precedence. |
| 232 |
import model_forms.models |
| 233 |
|
| 234 |
namespace = shell.Command().get_namespace() |
| 235 |
self.assertIs(namespace.get("Article"), model_forms.models.Article) |
| 236 |
|
| 237 |
@override_settings( |
| 238 |
INSTALLED_APPS=["shell", "django.contrib.auth", "django.contrib.contenttypes"] |
| 239 |
) |
| 240 |
def test_get_namespace_overridden(self): |
| 241 |
class TestCommand(shell.Command): |
| 242 |
def get_auto_imports(self): |
| 243 |
return super().get_auto_imports() + [ |
| 244 |
"django.urls.reverse", |
| 245 |
"django.urls.resolve", |
| 246 |
"django.db.connection", |
| 247 |
] |
| 248 |
|
| 249 |
namespace = TestCommand().get_namespace() |
| 250 |
|
| 251 |
self.assertEqual( |
| 252 |
namespace, |
| 253 |
{ |
| 254 |
"connection": connection, |
| 255 |
"resolve": resolve, |
| 256 |
"reverse": reverse, |
| 257 |
"Marker": Marker, |
| 258 |
"Phone": Phone, |
| 259 |
"ContentType": ContentType, |
| 260 |
"Group": Group, |
| 261 |
"Permission": Permission, |
| 262 |
"User": User, |
| 263 |
}, |
| 264 |
) |
| 265 |
|
| 266 |
@override_settings( |
| 267 |
INSTALLED_APPS=["shell", "django.contrib.auth", "django.contrib.contenttypes"] |
| 268 |
) |
| 269 |
def test_no_imports_flag(self): |
| 270 |
for verbosity in (0, 1, 2, 3): |
| 271 |
with self.subTest(verbosity=verbosity), captured_stdout() as stdout: |
| 272 |
namespace = shell.Command().get_namespace( |
| 273 |
verbosity=verbosity, no_imports=True |
| 274 |
) |
| 275 |
self.assertEqual(namespace, {}) |
| 276 |
self.assertEqual(stdout.getvalue().strip(), "") |
| 277 |
|
| 278 |
@override_settings( |
| 279 |
INSTALLED_APPS=["shell", "django.contrib.auth", "django.contrib.contenttypes"] |
| 280 |
) |
| 281 |
def test_verbosity_zero(self): |
| 282 |
with captured_stdout() as stdout: |
| 283 |
cmd = shell.Command() |
| 284 |
namespace = cmd.get_namespace(verbosity=0) |
| 285 |
self.assertEqual(len(namespace), len(cmd.get_auto_imports())) |
| 286 |
self.assertEqual(stdout.getvalue().strip(), "") |
| 287 |
|
| 288 |
@override_settings( |
| 289 |
INSTALLED_APPS=["shell", "django.contrib.auth", "django.contrib.contenttypes"] |
| 290 |
) |
| 291 |
def test_verbosity_one(self): |
| 292 |
with captured_stdout() as stdout: |
| 293 |
cmd = shell.Command() |
| 294 |
namespace = cmd.get_namespace(verbosity=1) |
| 295 |
self.assertEqual(len(namespace), len(cmd.get_auto_imports())) |
| 296 |
self.assertEqual( |
| 297 |
stdout.getvalue().strip(), |
| 298 |
"6 objects imported automatically (use -v 2 for details).", |
| 299 |
) |
| 300 |
|
| 301 |
@override_settings(INSTALLED_APPS=["shell", "django.contrib.contenttypes"]) |
| 302 |
@mock.patch.dict(sys.modules, {"isort": None}) |
| 303 |
def test_message_with_stdout_listing_objects_with_isort_not_installed(self): |
| 304 |
class TestCommand(shell.Command): |
| 305 |
def get_auto_imports(self): |
| 306 |
# Include duplicate import strings to ensure proper handling, |
| 307 |
# independent of isort's deduplication (#36252). |
| 308 |
return super().get_auto_imports() + [ |
| 309 |
"django.urls.reverse", |
| 310 |
"django.urls.resolve", |
| 311 |
"shell", |
| 312 |
"django", |
| 313 |
"django.urls.reverse", |
| 314 |
"shell", |
| 315 |
"django", |
| 316 |
] |
| 317 |
|
| 318 |
with captured_stdout() as stdout: |
| 319 |
TestCommand().get_namespace(verbosity=2) |
| 320 |
|
| 321 |
self.assertEqual( |
| 322 |
stdout.getvalue().strip(), |
| 323 |
"7 objects imported automatically:\n\n" |
| 324 |
" import shell\n" |
| 325 |
" import django\n" |
| 326 |
" from django.contrib.contenttypes.models import ContentType\n" |
| 327 |
" from shell.models import Phone, Marker\n" |
| 328 |
" from django.urls import reverse, resolve", |
| 329 |
) |
| 330 |
|
| 331 |
def test_message_with_stdout_one_object(self): |
| 332 |
class TestCommand(shell.Command): |
| 333 |
def get_auto_imports(self): |
| 334 |
return ["django.db.connection"] |
| 335 |
|
| 336 |
with captured_stdout() as stdout: |
| 337 |
TestCommand().get_namespace(verbosity=2) |
| 338 |
|
| 339 |
cases = { |
| 340 |
0: "", |
| 341 |
1: "1 object imported automatically (use -v 2 for details).", |
| 342 |
2: ( |
| 343 |
"1 object imported automatically:\n\n" |
| 344 |
" from django.db import connection" |
| 345 |
), |
| 346 |
} |
| 347 |
for verbosity, expected in cases.items(): |
| 348 |
with self.subTest(verbosity=verbosity): |
| 349 |
with captured_stdout() as stdout: |
| 350 |
TestCommand().get_namespace(verbosity=verbosity) |
| 351 |
self.assertEqual(stdout.getvalue().strip(), expected) |
| 352 |
|
| 353 |
@override_settings(INSTALLED_APPS=[]) |
| 354 |
def test_message_with_stdout_no_installed_apps(self): |
| 355 |
cases = { |
| 356 |
0: "", |
| 357 |
1: "0 objects imported automatically.", |
| 358 |
2: "0 objects imported automatically.", |
| 359 |
} |
| 360 |
for verbosity, expected in cases.items(): |
| 361 |
with self.subTest(verbosity=verbosity): |
| 362 |
with captured_stdout() as stdout: |
| 363 |
shell.Command().get_namespace(verbosity=verbosity) |
| 364 |
self.assertEqual(stdout.getvalue().strip(), expected) |
| 365 |
|
| 366 |
def test_message_with_stdout_overriden_none_result(self): |
| 367 |
class TestCommand(shell.Command): |
| 368 |
def get_auto_imports(self): |
| 369 |
return None |
| 370 |
|
| 371 |
for verbosity in [0, 1, 2]: |
| 372 |
with self.subTest(verbosity=verbosity): |
| 373 |
with captured_stdout() as stdout: |
| 374 |
result = TestCommand().get_namespace(verbosity=verbosity) |
| 375 |
self.assertEqual(result, {}) |
| 376 |
self.assertEqual(stdout.getvalue().strip(), "") |
| 377 |
|
| 378 |
@override_settings(INSTALLED_APPS=["shell", "django.contrib.contenttypes"]) |
| 379 |
def test_message_with_stdout_listing_objects_with_isort(self): |
| 380 |
sorted_imports = ( |
| 381 |
" from shell.models import Marker, Phone\n\n" |
| 382 |
" from django.contrib.contenttypes.models import ContentType" |
| 383 |
) |
| 384 |
mock_isort_code = mock.Mock(code=mock.MagicMock(return_value=sorted_imports)) |
| 385 |
|
| 386 |
class TestCommand(shell.Command): |
| 387 |
def get_auto_imports(self): |
| 388 |
return super().get_auto_imports() + [ |
| 389 |
"django.urls.reverse", |
| 390 |
"django.urls.resolve", |
| 391 |
"django", |
| 392 |
] |
| 393 |
|
| 394 |
with ( |
| 395 |
mock.patch.dict(sys.modules, {"isort": mock_isort_code}), |
| 396 |
captured_stdout() as stdout, |
| 397 |
): |
| 398 |
TestCommand().get_namespace(verbosity=2) |
| 399 |
|
| 400 |
self.assertEqual( |
| 401 |
stdout.getvalue().strip(), |
| 402 |
"6 objects imported automatically:\n\n" + sorted_imports, |
| 403 |
) |
| 404 |
|
| 405 |
def test_override_get_auto_imports(self): |
| 406 |
class TestCommand(shell.Command): |
| 407 |
def get_auto_imports(self): |
| 408 |
return [ |
| 409 |
"model_forms", |
| 410 |
"shell", |
| 411 |
"does.not.exist", |
| 412 |
"doesntexisteither", |
| 413 |
] |
| 414 |
|
| 415 |
with captured_stdout() as stdout: |
| 416 |
TestCommand().get_namespace(verbosity=2) |
| 417 |
|
| 418 |
expected = ( |
| 419 |
"2 objects could not be automatically imported:\n\n" |
| 420 |
" does.not.exist\n" |
| 421 |
" doesntexisteither\n\n" |
| 422 |
"2 objects imported automatically:\n\n" |
| 423 |
" import model_forms\n" |
| 424 |
" import shell\n\n" |
| 425 |
) |
| 426 |
self.assertEqual(stdout.getvalue(), expected) |
| 427 |
|
| 428 |
def test_override_get_auto_imports_one_error(self): |
| 429 |
class TestCommand(shell.Command): |
| 430 |
def get_auto_imports(self): |
| 431 |
return [ |
| 432 |
"foo", |
| 433 |
] |
| 434 |
|
| 435 |
expected = ( |
| 436 |
"1 object could not be automatically imported:\n\n foo\n\n" |
| 437 |
"0 objects imported automatically.\n\n" |
| 438 |
) |
| 439 |
for verbosity, expected in [(0, ""), (1, expected), (2, expected)]: |
| 440 |
with self.subTest(verbosity=verbosity): |
| 441 |
with captured_stdout() as stdout: |
| 442 |
TestCommand().get_namespace(verbosity=verbosity) |
| 443 |
self.assertEqual(stdout.getvalue(), expected) |
| 444 |
|
| 445 |
def test_override_get_auto_imports_many_errors(self): |
| 446 |
class TestCommand(shell.Command): |
| 447 |
def get_auto_imports(self): |
| 448 |
return [ |
| 449 |
"does.not.exist", |
| 450 |
"doesntexisteither", |
| 451 |
] |
| 452 |
|
| 453 |
expected = ( |
| 454 |
"2 objects could not be automatically imported:\n\n" |
| 455 |
" does.not.exist\n" |
| 456 |
" doesntexisteither\n\n" |
| 457 |
"0 objects imported automatically.\n\n" |
| 458 |
) |
| 459 |
for verbosity, expected in [(0, ""), (1, expected), (2, expected)]: |
| 460 |
with self.subTest(verbosity=verbosity): |
| 461 |
with captured_stdout() as stdout: |
| 462 |
TestCommand().get_namespace(verbosity=verbosity) |
| 463 |
self.assertEqual(stdout.getvalue(), expected) |