| 1 |
import builtins |
| 2 |
import getpass |
| 3 |
import os |
| 4 |
import sys |
| 5 |
from datetime import date |
| 6 |
from io import StringIO |
| 7 |
from unittest import mock |
| 8 |
|
| 9 |
from django.apps import apps |
| 10 |
from django.contrib.auth import get_permission_codename, management |
| 11 |
from django.contrib.auth.management import create_permissions, get_default_username |
| 12 |
from django.contrib.auth.management.commands import changepassword, createsuperuser |
| 13 |
from django.contrib.auth.models import Group, Permission, User |
| 14 |
from django.contrib.contenttypes.models import ContentType |
| 15 |
from django.core.management import call_command |
| 16 |
from django.core.management.base import CommandError |
| 17 |
from django.db import migrations |
| 18 |
from django.test import TestCase, override_settings |
| 19 |
from django.utils.translation import gettext_lazy as _ |
| 20 |
|
| 21 |
from .models import ( |
| 22 |
CustomUser, |
| 23 |
CustomUserNonUniqueUsername, |
| 24 |
CustomUserWithFK, |
| 25 |
CustomUserWithM2M, |
| 26 |
CustomUserWithUniqueConstraint, |
| 27 |
Email, |
| 28 |
Organization, |
| 29 |
UserProxy, |
| 30 |
) |
| 31 |
|
| 32 |
MOCK_INPUT_KEY_TO_PROMPTS = { |
| 33 |
# @mock_inputs dict key: [expected prompt messages], |
| 34 |
"bypass": ["Bypass password validation and create user anyway? [y/N]: "], |
| 35 |
"email": ["Email address: "], |
| 36 |
"date_of_birth": ["Date of birth: "], |
| 37 |
"first_name": ["First name: "], |
| 38 |
"username": [ |
| 39 |
"Username: ", |
| 40 |
lambda: "Username (leave blank to use '%s'): " % get_default_username(), |
| 41 |
], |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
def mock_inputs(inputs): |
| 46 |
""" |
| 47 |
Decorator to temporarily replace input/getpass to allow interactive |
| 48 |
createsuperuser. |
| 49 |
""" |
| 50 |
|
| 51 |
def inner(test_func): |
| 52 |
def wrapper(*args): |
| 53 |
class mock_getpass: |
| 54 |
@staticmethod |
| 55 |
def getpass(prompt=b"Password: ", stream=None): |
| 56 |
if callable(inputs["password"]): |
| 57 |
return inputs["password"]() |
| 58 |
return inputs["password"] |
| 59 |
|
| 60 |
def mock_input(prompt): |
| 61 |
assert "__proxy__" not in prompt |
| 62 |
response = None |
| 63 |
for key, val in inputs.items(): |
| 64 |
if val == "KeyboardInterrupt": |
| 65 |
raise KeyboardInterrupt |
| 66 |
# get() fallback because sometimes 'key' is the actual |
| 67 |
# prompt rather than a shortcut name. |
| 68 |
prompt_msgs = MOCK_INPUT_KEY_TO_PROMPTS.get(key, key) |
| 69 |
if isinstance(prompt_msgs, list): |
| 70 |
prompt_msgs = [ |
| 71 |
msg() if callable(msg) else msg for msg in prompt_msgs |
| 72 |
] |
| 73 |
if prompt in prompt_msgs: |
| 74 |
if callable(val): |
| 75 |
response = val() |
| 76 |
else: |
| 77 |
response = val |
| 78 |
break |
| 79 |
if response is None: |
| 80 |
raise ValueError("Mock input for %r not found." % prompt) |
| 81 |
return response |
| 82 |
|
| 83 |
old_getpass = createsuperuser.getpass |
| 84 |
old_input = builtins.input |
| 85 |
createsuperuser.getpass = mock_getpass |
| 86 |
builtins.input = mock_input |
| 87 |
try: |
| 88 |
test_func(*args) |
| 89 |
finally: |
| 90 |
createsuperuser.getpass = old_getpass |
| 91 |
builtins.input = old_input |
| 92 |
|
| 93 |
return wrapper |
| 94 |
|
| 95 |
return inner |
| 96 |
|
| 97 |
|
| 98 |
class MockTTY: |
| 99 |
""" |
| 100 |
A fake stdin object that pretends to be a TTY to be used in conjunction |
| 101 |
with mock_inputs. |
| 102 |
""" |
| 103 |
|
| 104 |
def isatty(self): |
| 105 |
return True |
| 106 |
|
| 107 |
|
| 108 |
class MockInputTests(TestCase): |
| 109 |
@mock_inputs({"username": "alice"}) |
| 110 |
def test_input_not_found(self): |
| 111 |
with self.assertRaisesMessage( |
| 112 |
ValueError, "Mock input for 'Email address: ' not found." |
| 113 |
): |
| 114 |
call_command("createsuperuser", stdin=MockTTY()) |
| 115 |
|
| 116 |
|
| 117 |
class GetDefaultUsernameTestCase(TestCase): |
| 118 |
databases = {"default", "other"} |
| 119 |
|
| 120 |
def setUp(self): |
| 121 |
self.old_get_system_username = management.get_system_username |
| 122 |
|
| 123 |
def tearDown(self): |
| 124 |
management.get_system_username = self.old_get_system_username |
| 125 |
|
| 126 |
def test_actual_implementation(self): |
| 127 |
self.assertIsInstance(management.get_system_username(), str) |
| 128 |
|
| 129 |
def test_getuser_raises_exception(self): |
| 130 |
# TODO: Drop ImportError and KeyError when dropping support for PY312. |
| 131 |
for exc in (ImportError, KeyError, OSError): |
| 132 |
with self.subTest(exc=str(exc)): |
| 133 |
with mock.patch("getpass.getuser", side_effect=exc): |
| 134 |
self.assertEqual(management.get_system_username(), "") |
| 135 |
|
| 136 |
def test_simple(self): |
| 137 |
management.get_system_username = lambda: "joe" |
| 138 |
self.assertEqual(management.get_default_username(), "joe") |
| 139 |
|
| 140 |
def test_existing(self): |
| 141 |
User.objects.create(username="joe") |
| 142 |
management.get_system_username = lambda: "joe" |
| 143 |
self.assertEqual(management.get_default_username(), "") |
| 144 |
self.assertEqual(management.get_default_username(check_db=False), "joe") |
| 145 |
|
| 146 |
def test_i18n(self): |
| 147 |
# 'Julia' with accented 'u': |
| 148 |
management.get_system_username = lambda: "J\xfalia" |
| 149 |
self.assertEqual(management.get_default_username(), "julia") |
| 150 |
|
| 151 |
def test_with_database(self): |
| 152 |
User.objects.create(username="joe") |
| 153 |
management.get_system_username = lambda: "joe" |
| 154 |
self.assertEqual(management.get_default_username(), "") |
| 155 |
self.assertEqual(management.get_default_username(database="other"), "joe") |
| 156 |
|
| 157 |
User.objects.using("other").create(username="joe") |
| 158 |
self.assertEqual(management.get_default_username(database="other"), "") |
| 159 |
|
| 160 |
|
| 161 |
@override_settings( |
| 162 |
AUTH_PASSWORD_VALIDATORS=[ |
| 163 |
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, |
| 164 |
] |
| 165 |
) |
| 166 |
class ChangepasswordManagementCommandTestCase(TestCase): |
| 167 |
@classmethod |
| 168 |
def setUpTestData(cls): |
| 169 |
cls.user = User.objects.create_user(username="joe", password="qwerty") |
| 170 |
|
| 171 |
def setUp(self): |
| 172 |
self.stdout = StringIO() |
| 173 |
self.addCleanup(self.stdout.close) |
| 174 |
self.stderr = StringIO() |
| 175 |
self.addCleanup(self.stderr.close) |
| 176 |
|
| 177 |
@mock.patch.object(getpass, "getpass", return_value="password") |
| 178 |
def test_get_pass(self, mock_get_pass): |
| 179 |
call_command("changepassword", username="joe", stdout=self.stdout) |
| 180 |
self.assertIs(User.objects.get(username="joe").check_password("password"), True) |
| 181 |
|
| 182 |
@mock.patch.object(getpass, "getpass", return_value="") |
| 183 |
def test_get_pass_no_input(self, mock_get_pass): |
| 184 |
with self.assertRaisesMessage(CommandError, "aborted"): |
| 185 |
call_command("changepassword", username="joe", stdout=self.stdout) |
| 186 |
|
| 187 |
@mock.patch.object(changepassword.Command, "_get_pass", return_value="new_password") |
| 188 |
def test_system_username(self, mock_get_pass): |
| 189 |
"""The system username is used if --username isn't provided.""" |
| 190 |
username = getpass.getuser() |
| 191 |
User.objects.create_user(username=username, password="qwerty") |
| 192 |
call_command("changepassword", stdout=self.stdout) |
| 193 |
self.assertIs( |
| 194 |
User.objects.get(username=username).check_password("new_password"), True |
| 195 |
) |
| 196 |
|
| 197 |
def test_nonexistent_username(self): |
| 198 |
with self.assertRaisesMessage(CommandError, "user 'test' does not exist"): |
| 199 |
call_command("changepassword", username="test", stdout=self.stdout) |
| 200 |
|
| 201 |
@mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") |
| 202 |
def test_that_changepassword_command_changes_joes_password(self, mock_get_pass): |
| 203 |
"Executing the changepassword management command should change joe's password" |
| 204 |
self.assertTrue(self.user.check_password("qwerty")) |
| 205 |
|
| 206 |
call_command("changepassword", username="joe", stdout=self.stdout) |
| 207 |
command_output = self.stdout.getvalue().strip() |
| 208 |
|
| 209 |
self.assertEqual( |
| 210 |
command_output, |
| 211 |
"Changing password for user 'joe'\n" |
| 212 |
"Password changed successfully for user 'joe'", |
| 213 |
) |
| 214 |
self.assertTrue(User.objects.get(username="joe").check_password("not qwerty")) |
| 215 |
|
| 216 |
@mock.patch.object( |
| 217 |
changepassword.Command, "_get_pass", side_effect=lambda *args: str(args) |
| 218 |
) |
| 219 |
def test_that_max_tries_exits_1(self, mock_get_pass): |
| 220 |
""" |
| 221 |
A CommandError should be thrown by handle() if the user enters in |
| 222 |
mismatched passwords three times. |
| 223 |
""" |
| 224 |
msg = "Aborting password change for user 'joe' after 3 attempts" |
| 225 |
with self.assertRaisesMessage(CommandError, msg): |
| 226 |
call_command( |
| 227 |
"changepassword", username="joe", stdout=self.stdout, stderr=self.stderr |
| 228 |
) |
| 229 |
|
| 230 |
@mock.patch.object(changepassword.Command, "_get_pass", return_value="1234567890") |
| 231 |
def test_password_validation(self, mock_get_pass): |
| 232 |
""" |
| 233 |
A CommandError should be raised if the user enters in passwords which |
| 234 |
fail validation three times. |
| 235 |
""" |
| 236 |
abort_msg = "Aborting password change for user 'joe' after 3 attempts" |
| 237 |
with self.assertRaisesMessage(CommandError, abort_msg): |
| 238 |
call_command( |
| 239 |
"changepassword", username="joe", stdout=self.stdout, stderr=self.stderr |
| 240 |
) |
| 241 |
self.assertIn("This password is entirely numeric.", self.stderr.getvalue()) |
| 242 |
|
| 243 |
@mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") |
| 244 |
def test_that_changepassword_command_works_with_nonascii_output( |
| 245 |
self, mock_get_pass |
| 246 |
): |
| 247 |
""" |
| 248 |
#21627 -- Executing the changepassword management command should allow |
| 249 |
non-ASCII characters from the User object representation. |
| 250 |
""" |
| 251 |
# 'Julia' with accented 'u': |
| 252 |
User.objects.create_user(username="J\xfalia", password="qwerty") |
| 253 |
call_command("changepassword", username="J\xfalia", stdout=self.stdout) |
| 254 |
|
| 255 |
|
| 256 |
class MultiDBChangepasswordManagementCommandTestCase(TestCase): |
| 257 |
databases = {"default", "other"} |
| 258 |
|
| 259 |
@mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") |
| 260 |
def test_that_changepassword_command_with_database_option_uses_given_db( |
| 261 |
self, mock_get_pass |
| 262 |
): |
| 263 |
""" |
| 264 |
changepassword --database should operate on the specified DB. |
| 265 |
""" |
| 266 |
user = User.objects.db_manager("other").create_user( |
| 267 |
username="joe", password="qwerty" |
| 268 |
) |
| 269 |
self.assertTrue(user.check_password("qwerty")) |
| 270 |
|
| 271 |
out = StringIO() |
| 272 |
call_command("changepassword", username="joe", database="other", stdout=out) |
| 273 |
command_output = out.getvalue().strip() |
| 274 |
|
| 275 |
self.assertEqual( |
| 276 |
command_output, |
| 277 |
"Changing password for user 'joe'\n" |
| 278 |
"Password changed successfully for user 'joe'", |
| 279 |
) |
| 280 |
self.assertTrue( |
| 281 |
User.objects.using("other").get(username="joe").check_password("not qwerty") |
| 282 |
) |
| 283 |
|
| 284 |
|
| 285 |
@override_settings( |
| 286 |
SILENCED_SYSTEM_CHECKS=["fields.W342"], # ForeignKey(unique=True) |
| 287 |
AUTH_PASSWORD_VALIDATORS=[ |
| 288 |
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"} |
| 289 |
], |
| 290 |
) |
| 291 |
class CreatesuperuserManagementCommandTestCase(TestCase): |
| 292 |
def test_no_email_argument(self): |
| 293 |
new_io = StringIO() |
| 294 |
with self.assertRaisesMessage( |
| 295 |
CommandError, "You must use --email with --noinput." |
| 296 |
): |
| 297 |
call_command( |
| 298 |
"createsuperuser", interactive=False, username="joe", stdout=new_io |
| 299 |
) |
| 300 |
|
| 301 |
def test_basic_usage(self): |
| 302 |
"Check the operation of the createsuperuser management command" |
| 303 |
# We can use the management command to create a superuser |
| 304 |
new_io = StringIO() |
| 305 |
call_command( |
| 306 |
"createsuperuser", |
| 307 |
interactive=False, |
| 308 |
username="joe", |
| 309 |
email="[email protected]", |
| 310 |
stdout=new_io, |
| 311 |
) |
| 312 |
command_output = new_io.getvalue().strip() |
| 313 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 314 |
u = User.objects.get(username="joe") |
| 315 |
self.assertEqual(u.email, "[email protected]") |
| 316 |
|
| 317 |
# created password should be unusable |
| 318 |
self.assertFalse(u.has_usable_password()) |
| 319 |
|
| 320 |
def test_validate_username(self): |
| 321 |
msg = ( |
| 322 |
"Enter a valid username. This value may contain only letters, numbers, " |
| 323 |
"and @/./+/-/_ characters." |
| 324 |
) |
| 325 |
with self.assertRaisesMessage(CommandError, msg): |
| 326 |
call_command( |
| 327 |
"createsuperuser", |
| 328 |
interactive=False, |
| 329 |
username="🤠", |
| 330 |
email="[email protected]", |
| 331 |
) |
| 332 |
|
| 333 |
def test_non_ascii_verbose_name(self): |
| 334 |
@mock_inputs( |
| 335 |
{ |
| 336 |
"password": "nopasswd", |
| 337 |
"Uživatel (leave blank to use '%s'): " |
| 338 |
% get_default_username(): "foo", # username (cz) |
| 339 |
"email": "[email protected]", |
| 340 |
} |
| 341 |
) |
| 342 |
def test(self): |
| 343 |
username_field = User._meta.get_field("username") |
| 344 |
old_verbose_name = username_field.verbose_name |
| 345 |
username_field.verbose_name = _("u\u017eivatel") |
| 346 |
new_io = StringIO() |
| 347 |
try: |
| 348 |
call_command( |
| 349 |
"createsuperuser", |
| 350 |
interactive=True, |
| 351 |
stdout=new_io, |
| 352 |
stdin=MockTTY(), |
| 353 |
) |
| 354 |
finally: |
| 355 |
username_field.verbose_name = old_verbose_name |
| 356 |
|
| 357 |
command_output = new_io.getvalue().strip() |
| 358 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 359 |
|
| 360 |
test(self) |
| 361 |
|
| 362 |
def test_verbosity_zero(self): |
| 363 |
# We can suppress output on the management command |
| 364 |
new_io = StringIO() |
| 365 |
call_command( |
| 366 |
"createsuperuser", |
| 367 |
interactive=False, |
| 368 |
username="joe2", |
| 369 |
email="[email protected]", |
| 370 |
verbosity=0, |
| 371 |
stdout=new_io, |
| 372 |
) |
| 373 |
command_output = new_io.getvalue().strip() |
| 374 |
self.assertEqual(command_output, "") |
| 375 |
u = User.objects.get(username="joe2") |
| 376 |
self.assertEqual(u.email, "[email protected]") |
| 377 |
self.assertFalse(u.has_usable_password()) |
| 378 |
|
| 379 |
def test_email_in_username(self): |
| 380 |
call_command( |
| 381 |
"createsuperuser", |
| 382 |
interactive=False, |
| 383 |
username="[email protected]", |
| 384 |
email="[email protected]", |
| 385 |
verbosity=0, |
| 386 |
) |
| 387 |
u = User._default_manager.get(username="[email protected]") |
| 388 |
self.assertEqual(u.email, "[email protected]") |
| 389 |
self.assertFalse(u.has_usable_password()) |
| 390 |
|
| 391 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") |
| 392 |
def test_swappable_user(self): |
| 393 |
"A superuser can be created when a custom user model is in use" |
| 394 |
# We can use the management command to create a superuser |
| 395 |
# We skip validation because the temporary substitution of the |
| 396 |
# swappable User model messes with validation. |
| 397 |
new_io = StringIO() |
| 398 |
call_command( |
| 399 |
"createsuperuser", |
| 400 |
interactive=False, |
| 401 |
email="[email protected]", |
| 402 |
date_of_birth="1976-04-01", |
| 403 |
first_name="Joe", |
| 404 |
stdout=new_io, |
| 405 |
) |
| 406 |
command_output = new_io.getvalue().strip() |
| 407 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 408 |
u = CustomUser._default_manager.get(email="[email protected]") |
| 409 |
self.assertEqual(u.date_of_birth, date(1976, 4, 1)) |
| 410 |
|
| 411 |
# created password should be unusable |
| 412 |
self.assertFalse(u.has_usable_password()) |
| 413 |
|
| 414 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") |
| 415 |
def test_swappable_user_missing_required_field(self): |
| 416 |
"A Custom superuser won't be created when a required field isn't provided" |
| 417 |
# We can use the management command to create a superuser |
| 418 |
# We skip validation because the temporary substitution of the |
| 419 |
# swappable User model messes with validation. |
| 420 |
new_io = StringIO() |
| 421 |
with self.assertRaisesMessage( |
| 422 |
CommandError, "You must use --email with --noinput." |
| 423 |
): |
| 424 |
call_command( |
| 425 |
"createsuperuser", |
| 426 |
interactive=False, |
| 427 |
stdout=new_io, |
| 428 |
stderr=new_io, |
| 429 |
) |
| 430 |
|
| 431 |
self.assertEqual(CustomUser._default_manager.count(), 0) |
| 432 |
|
| 433 |
@override_settings( |
| 434 |
AUTH_USER_MODEL="auth_tests.CustomUserNonUniqueUsername", |
| 435 |
AUTHENTICATION_BACKENDS=["my.custom.backend"], |
| 436 |
) |
| 437 |
def test_swappable_user_username_non_unique(self): |
| 438 |
@mock_inputs( |
| 439 |
{ |
| 440 |
"username": "joe", |
| 441 |
"password": "nopasswd", |
| 442 |
} |
| 443 |
) |
| 444 |
def createsuperuser(): |
| 445 |
new_io = StringIO() |
| 446 |
call_command( |
| 447 |
"createsuperuser", |
| 448 |
interactive=True, |
| 449 |
email="[email protected]", |
| 450 |
stdout=new_io, |
| 451 |
stdin=MockTTY(), |
| 452 |
) |
| 453 |
command_output = new_io.getvalue().strip() |
| 454 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 455 |
|
| 456 |
for i in range(2): |
| 457 |
createsuperuser() |
| 458 |
|
| 459 |
users = CustomUserNonUniqueUsername.objects.filter(username="joe") |
| 460 |
self.assertEqual(users.count(), 2) |
| 461 |
|
| 462 |
def test_skip_if_not_in_TTY(self): |
| 463 |
""" |
| 464 |
If the command is not called from a TTY, it should be skipped and a |
| 465 |
message should be displayed (#7423). |
| 466 |
""" |
| 467 |
|
| 468 |
class FakeStdin: |
| 469 |
"""A fake stdin object that has isatty() return False.""" |
| 470 |
|
| 471 |
def isatty(self): |
| 472 |
return False |
| 473 |
|
| 474 |
out = StringIO() |
| 475 |
call_command( |
| 476 |
"createsuperuser", |
| 477 |
stdin=FakeStdin(), |
| 478 |
stdout=out, |
| 479 |
interactive=True, |
| 480 |
) |
| 481 |
|
| 482 |
self.assertEqual(User._default_manager.count(), 0) |
| 483 |
self.assertIn("Superuser creation skipped", out.getvalue()) |
| 484 |
|
| 485 |
def test_passing_stdin(self): |
| 486 |
""" |
| 487 |
You can pass a stdin object as an option and it should be |
| 488 |
available on self.stdin. |
| 489 |
If no such option is passed, it defaults to sys.stdin. |
| 490 |
""" |
| 491 |
sentinel = object() |
| 492 |
command = createsuperuser.Command() |
| 493 |
call_command( |
| 494 |
command, |
| 495 |
stdin=sentinel, |
| 496 |
interactive=False, |
| 497 |
verbosity=0, |
| 498 |
username="janet", |
| 499 |
email="[email protected]", |
| 500 |
) |
| 501 |
self.assertIs(command.stdin, sentinel) |
| 502 |
|
| 503 |
command = createsuperuser.Command() |
| 504 |
call_command( |
| 505 |
command, |
| 506 |
interactive=False, |
| 507 |
verbosity=0, |
| 508 |
username="joe", |
| 509 |
email="[email protected]", |
| 510 |
) |
| 511 |
self.assertIs(command.stdin, sys.stdin) |
| 512 |
|
| 513 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") |
| 514 |
def test_fields_with_fk(self): |
| 515 |
new_io = StringIO() |
| 516 |
group = Group.objects.create(name="mygroup") |
| 517 |
email = Email.objects.create(email="[email protected]") |
| 518 |
call_command( |
| 519 |
"createsuperuser", |
| 520 |
interactive=False, |
| 521 |
username=email.pk, |
| 522 |
email=email.email, |
| 523 |
group=group.pk, |
| 524 |
stdout=new_io, |
| 525 |
) |
| 526 |
command_output = new_io.getvalue().strip() |
| 527 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 528 |
u = CustomUserWithFK._default_manager.get(email=email) |
| 529 |
self.assertEqual(u.username, email) |
| 530 |
self.assertEqual(u.group, group) |
| 531 |
|
| 532 |
non_existent_email = "[email protected]" |
| 533 |
msg = "email instance with email %r is not a valid choice." % non_existent_email |
| 534 |
with self.assertRaisesMessage(CommandError, msg): |
| 535 |
call_command( |
| 536 |
"createsuperuser", |
| 537 |
interactive=False, |
| 538 |
username=email.pk, |
| 539 |
email=non_existent_email, |
| 540 |
stdout=new_io, |
| 541 |
) |
| 542 |
|
| 543 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") |
| 544 |
def test_fields_with_fk_interactive(self): |
| 545 |
new_io = StringIO() |
| 546 |
group = Group.objects.create(name="mygroup") |
| 547 |
email = Email.objects.create(email="[email protected]") |
| 548 |
|
| 549 |
@mock_inputs( |
| 550 |
{ |
| 551 |
"password": "nopasswd", |
| 552 |
"Username (Email.id): ": email.pk, |
| 553 |
"Email (Email.email): ": email.email, |
| 554 |
"Group (Group.id): ": group.pk, |
| 555 |
} |
| 556 |
) |
| 557 |
def test(self): |
| 558 |
call_command( |
| 559 |
"createsuperuser", |
| 560 |
interactive=True, |
| 561 |
stdout=new_io, |
| 562 |
stdin=MockTTY(), |
| 563 |
) |
| 564 |
|
| 565 |
command_output = new_io.getvalue().strip() |
| 566 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 567 |
u = CustomUserWithFK._default_manager.get(email=email) |
| 568 |
self.assertEqual(u.username, email) |
| 569 |
self.assertEqual(u.group, group) |
| 570 |
|
| 571 |
test(self) |
| 572 |
|
| 573 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") |
| 574 |
def test_fields_with_fk_via_option_interactive(self): |
| 575 |
new_io = StringIO() |
| 576 |
group = Group.objects.create(name="mygroup") |
| 577 |
email = Email.objects.create(email="[email protected]") |
| 578 |
|
| 579 |
@mock_inputs({"password": "nopasswd"}) |
| 580 |
def test(self): |
| 581 |
call_command( |
| 582 |
"createsuperuser", |
| 583 |
interactive=True, |
| 584 |
username=email.pk, |
| 585 |
email=email.email, |
| 586 |
group=group.pk, |
| 587 |
stdout=new_io, |
| 588 |
stdin=MockTTY(), |
| 589 |
) |
| 590 |
|
| 591 |
command_output = new_io.getvalue().strip() |
| 592 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 593 |
u = CustomUserWithFK._default_manager.get(email=email) |
| 594 |
self.assertEqual(u.username, email) |
| 595 |
self.assertEqual(u.group, group) |
| 596 |
|
| 597 |
test(self) |
| 598 |
|
| 599 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") |
| 600 |
def test_validate_fk(self): |
| 601 |
email = Email.objects.create(email="[email protected]") |
| 602 |
Group.objects.all().delete() |
| 603 |
nonexistent_group_id = 1 |
| 604 |
msg = f"group instance with id {nonexistent_group_id} is not a valid choice." |
| 605 |
|
| 606 |
with self.assertRaisesMessage(CommandError, msg): |
| 607 |
call_command( |
| 608 |
"createsuperuser", |
| 609 |
interactive=False, |
| 610 |
username=email.pk, |
| 611 |
email=email.email, |
| 612 |
group=nonexistent_group_id, |
| 613 |
verbosity=0, |
| 614 |
) |
| 615 |
|
| 616 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") |
| 617 |
def test_validate_fk_environment_variable(self): |
| 618 |
email = Email.objects.create(email="[email protected]") |
| 619 |
Group.objects.all().delete() |
| 620 |
nonexistent_group_id = 1 |
| 621 |
msg = f"group instance with id {nonexistent_group_id} is not a valid choice." |
| 622 |
|
| 623 |
with mock.patch.dict( |
| 624 |
os.environ, |
| 625 |
{"DJANGO_SUPERUSER_GROUP": str(nonexistent_group_id)}, |
| 626 |
): |
| 627 |
with self.assertRaisesMessage(CommandError, msg): |
| 628 |
call_command( |
| 629 |
"createsuperuser", |
| 630 |
interactive=False, |
| 631 |
username=email.pk, |
| 632 |
email=email.email, |
| 633 |
verbosity=0, |
| 634 |
) |
| 635 |
|
| 636 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") |
| 637 |
def test_validate_fk_via_option_interactive(self): |
| 638 |
email = Email.objects.create(email="[email protected]") |
| 639 |
Group.objects.all().delete() |
| 640 |
nonexistent_group_id = 1 |
| 641 |
msg = f"group instance with id {nonexistent_group_id} is not a valid choice." |
| 642 |
|
| 643 |
@mock_inputs( |
| 644 |
{ |
| 645 |
"password": "nopasswd", |
| 646 |
"Username (Email.id): ": email.pk, |
| 647 |
"Email (Email.email): ": email.email, |
| 648 |
} |
| 649 |
) |
| 650 |
def test(self): |
| 651 |
with self.assertRaisesMessage(CommandError, msg): |
| 652 |
call_command( |
| 653 |
"createsuperuser", |
| 654 |
group=nonexistent_group_id, |
| 655 |
stdin=MockTTY(), |
| 656 |
verbosity=0, |
| 657 |
) |
| 658 |
|
| 659 |
test(self) |
| 660 |
|
| 661 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2m") |
| 662 |
def test_fields_with_m2m(self): |
| 663 |
new_io = StringIO() |
| 664 |
org_id_1 = Organization.objects.create(name="Organization 1").pk |
| 665 |
org_id_2 = Organization.objects.create(name="Organization 2").pk |
| 666 |
call_command( |
| 667 |
"createsuperuser", |
| 668 |
interactive=False, |
| 669 |
username="joe", |
| 670 |
orgs=[org_id_1, org_id_2], |
| 671 |
stdout=new_io, |
| 672 |
) |
| 673 |
command_output = new_io.getvalue().strip() |
| 674 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 675 |
user = CustomUserWithM2M._default_manager.get(username="joe") |
| 676 |
self.assertEqual(user.orgs.count(), 2) |
| 677 |
|
| 678 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2M") |
| 679 |
def test_fields_with_m2m_interactive(self): |
| 680 |
new_io = StringIO() |
| 681 |
org_id_1 = Organization.objects.create(name="Organization 1").pk |
| 682 |
org_id_2 = Organization.objects.create(name="Organization 2").pk |
| 683 |
|
| 684 |
@mock_inputs( |
| 685 |
{ |
| 686 |
"password": "nopasswd", |
| 687 |
"Username: ": "joe", |
| 688 |
"Orgs (Organization.id): ": "%s, %s" % (org_id_1, org_id_2), |
| 689 |
} |
| 690 |
) |
| 691 |
def test(self): |
| 692 |
call_command( |
| 693 |
"createsuperuser", |
| 694 |
interactive=True, |
| 695 |
stdout=new_io, |
| 696 |
stdin=MockTTY(), |
| 697 |
) |
| 698 |
command_output = new_io.getvalue().strip() |
| 699 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 700 |
user = CustomUserWithM2M._default_manager.get(username="joe") |
| 701 |
self.assertEqual(user.orgs.count(), 2) |
| 702 |
|
| 703 |
test(self) |
| 704 |
|
| 705 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2M") |
| 706 |
def test_fields_with_m2m_interactive_blank(self): |
| 707 |
new_io = StringIO() |
| 708 |
org_id = Organization.objects.create(name="Organization").pk |
| 709 |
entered_orgs = [str(org_id), " "] |
| 710 |
|
| 711 |
def return_orgs(): |
| 712 |
return entered_orgs.pop() |
| 713 |
|
| 714 |
@mock_inputs( |
| 715 |
{ |
| 716 |
"password": "nopasswd", |
| 717 |
"Username: ": "joe", |
| 718 |
"Orgs (Organization.id): ": return_orgs, |
| 719 |
} |
| 720 |
) |
| 721 |
def test(self): |
| 722 |
call_command( |
| 723 |
"createsuperuser", |
| 724 |
interactive=True, |
| 725 |
stdout=new_io, |
| 726 |
stderr=new_io, |
| 727 |
stdin=MockTTY(), |
| 728 |
) |
| 729 |
self.assertEqual( |
| 730 |
new_io.getvalue().strip(), |
| 731 |
"Error: This field cannot be blank.\n" |
| 732 |
"Superuser created successfully.", |
| 733 |
) |
| 734 |
|
| 735 |
test(self) |
| 736 |
|
| 737 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2MThrough") |
| 738 |
def test_fields_with_m2m_and_through(self): |
| 739 |
msg = ( |
| 740 |
"Required field 'orgs' specifies a many-to-many relation through " |
| 741 |
"model, which is not supported." |
| 742 |
) |
| 743 |
with self.assertRaisesMessage(CommandError, msg): |
| 744 |
call_command("createsuperuser") |
| 745 |
|
| 746 |
def test_default_username(self): |
| 747 |
"""createsuperuser uses a default username when one isn't provided.""" |
| 748 |
# Get the default username before creating a user. |
| 749 |
default_username = get_default_username() |
| 750 |
new_io = StringIO() |
| 751 |
entered_passwords = ["password", "password"] |
| 752 |
|
| 753 |
def return_passwords(): |
| 754 |
return entered_passwords.pop(0) |
| 755 |
|
| 756 |
@mock_inputs({"password": return_passwords, "username": "", "email": ""}) |
| 757 |
def test(self): |
| 758 |
call_command( |
| 759 |
"createsuperuser", |
| 760 |
interactive=True, |
| 761 |
stdin=MockTTY(), |
| 762 |
stdout=new_io, |
| 763 |
stderr=new_io, |
| 764 |
) |
| 765 |
self.assertEqual( |
| 766 |
new_io.getvalue().strip(), "Superuser created successfully." |
| 767 |
) |
| 768 |
self.assertTrue(User.objects.filter(username=default_username).exists()) |
| 769 |
|
| 770 |
test(self) |
| 771 |
|
| 772 |
def test_password_validation(self): |
| 773 |
""" |
| 774 |
Creation should fail if the password fails validation. |
| 775 |
""" |
| 776 |
new_io = StringIO() |
| 777 |
entered_passwords = ["1234567890", "1234567890", "password", "password"] |
| 778 |
|
| 779 |
def bad_then_good_password(): |
| 780 |
return entered_passwords.pop(0) |
| 781 |
|
| 782 |
@mock_inputs( |
| 783 |
{ |
| 784 |
"password": bad_then_good_password, |
| 785 |
"username": "joe1234567890", |
| 786 |
"email": "", |
| 787 |
"bypass": "n", |
| 788 |
} |
| 789 |
) |
| 790 |
def test(self): |
| 791 |
call_command( |
| 792 |
"createsuperuser", |
| 793 |
interactive=True, |
| 794 |
stdin=MockTTY(), |
| 795 |
stdout=new_io, |
| 796 |
stderr=new_io, |
| 797 |
) |
| 798 |
self.assertEqual( |
| 799 |
new_io.getvalue().strip(), |
| 800 |
"This password is entirely numeric.\n" |
| 801 |
"Superuser created successfully.", |
| 802 |
) |
| 803 |
|
| 804 |
test(self) |
| 805 |
|
| 806 |
@override_settings( |
| 807 |
AUTH_PASSWORD_VALIDATORS=[ |
| 808 |
{ |
| 809 |
"NAME": ( |
| 810 |
"django.contrib.auth.password_validation." |
| 811 |
"UserAttributeSimilarityValidator" |
| 812 |
) |
| 813 |
}, |
| 814 |
] |
| 815 |
) |
| 816 |
def test_validate_password_against_username(self): |
| 817 |
new_io = StringIO() |
| 818 |
username = "supremelycomplex" |
| 819 |
entered_passwords = [ |
| 820 |
username, |
| 821 |
username, |
| 822 |
"superduperunguessablepassword", |
| 823 |
"superduperunguessablepassword", |
| 824 |
] |
| 825 |
|
| 826 |
def bad_then_good_password(): |
| 827 |
return entered_passwords.pop(0) |
| 828 |
|
| 829 |
@mock_inputs( |
| 830 |
{ |
| 831 |
"password": bad_then_good_password, |
| 832 |
"username": username, |
| 833 |
"email": "", |
| 834 |
"bypass": "n", |
| 835 |
} |
| 836 |
) |
| 837 |
def test(self): |
| 838 |
call_command( |
| 839 |
"createsuperuser", |
| 840 |
interactive=True, |
| 841 |
stdin=MockTTY(), |
| 842 |
stdout=new_io, |
| 843 |
stderr=new_io, |
| 844 |
) |
| 845 |
self.assertEqual( |
| 846 |
new_io.getvalue().strip(), |
| 847 |
"The password is too similar to the username.\n" |
| 848 |
"Superuser created successfully.", |
| 849 |
) |
| 850 |
|
| 851 |
test(self) |
| 852 |
|
| 853 |
@override_settings( |
| 854 |
AUTH_USER_MODEL="auth_tests.CustomUser", |
| 855 |
AUTH_PASSWORD_VALIDATORS=[ |
| 856 |
{ |
| 857 |
"NAME": ( |
| 858 |
"django.contrib.auth.password_validation." |
| 859 |
"UserAttributeSimilarityValidator" |
| 860 |
) |
| 861 |
}, |
| 862 |
], |
| 863 |
) |
| 864 |
def test_validate_password_against_required_fields(self): |
| 865 |
new_io = StringIO() |
| 866 |
first_name = "josephine" |
| 867 |
entered_passwords = [ |
| 868 |
first_name, |
| 869 |
first_name, |
| 870 |
"superduperunguessablepassword", |
| 871 |
"superduperunguessablepassword", |
| 872 |
] |
| 873 |
|
| 874 |
def bad_then_good_password(): |
| 875 |
return entered_passwords.pop(0) |
| 876 |
|
| 877 |
@mock_inputs( |
| 878 |
{ |
| 879 |
"password": bad_then_good_password, |
| 880 |
"username": "whatever", |
| 881 |
"first_name": first_name, |
| 882 |
"date_of_birth": "1970-01-01", |
| 883 |
"email": "[email protected]", |
| 884 |
"bypass": "n", |
| 885 |
} |
| 886 |
) |
| 887 |
def test(self): |
| 888 |
call_command( |
| 889 |
"createsuperuser", |
| 890 |
interactive=True, |
| 891 |
stdin=MockTTY(), |
| 892 |
stdout=new_io, |
| 893 |
stderr=new_io, |
| 894 |
) |
| 895 |
self.assertEqual( |
| 896 |
new_io.getvalue().strip(), |
| 897 |
"The password is too similar to the first name.\n" |
| 898 |
"Superuser created successfully.", |
| 899 |
) |
| 900 |
|
| 901 |
test(self) |
| 902 |
|
| 903 |
@override_settings( |
| 904 |
AUTH_USER_MODEL="auth_tests.CustomUser", |
| 905 |
AUTH_PASSWORD_VALIDATORS=[ |
| 906 |
{ |
| 907 |
"NAME": ( |
| 908 |
"django.contrib.auth.password_validation." |
| 909 |
"UserAttributeSimilarityValidator" |
| 910 |
) |
| 911 |
}, |
| 912 |
], |
| 913 |
) |
| 914 |
def test_validate_password_against_required_fields_via_option(self): |
| 915 |
new_io = StringIO() |
| 916 |
first_name = "josephine" |
| 917 |
entered_passwords = [ |
| 918 |
first_name, |
| 919 |
first_name, |
| 920 |
"superduperunguessablepassword", |
| 921 |
"superduperunguessablepassword", |
| 922 |
] |
| 923 |
|
| 924 |
def bad_then_good_password(): |
| 925 |
return entered_passwords.pop(0) |
| 926 |
|
| 927 |
@mock_inputs( |
| 928 |
{ |
| 929 |
"password": bad_then_good_password, |
| 930 |
"bypass": "n", |
| 931 |
} |
| 932 |
) |
| 933 |
def test(self): |
| 934 |
call_command( |
| 935 |
"createsuperuser", |
| 936 |
interactive=True, |
| 937 |
first_name=first_name, |
| 938 |
date_of_birth="1970-01-01", |
| 939 |
email="[email protected]", |
| 940 |
stdin=MockTTY(), |
| 941 |
stdout=new_io, |
| 942 |
stderr=new_io, |
| 943 |
) |
| 944 |
self.assertEqual( |
| 945 |
new_io.getvalue().strip(), |
| 946 |
"The password is too similar to the first name.\n" |
| 947 |
"Superuser created successfully.", |
| 948 |
) |
| 949 |
|
| 950 |
test(self) |
| 951 |
|
| 952 |
def test_blank_username(self): |
| 953 |
"""Creation fails if --username is blank.""" |
| 954 |
new_io = StringIO() |
| 955 |
with self.assertRaisesMessage(CommandError, "Username cannot be blank."): |
| 956 |
call_command( |
| 957 |
"createsuperuser", |
| 958 |
username="", |
| 959 |
stdin=MockTTY(), |
| 960 |
stdout=new_io, |
| 961 |
stderr=new_io, |
| 962 |
) |
| 963 |
|
| 964 |
def test_blank_username_non_interactive(self): |
| 965 |
new_io = StringIO() |
| 966 |
with self.assertRaisesMessage(CommandError, "Username cannot be blank."): |
| 967 |
call_command( |
| 968 |
"createsuperuser", |
| 969 |
username="", |
| 970 |
interactive=False, |
| 971 |
stdin=MockTTY(), |
| 972 |
stdout=new_io, |
| 973 |
stderr=new_io, |
| 974 |
) |
| 975 |
|
| 976 |
def test_blank_email_allowed_non_interactive(self): |
| 977 |
new_io = StringIO() |
| 978 |
|
| 979 |
call_command( |
| 980 |
"createsuperuser", |
| 981 |
email="", |
| 982 |
username="joe", |
| 983 |
interactive=False, |
| 984 |
stdout=new_io, |
| 985 |
stderr=new_io, |
| 986 |
) |
| 987 |
self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") |
| 988 |
u = User.objects.get(username="joe") |
| 989 |
self.assertEqual(u.email, "") |
| 990 |
|
| 991 |
@mock.patch.dict(os.environ, {"DJANGO_SUPERUSER_EMAIL": ""}) |
| 992 |
def test_blank_email_allowed_non_interactive_environment_variable(self): |
| 993 |
new_io = StringIO() |
| 994 |
|
| 995 |
call_command( |
| 996 |
"createsuperuser", |
| 997 |
username="joe", |
| 998 |
interactive=False, |
| 999 |
stdout=new_io, |
| 1000 |
stderr=new_io, |
| 1001 |
) |
| 1002 |
self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") |
| 1003 |
u = User.objects.get(username="joe") |
| 1004 |
self.assertEqual(u.email, "") |
| 1005 |
|
| 1006 |
def test_password_validation_bypass(self): |
| 1007 |
""" |
| 1008 |
Password validation can be bypassed by entering 'y' at the prompt. |
| 1009 |
""" |
| 1010 |
new_io = StringIO() |
| 1011 |
|
| 1012 |
@mock_inputs( |
| 1013 |
{ |
| 1014 |
"password": "1234567890", |
| 1015 |
"username": "joe1234567890", |
| 1016 |
"email": "", |
| 1017 |
"bypass": "y", |
| 1018 |
} |
| 1019 |
) |
| 1020 |
def test(self): |
| 1021 |
call_command( |
| 1022 |
"createsuperuser", |
| 1023 |
interactive=True, |
| 1024 |
stdin=MockTTY(), |
| 1025 |
stdout=new_io, |
| 1026 |
stderr=new_io, |
| 1027 |
) |
| 1028 |
self.assertEqual( |
| 1029 |
new_io.getvalue().strip(), |
| 1030 |
"This password is entirely numeric.\n" |
| 1031 |
"Superuser created successfully.", |
| 1032 |
) |
| 1033 |
|
| 1034 |
test(self) |
| 1035 |
|
| 1036 |
def test_invalid_username(self): |
| 1037 |
"""Creation fails if the username fails validation.""" |
| 1038 |
user_field = User._meta.get_field(User.USERNAME_FIELD) |
| 1039 |
new_io = StringIO() |
| 1040 |
entered_passwords = ["password", "password"] |
| 1041 |
# Enter an invalid (too long) username first and then a valid one. |
| 1042 |
invalid_username = ("x" * user_field.max_length) + "y" |
| 1043 |
entered_usernames = [invalid_username, "janet"] |
| 1044 |
|
| 1045 |
def return_passwords(): |
| 1046 |
return entered_passwords.pop(0) |
| 1047 |
|
| 1048 |
def return_usernames(): |
| 1049 |
return entered_usernames.pop(0) |
| 1050 |
|
| 1051 |
@mock_inputs( |
| 1052 |
{"password": return_passwords, "username": return_usernames, "email": ""} |
| 1053 |
) |
| 1054 |
def test(self): |
| 1055 |
call_command( |
| 1056 |
"createsuperuser", |
| 1057 |
interactive=True, |
| 1058 |
stdin=MockTTY(), |
| 1059 |
stdout=new_io, |
| 1060 |
stderr=new_io, |
| 1061 |
) |
| 1062 |
self.assertEqual( |
| 1063 |
new_io.getvalue().strip(), |
| 1064 |
"Error: Ensure this value has at most %s characters (it has %s).\n" |
| 1065 |
"Superuser created successfully." |
| 1066 |
% (user_field.max_length, len(invalid_username)), |
| 1067 |
) |
| 1068 |
|
| 1069 |
test(self) |
| 1070 |
|
| 1071 |
@mock_inputs({"username": "KeyboardInterrupt"}) |
| 1072 |
def test_keyboard_interrupt(self): |
| 1073 |
new_io = StringIO() |
| 1074 |
with self.assertRaises(SystemExit): |
| 1075 |
call_command( |
| 1076 |
"createsuperuser", |
| 1077 |
interactive=True, |
| 1078 |
stdin=MockTTY(), |
| 1079 |
stdout=new_io, |
| 1080 |
stderr=new_io, |
| 1081 |
) |
| 1082 |
self.assertEqual(new_io.getvalue(), "\nOperation cancelled.\n") |
| 1083 |
|
| 1084 |
def test_existing_username(self): |
| 1085 |
"""Creation fails if the username already exists.""" |
| 1086 |
user = User.objects.create(username="janet") |
| 1087 |
new_io = StringIO() |
| 1088 |
entered_passwords = ["password", "password"] |
| 1089 |
# Enter the existing username first and then a new one. |
| 1090 |
entered_usernames = [user.username, "joe"] |
| 1091 |
|
| 1092 |
def return_passwords(): |
| 1093 |
return entered_passwords.pop(0) |
| 1094 |
|
| 1095 |
def return_usernames(): |
| 1096 |
return entered_usernames.pop(0) |
| 1097 |
|
| 1098 |
@mock_inputs( |
| 1099 |
{"password": return_passwords, "username": return_usernames, "email": ""} |
| 1100 |
) |
| 1101 |
def test(self): |
| 1102 |
call_command( |
| 1103 |
"createsuperuser", |
| 1104 |
interactive=True, |
| 1105 |
stdin=MockTTY(), |
| 1106 |
stdout=new_io, |
| 1107 |
stderr=new_io, |
| 1108 |
) |
| 1109 |
self.assertEqual( |
| 1110 |
new_io.getvalue().strip(), |
| 1111 |
"Error: That username is already taken.\n" |
| 1112 |
"Superuser created successfully.", |
| 1113 |
) |
| 1114 |
|
| 1115 |
test(self) |
| 1116 |
|
| 1117 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithUniqueConstraint") |
| 1118 |
def test_existing_username_meta_unique_constraint(self): |
| 1119 |
""" |
| 1120 |
Creation fails if the username already exists and a custom user model |
| 1121 |
has UniqueConstraint. |
| 1122 |
""" |
| 1123 |
user = CustomUserWithUniqueConstraint.objects.create(username="janet") |
| 1124 |
new_io = StringIO() |
| 1125 |
entered_passwords = ["password", "password"] |
| 1126 |
# Enter the existing username first and then a new one. |
| 1127 |
entered_usernames = [user.username, "joe"] |
| 1128 |
|
| 1129 |
def return_passwords(): |
| 1130 |
return entered_passwords.pop(0) |
| 1131 |
|
| 1132 |
def return_usernames(): |
| 1133 |
return entered_usernames.pop(0) |
| 1134 |
|
| 1135 |
@mock_inputs({"password": return_passwords, "username": return_usernames}) |
| 1136 |
def test(self): |
| 1137 |
call_command( |
| 1138 |
"createsuperuser", |
| 1139 |
interactive=True, |
| 1140 |
stdin=MockTTY(), |
| 1141 |
stdout=new_io, |
| 1142 |
stderr=new_io, |
| 1143 |
) |
| 1144 |
self.assertEqual( |
| 1145 |
new_io.getvalue().strip(), |
| 1146 |
"Error: That username is already taken.\n" |
| 1147 |
"Superuser created successfully.", |
| 1148 |
) |
| 1149 |
|
| 1150 |
test(self) |
| 1151 |
|
| 1152 |
def test_existing_username_non_interactive(self): |
| 1153 |
"""Creation fails if the username already exists.""" |
| 1154 |
User.objects.create(username="janet") |
| 1155 |
new_io = StringIO() |
| 1156 |
with self.assertRaisesMessage( |
| 1157 |
CommandError, "Error: That username is already taken." |
| 1158 |
): |
| 1159 |
call_command( |
| 1160 |
"createsuperuser", |
| 1161 |
username="janet", |
| 1162 |
email="", |
| 1163 |
interactive=False, |
| 1164 |
stdout=new_io, |
| 1165 |
) |
| 1166 |
|
| 1167 |
def test_existing_username_provided_via_option_and_interactive(self): |
| 1168 |
"""call_command() gets username='janet' and interactive=True.""" |
| 1169 |
new_io = StringIO() |
| 1170 |
entered_passwords = ["password", "password"] |
| 1171 |
User.objects.create(username="janet") |
| 1172 |
|
| 1173 |
def return_passwords(): |
| 1174 |
return entered_passwords.pop(0) |
| 1175 |
|
| 1176 |
@mock_inputs( |
| 1177 |
{ |
| 1178 |
"password": return_passwords, |
| 1179 |
"username": "janet1", |
| 1180 |
"email": "[email protected]", |
| 1181 |
} |
| 1182 |
) |
| 1183 |
def test(self): |
| 1184 |
call_command( |
| 1185 |
"createsuperuser", |
| 1186 |
username="janet", |
| 1187 |
interactive=True, |
| 1188 |
stdin=MockTTY(), |
| 1189 |
stdout=new_io, |
| 1190 |
stderr=new_io, |
| 1191 |
) |
| 1192 |
msg = ( |
| 1193 |
"Error: That username is already taken.\n" |
| 1194 |
"Superuser created successfully." |
| 1195 |
) |
| 1196 |
self.assertEqual(new_io.getvalue().strip(), msg) |
| 1197 |
|
| 1198 |
test(self) |
| 1199 |
|
| 1200 |
def test_validation_mismatched_passwords(self): |
| 1201 |
""" |
| 1202 |
Creation should fail if the user enters mismatched passwords. |
| 1203 |
""" |
| 1204 |
new_io = StringIO() |
| 1205 |
|
| 1206 |
# The first two passwords do not match, but the second two do match and |
| 1207 |
# are valid. |
| 1208 |
entered_passwords = ["password", "not password", "password2", "password2"] |
| 1209 |
|
| 1210 |
def mismatched_passwords_then_matched(): |
| 1211 |
return entered_passwords.pop(0) |
| 1212 |
|
| 1213 |
@mock_inputs( |
| 1214 |
{ |
| 1215 |
"password": mismatched_passwords_then_matched, |
| 1216 |
"username": "joe1234567890", |
| 1217 |
"email": "", |
| 1218 |
} |
| 1219 |
) |
| 1220 |
def test(self): |
| 1221 |
call_command( |
| 1222 |
"createsuperuser", |
| 1223 |
interactive=True, |
| 1224 |
stdin=MockTTY(), |
| 1225 |
stdout=new_io, |
| 1226 |
stderr=new_io, |
| 1227 |
) |
| 1228 |
self.assertEqual( |
| 1229 |
new_io.getvalue().strip(), |
| 1230 |
"Error: Your passwords didn't match.\n" |
| 1231 |
"Superuser created successfully.", |
| 1232 |
) |
| 1233 |
|
| 1234 |
test(self) |
| 1235 |
|
| 1236 |
def test_validation_blank_password_entered(self): |
| 1237 |
""" |
| 1238 |
Creation should fail if the user enters blank passwords. |
| 1239 |
""" |
| 1240 |
new_io = StringIO() |
| 1241 |
|
| 1242 |
# The first two passwords are empty strings, but the second two are |
| 1243 |
# valid. |
| 1244 |
entered_passwords = ["", "", "password2", "password2"] |
| 1245 |
|
| 1246 |
def blank_passwords_then_valid(): |
| 1247 |
return entered_passwords.pop(0) |
| 1248 |
|
| 1249 |
@mock_inputs( |
| 1250 |
{ |
| 1251 |
"password": blank_passwords_then_valid, |
| 1252 |
"username": "joe1234567890", |
| 1253 |
"email": "", |
| 1254 |
} |
| 1255 |
) |
| 1256 |
def test(self): |
| 1257 |
call_command( |
| 1258 |
"createsuperuser", |
| 1259 |
interactive=True, |
| 1260 |
stdin=MockTTY(), |
| 1261 |
stdout=new_io, |
| 1262 |
stderr=new_io, |
| 1263 |
) |
| 1264 |
self.assertEqual( |
| 1265 |
new_io.getvalue().strip(), |
| 1266 |
"Error: Blank passwords aren't allowed.\n" |
| 1267 |
"Superuser created successfully.", |
| 1268 |
) |
| 1269 |
|
| 1270 |
test(self) |
| 1271 |
|
| 1272 |
@override_settings(AUTH_USER_MODEL="auth_tests.NoPasswordUser") |
| 1273 |
def test_usermodel_without_password(self): |
| 1274 |
new_io = StringIO() |
| 1275 |
call_command( |
| 1276 |
"createsuperuser", |
| 1277 |
interactive=False, |
| 1278 |
stdin=MockTTY(), |
| 1279 |
stdout=new_io, |
| 1280 |
stderr=new_io, |
| 1281 |
username="username", |
| 1282 |
) |
| 1283 |
self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") |
| 1284 |
|
| 1285 |
@override_settings(AUTH_USER_MODEL="auth_tests.NoPasswordUser") |
| 1286 |
def test_usermodel_without_password_interactive(self): |
| 1287 |
new_io = StringIO() |
| 1288 |
|
| 1289 |
@mock_inputs({"username": "username"}) |
| 1290 |
def test(self): |
| 1291 |
call_command( |
| 1292 |
"createsuperuser", |
| 1293 |
interactive=True, |
| 1294 |
stdin=MockTTY(), |
| 1295 |
stdout=new_io, |
| 1296 |
stderr=new_io, |
| 1297 |
) |
| 1298 |
self.assertEqual( |
| 1299 |
new_io.getvalue().strip(), "Superuser created successfully." |
| 1300 |
) |
| 1301 |
|
| 1302 |
test(self) |
| 1303 |
|
| 1304 |
@mock.patch.dict( |
| 1305 |
os.environ, |
| 1306 |
{ |
| 1307 |
"DJANGO_SUPERUSER_PASSWORD": "test_password", |
| 1308 |
"DJANGO_SUPERUSER_USERNAME": "test_superuser", |
| 1309 |
"DJANGO_SUPERUSER_EMAIL": "[email protected]", |
| 1310 |
"DJANGO_SUPERUSER_FIRST_NAME": "ignored_first_name", |
| 1311 |
}, |
| 1312 |
) |
| 1313 |
def test_environment_variable_non_interactive(self): |
| 1314 |
call_command("createsuperuser", interactive=False, verbosity=0) |
| 1315 |
user = User.objects.get(username="test_superuser") |
| 1316 |
self.assertEqual(user.email, "[email protected]") |
| 1317 |
self.assertTrue(user.check_password("test_password")) |
| 1318 |
# Environment variables are ignored for non-required fields. |
| 1319 |
self.assertEqual(user.first_name, "") |
| 1320 |
|
| 1321 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2m") |
| 1322 |
def test_environment_variable_m2m_non_interactive(self): |
| 1323 |
new_io = StringIO() |
| 1324 |
org_id_1 = Organization.objects.create(name="Organization 1").pk |
| 1325 |
org_id_2 = Organization.objects.create(name="Organization 2").pk |
| 1326 |
with mock.patch.dict( |
| 1327 |
os.environ, |
| 1328 |
{ |
| 1329 |
"DJANGO_SUPERUSER_ORGS": f"{org_id_1},{org_id_2}", |
| 1330 |
}, |
| 1331 |
): |
| 1332 |
call_command( |
| 1333 |
"createsuperuser", |
| 1334 |
interactive=False, |
| 1335 |
username="joe", |
| 1336 |
stdout=new_io, |
| 1337 |
) |
| 1338 |
command_output = new_io.getvalue().strip() |
| 1339 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 1340 |
user = CustomUserWithM2M._default_manager.get(username="joe") |
| 1341 |
self.assertEqual(user.orgs.count(), 2) |
| 1342 |
|
| 1343 |
@mock.patch.dict( |
| 1344 |
os.environ, |
| 1345 |
{ |
| 1346 |
"DJANGO_SUPERUSER_USERNAME": "test_superuser", |
| 1347 |
"DJANGO_SUPERUSER_EMAIL": "[email protected]", |
| 1348 |
}, |
| 1349 |
) |
| 1350 |
def test_ignore_environment_variable_non_interactive(self): |
| 1351 |
# Environment variables are ignored in non-interactive mode, if |
| 1352 |
# provided by a command line arguments. |
| 1353 |
call_command( |
| 1354 |
"createsuperuser", |
| 1355 |
interactive=False, |
| 1356 |
username="cmd_superuser", |
| 1357 |
email="[email protected]", |
| 1358 |
verbosity=0, |
| 1359 |
) |
| 1360 |
user = User.objects.get(username="cmd_superuser") |
| 1361 |
self.assertEqual(user.email, "[email protected]") |
| 1362 |
self.assertFalse(user.has_usable_password()) |
| 1363 |
|
| 1364 |
@mock.patch.dict( |
| 1365 |
os.environ, |
| 1366 |
{ |
| 1367 |
"DJANGO_SUPERUSER_PASSWORD": "test_password", |
| 1368 |
"DJANGO_SUPERUSER_USERNAME": "test_superuser", |
| 1369 |
"DJANGO_SUPERUSER_EMAIL": "[email protected]", |
| 1370 |
}, |
| 1371 |
) |
| 1372 |
def test_ignore_environment_variable_interactive(self): |
| 1373 |
# Environment variables are ignored in interactive mode. |
| 1374 |
@mock_inputs({"password": "cmd_password"}) |
| 1375 |
def test(self): |
| 1376 |
call_command( |
| 1377 |
"createsuperuser", |
| 1378 |
interactive=True, |
| 1379 |
username="cmd_superuser", |
| 1380 |
email="[email protected]", |
| 1381 |
stdin=MockTTY(), |
| 1382 |
verbosity=0, |
| 1383 |
) |
| 1384 |
user = User.objects.get(username="cmd_superuser") |
| 1385 |
self.assertEqual(user.email, "[email protected]") |
| 1386 |
self.assertTrue(user.check_password("cmd_password")) |
| 1387 |
|
| 1388 |
test(self) |
| 1389 |
|
| 1390 |
|
| 1391 |
class MultiDBCreatesuperuserTestCase(TestCase): |
| 1392 |
databases = {"default", "other"} |
| 1393 |
|
| 1394 |
def test_createsuperuser_command_with_database_option(self): |
| 1395 |
""" |
| 1396 |
createsuperuser --database should operate on the specified DB. |
| 1397 |
""" |
| 1398 |
new_io = StringIO() |
| 1399 |
call_command( |
| 1400 |
"createsuperuser", |
| 1401 |
interactive=False, |
| 1402 |
username="joe", |
| 1403 |
email="[email protected]", |
| 1404 |
database="other", |
| 1405 |
stdout=new_io, |
| 1406 |
) |
| 1407 |
command_output = new_io.getvalue().strip() |
| 1408 |
self.assertEqual(command_output, "Superuser created successfully.") |
| 1409 |
user = User.objects.using("other").get(username="joe") |
| 1410 |
self.assertEqual(user.email, "[email protected]") |
| 1411 |
|
| 1412 |
def test_createsuperuser_command_suggested_username_with_database_option(self): |
| 1413 |
default_username = get_default_username(database="other") |
| 1414 |
qs = User.objects.using("other") |
| 1415 |
|
| 1416 |
@mock_inputs({"password": "nopasswd", "username": "", "email": ""}) |
| 1417 |
def test_other_create_with_suggested_username(self): |
| 1418 |
call_command( |
| 1419 |
"createsuperuser", |
| 1420 |
interactive=True, |
| 1421 |
stdin=MockTTY(), |
| 1422 |
verbosity=0, |
| 1423 |
database="other", |
| 1424 |
) |
| 1425 |
self.assertIs(qs.filter(username=default_username).exists(), True) |
| 1426 |
|
| 1427 |
test_other_create_with_suggested_username(self) |
| 1428 |
|
| 1429 |
@mock_inputs({"password": "nopasswd", "Username: ": "other", "email": ""}) |
| 1430 |
def test_other_no_suggestion(self): |
| 1431 |
call_command( |
| 1432 |
"createsuperuser", |
| 1433 |
interactive=True, |
| 1434 |
stdin=MockTTY(), |
| 1435 |
verbosity=0, |
| 1436 |
database="other", |
| 1437 |
) |
| 1438 |
self.assertIs(qs.filter(username="other").exists(), True) |
| 1439 |
|
| 1440 |
test_other_no_suggestion(self) |
| 1441 |
|
| 1442 |
|
| 1443 |
class CreatePermissionsTests(TestCase): |
| 1444 |
def setUp(self): |
| 1445 |
self._original_permissions = Permission._meta.permissions[:] |
| 1446 |
self._original_default_permissions = Permission._meta.default_permissions |
| 1447 |
self.app_config = apps.get_app_config("auth") |
| 1448 |
|
| 1449 |
def tearDown(self): |
| 1450 |
Permission._meta.permissions = self._original_permissions |
| 1451 |
Permission._meta.default_permissions = self._original_default_permissions |
| 1452 |
ContentType.objects.clear_cache() |
| 1453 |
|
| 1454 |
def test_default_permissions(self): |
| 1455 |
permission_content_type = ContentType.objects.get_by_natural_key( |
| 1456 |
"auth", "permission" |
| 1457 |
) |
| 1458 |
Permission._meta.permissions = [ |
| 1459 |
("my_custom_permission", "Some permission"), |
| 1460 |
] |
| 1461 |
create_permissions(self.app_config, verbosity=0) |
| 1462 |
|
| 1463 |
# view/add/change/delete permission by default + custom permission |
| 1464 |
self.assertEqual( |
| 1465 |
Permission.objects.filter( |
| 1466 |
content_type=permission_content_type, |
| 1467 |
).count(), |
| 1468 |
5, |
| 1469 |
) |
| 1470 |
|
| 1471 |
Permission.objects.filter(content_type=permission_content_type).delete() |
| 1472 |
Permission._meta.default_permissions = [] |
| 1473 |
create_permissions(self.app_config, verbosity=0) |
| 1474 |
|
| 1475 |
# custom permission only since default permissions is empty |
| 1476 |
self.assertEqual( |
| 1477 |
Permission.objects.filter( |
| 1478 |
content_type=permission_content_type, |
| 1479 |
).count(), |
| 1480 |
1, |
| 1481 |
) |
| 1482 |
|
| 1483 |
def test_unavailable_models(self): |
| 1484 |
""" |
| 1485 |
#24075 - Permissions shouldn't be created or deleted if the ContentType |
| 1486 |
or Permission models aren't available. |
| 1487 |
""" |
| 1488 |
state = migrations.state.ProjectState() |
| 1489 |
# Unavailable contenttypes.ContentType |
| 1490 |
with self.assertNumQueries(0): |
| 1491 |
create_permissions(self.app_config, verbosity=0, apps=state.apps) |
| 1492 |
# Unavailable auth.Permission |
| 1493 |
state = migrations.state.ProjectState(real_apps={"contenttypes"}) |
| 1494 |
with self.assertNumQueries(0): |
| 1495 |
create_permissions(self.app_config, verbosity=0, apps=state.apps) |
| 1496 |
|
| 1497 |
def test_create_permissions_checks_contenttypes_created(self): |
| 1498 |
""" |
| 1499 |
`post_migrate` handler ordering isn't guaranteed. Simulate a case |
| 1500 |
where create_permissions() is called before create_contenttypes(). |
| 1501 |
""" |
| 1502 |
# Warm the manager cache. |
| 1503 |
ContentType.objects.get_for_model(Group) |
| 1504 |
# Apply a deletion as if e.g. a database 'flush' had been executed. |
| 1505 |
ContentType.objects.filter(app_label="auth", model="group").delete() |
| 1506 |
# This fails with a foreign key constraint without the fix. |
| 1507 |
create_permissions(apps.get_app_config("auth"), interactive=False, verbosity=0) |
| 1508 |
|
| 1509 |
def test_permission_with_proxy_content_type_created(self): |
| 1510 |
""" |
| 1511 |
A proxy model's permissions use its own content type rather than the |
| 1512 |
content type of the concrete model. |
| 1513 |
""" |
| 1514 |
opts = UserProxy._meta |
| 1515 |
codename = get_permission_codename("add", opts) |
| 1516 |
self.assertTrue( |
| 1517 |
Permission.objects.filter( |
| 1518 |
content_type__model=opts.model_name, |
| 1519 |
content_type__app_label=opts.app_label, |
| 1520 |
codename=codename, |
| 1521 |
).exists() |
| 1522 |
) |
| 1523 |
|
| 1524 |
|
| 1525 |
class DefaultDBRouter: |
| 1526 |
"""Route all writes to default.""" |
| 1527 |
|
| 1528 |
def db_for_write(self, model, **hints): |
| 1529 |
return "default" |
| 1530 |
|
| 1531 |
|
| 1532 |
@override_settings(DATABASE_ROUTERS=[DefaultDBRouter()]) |
| 1533 |
class CreatePermissionsMultipleDatabasesTests(TestCase): |
| 1534 |
databases = {"default", "other"} |
| 1535 |
|
| 1536 |
def test_set_permissions_fk_to_using_parameter(self): |
| 1537 |
Permission.objects.using("other").delete() |
| 1538 |
with self.assertNumQueries(4, using="other") as captured_queries: |
| 1539 |
create_permissions(apps.get_app_config("auth"), verbosity=0, using="other") |
| 1540 |
self.assertIn("INSERT INTO", captured_queries[-1]["sql"].upper()) |
| 1541 |
self.assertGreater(Permission.objects.using("other").count(), 0) |