| 1 |
from unittest import mock |
| 2 |
|
| 3 |
from django.conf.global_settings import PASSWORD_HASHERS |
| 4 |
from django.contrib.auth import get_user_model |
| 5 |
from django.contrib.auth.backends import ModelBackend |
| 6 |
from django.contrib.auth.base_user import AbstractBaseUser |
| 7 |
from django.contrib.auth.hashers import get_hasher |
| 8 |
from django.contrib.auth.models import ( |
| 9 |
AnonymousUser, |
| 10 |
Group, |
| 11 |
Permission, |
| 12 |
User, |
| 13 |
UserManager, |
| 14 |
) |
| 15 |
from django.contrib.contenttypes.models import ContentType |
| 16 |
from django.core import mail |
| 17 |
from django.db import connection, migrations |
| 18 |
from django.db.migrations.state import ModelState, ProjectState |
| 19 |
from django.db.models.signals import post_save |
| 20 |
from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings |
| 21 |
|
| 22 |
from .models import CustomEmailField, IntegerUsernameUser |
| 23 |
|
| 24 |
|
| 25 |
class NaturalKeysTestCase(TestCase): |
| 26 |
def test_user_natural_key(self): |
| 27 |
staff_user = User.objects.create_user(username="staff") |
| 28 |
self.assertEqual(User.objects.get_by_natural_key("staff"), staff_user) |
| 29 |
self.assertEqual(staff_user.natural_key(), ("staff",)) |
| 30 |
|
| 31 |
async def test_auser_natural_key(self): |
| 32 |
staff_user = await User.objects.acreate_user(username="staff") |
| 33 |
self.assertEqual(await User.objects.aget_by_natural_key("staff"), staff_user) |
| 34 |
self.assertEqual(staff_user.natural_key(), ("staff",)) |
| 35 |
|
| 36 |
def test_group_natural_key(self): |
| 37 |
users_group = Group.objects.create(name="users") |
| 38 |
self.assertEqual(Group.objects.get_by_natural_key("users"), users_group) |
| 39 |
|
| 40 |
async def test_agroup_natural_key(self): |
| 41 |
users_group = await Group.objects.acreate(name="users") |
| 42 |
self.assertEqual(await Group.objects.aget_by_natural_key("users"), users_group) |
| 43 |
|
| 44 |
|
| 45 |
class LoadDataWithoutNaturalKeysTestCase(TestCase): |
| 46 |
fixtures = ["regular.json"] |
| 47 |
|
| 48 |
def test_user_is_created_and_added_to_group(self): |
| 49 |
user = User.objects.get(username="my_username") |
| 50 |
group = Group.objects.get(name="my_group") |
| 51 |
self.assertEqual(group, user.groups.get()) |
| 52 |
|
| 53 |
|
| 54 |
class LoadDataWithNaturalKeysTestCase(TestCase): |
| 55 |
fixtures = ["natural.json"] |
| 56 |
|
| 57 |
def test_user_is_created_and_added_to_group(self): |
| 58 |
user = User.objects.get(username="my_username") |
| 59 |
group = Group.objects.get(name="my_group") |
| 60 |
self.assertEqual(group, user.groups.get()) |
| 61 |
|
| 62 |
|
| 63 |
class LoadDataWithNaturalKeysAndMultipleDatabasesTestCase(TestCase): |
| 64 |
databases = {"default", "other"} |
| 65 |
|
| 66 |
def test_load_data_with_user_permissions(self): |
| 67 |
# Create test contenttypes for both databases |
| 68 |
default_objects = [ |
| 69 |
ContentType.objects.db_manager("default").create( |
| 70 |
model="examplemodela", |
| 71 |
app_label="app_a", |
| 72 |
), |
| 73 |
ContentType.objects.db_manager("default").create( |
| 74 |
model="examplemodelb", |
| 75 |
app_label="app_b", |
| 76 |
), |
| 77 |
] |
| 78 |
other_objects = [ |
| 79 |
ContentType.objects.db_manager("other").create( |
| 80 |
model="examplemodelb", |
| 81 |
app_label="app_b", |
| 82 |
), |
| 83 |
ContentType.objects.db_manager("other").create( |
| 84 |
model="examplemodela", |
| 85 |
app_label="app_a", |
| 86 |
), |
| 87 |
] |
| 88 |
|
| 89 |
# Now we create the test UserPermission |
| 90 |
Permission.objects.db_manager("default").create( |
| 91 |
name="Can delete example model b", |
| 92 |
codename="delete_examplemodelb", |
| 93 |
content_type=default_objects[1], |
| 94 |
) |
| 95 |
Permission.objects.db_manager("other").create( |
| 96 |
name="Can delete example model b", |
| 97 |
codename="delete_examplemodelb", |
| 98 |
content_type=other_objects[0], |
| 99 |
) |
| 100 |
|
| 101 |
perm_default = Permission.objects.get_by_natural_key( |
| 102 |
"delete_examplemodelb", |
| 103 |
"app_b", |
| 104 |
"examplemodelb", |
| 105 |
) |
| 106 |
|
| 107 |
perm_other = Permission.objects.db_manager("other").get_by_natural_key( |
| 108 |
"delete_examplemodelb", |
| 109 |
"app_b", |
| 110 |
"examplemodelb", |
| 111 |
) |
| 112 |
|
| 113 |
self.assertEqual(perm_default.content_type_id, default_objects[1].id) |
| 114 |
self.assertEqual(perm_other.content_type_id, other_objects[0].id) |
| 115 |
|
| 116 |
|
| 117 |
class UserManagerTestCase(TransactionTestCase): |
| 118 |
available_apps = [ |
| 119 |
"auth_tests", |
| 120 |
"django.contrib.auth", |
| 121 |
"django.contrib.contenttypes", |
| 122 |
] |
| 123 |
|
| 124 |
def test_create_user(self): |
| 125 |
email_lowercase = "[email protected]" |
| 126 |
user = User.objects.create_user("user", email_lowercase) |
| 127 |
self.assertEqual(user.email, email_lowercase) |
| 128 |
self.assertEqual(user.username, "user") |
| 129 |
self.assertFalse(user.has_usable_password()) |
| 130 |
|
| 131 |
def test_create_user_email_domain_normalize_rfc3696(self): |
| 132 |
# According to RFC 3696 Section 3 the "@" symbol can be part of the |
| 133 |
# local part of an email address. |
| 134 |
returned = UserManager.normalize_email(r"Abc\@[email protected]") |
| 135 |
self.assertEqual(returned, r"Abc\@[email protected]") |
| 136 |
|
| 137 |
def test_create_user_email_domain_normalize(self): |
| 138 |
returned = UserManager.normalize_email("[email protected]") |
| 139 |
self.assertEqual(returned, "[email protected]") |
| 140 |
|
| 141 |
def test_create_user_email_domain_normalize_with_whitespace(self): |
| 142 |
returned = UserManager.normalize_email(r"email\ [email protected]") |
| 143 |
self.assertEqual(returned, r"email\ [email protected]") |
| 144 |
|
| 145 |
def test_empty_username(self): |
| 146 |
with self.assertRaisesMessage(ValueError, "The given username must be set"): |
| 147 |
User.objects.create_user(username="") |
| 148 |
|
| 149 |
def test_create_user_is_staff(self): |
| 150 |
email = "[email protected]" |
| 151 |
user = User.objects.create_user("user", email, is_staff=True) |
| 152 |
self.assertEqual(user.email, email) |
| 153 |
self.assertEqual(user.username, "user") |
| 154 |
self.assertTrue(user.is_staff) |
| 155 |
|
| 156 |
def test_create_super_user_raises_error_on_false_is_superuser(self): |
| 157 |
with self.assertRaisesMessage( |
| 158 |
ValueError, "Superuser must have is_superuser=True." |
| 159 |
): |
| 160 |
User.objects.create_superuser( |
| 161 |
username="test", |
| 162 |
email="[email protected]", |
| 163 |
password="test", |
| 164 |
is_superuser=False, |
| 165 |
) |
| 166 |
|
| 167 |
async def test_acreate_super_user_raises_error_on_false_is_superuser(self): |
| 168 |
with self.assertRaisesMessage( |
| 169 |
ValueError, "Superuser must have is_superuser=True." |
| 170 |
): |
| 171 |
await User.objects.acreate_superuser( |
| 172 |
username="test", |
| 173 |
email="[email protected]", |
| 174 |
password="test", |
| 175 |
is_superuser=False, |
| 176 |
) |
| 177 |
|
| 178 |
def test_create_superuser_raises_error_on_false_is_staff(self): |
| 179 |
with self.assertRaisesMessage(ValueError, "Superuser must have is_staff=True."): |
| 180 |
User.objects.create_superuser( |
| 181 |
username="test", |
| 182 |
email="[email protected]", |
| 183 |
password="test", |
| 184 |
is_staff=False, |
| 185 |
) |
| 186 |
|
| 187 |
async def test_acreate_superuser_raises_error_on_false_is_staff(self): |
| 188 |
with self.assertRaisesMessage(ValueError, "Superuser must have is_staff=True."): |
| 189 |
await User.objects.acreate_superuser( |
| 190 |
username="test", |
| 191 |
email="[email protected]", |
| 192 |
password="test", |
| 193 |
is_staff=False, |
| 194 |
) |
| 195 |
|
| 196 |
def test_runpython_manager_methods(self): |
| 197 |
def forwards(apps, schema_editor): |
| 198 |
UserModel = apps.get_model("auth", "User") |
| 199 |
user = UserModel.objects.create_user("user1", password="secure") |
| 200 |
self.assertIsInstance(user, UserModel) |
| 201 |
|
| 202 |
operation = migrations.RunPython(forwards, migrations.RunPython.noop) |
| 203 |
project_state = ProjectState() |
| 204 |
project_state.add_model(ModelState.from_model(User)) |
| 205 |
project_state.add_model(ModelState.from_model(Group)) |
| 206 |
project_state.add_model(ModelState.from_model(Permission)) |
| 207 |
project_state.add_model(ModelState.from_model(ContentType)) |
| 208 |
new_state = project_state.clone() |
| 209 |
with connection.schema_editor() as editor: |
| 210 |
operation.state_forwards("test_manager_methods", new_state) |
| 211 |
operation.database_forwards( |
| 212 |
"test_manager_methods", |
| 213 |
editor, |
| 214 |
project_state, |
| 215 |
new_state, |
| 216 |
) |
| 217 |
user = User.objects.get(username="user1") |
| 218 |
self.assertTrue(user.check_password("secure")) |
| 219 |
|
| 220 |
|
| 221 |
class AbstractBaseUserTests(SimpleTestCase): |
| 222 |
def test_has_usable_password(self): |
| 223 |
""" |
| 224 |
Passwords are usable even if they don't correspond to a hasher in |
| 225 |
settings.PASSWORD_HASHERS. |
| 226 |
""" |
| 227 |
self.assertIs(User(password="some-gibbberish").has_usable_password(), True) |
| 228 |
|
| 229 |
def test_normalize_username(self): |
| 230 |
self.assertEqual(IntegerUsernameUser().normalize_username(123), 123) |
| 231 |
|
| 232 |
def test_clean_normalize_username(self): |
| 233 |
# The normalization happens in AbstractBaseUser.clean() |
| 234 |
ohm_username = "iamtheΩ" # U+2126 OHM SIGN |
| 235 |
for model in ("auth.User", "auth_tests.CustomUser"): |
| 236 |
with self.subTest(model=model), self.settings(AUTH_USER_MODEL=model): |
| 237 |
User = get_user_model() |
| 238 |
user = User(**{User.USERNAME_FIELD: ohm_username, "password": "foo"}) |
| 239 |
user.clean() |
| 240 |
username = user.get_username() |
| 241 |
self.assertNotEqual(username, ohm_username) |
| 242 |
self.assertEqual( |
| 243 |
username, "iamtheΩ" |
| 244 |
) # U+03A9 GREEK CAPITAL LETTER OMEGA |
| 245 |
|
| 246 |
def test_default_email(self): |
| 247 |
self.assertEqual(AbstractBaseUser.get_email_field_name(), "email") |
| 248 |
|
| 249 |
def test_custom_email(self): |
| 250 |
user = CustomEmailField() |
| 251 |
self.assertEqual(user.get_email_field_name(), "email_address") |
| 252 |
|
| 253 |
|
| 254 |
class AbstractUserTestCase(TestCase): |
| 255 |
def test_email_user(self): |
| 256 |
# valid send_mail parameters |
| 257 |
kwargs = { |
| 258 |
"fail_silently": False, |
| 259 |
"auth_user": None, |
| 260 |
"auth_password": None, |
| 261 |
"connection": None, |
| 262 |
"html_message": None, |
| 263 |
} |
| 264 |
user = User(email="[email protected]") |
| 265 |
user.email_user( |
| 266 |
subject="Subject here", |
| 267 |
message="This is a message", |
| 268 |
from_email="[email protected]", |
| 269 |
**kwargs, |
| 270 |
) |
| 271 |
self.assertEqual(len(mail.outbox), 1) |
| 272 |
message = mail.outbox[0] |
| 273 |
self.assertEqual(message.subject, "Subject here") |
| 274 |
self.assertEqual(message.body, "This is a message") |
| 275 |
self.assertEqual(message.from_email, "[email protected]") |
| 276 |
self.assertEqual(message.to, [user.email]) |
| 277 |
|
| 278 |
def test_last_login_default(self): |
| 279 |
user1 = User.objects.create(username="user1") |
| 280 |
self.assertIsNone(user1.last_login) |
| 281 |
|
| 282 |
user2 = User.objects.create_user(username="user2") |
| 283 |
self.assertIsNone(user2.last_login) |
| 284 |
|
| 285 |
def test_user_clean_normalize_email(self): |
| 286 |
user = User(username="user", password="foo", email="[email protected]") |
| 287 |
user.clean() |
| 288 |
self.assertEqual(user.email, "[email protected]") |
| 289 |
|
| 290 |
def test_user_double_save(self): |
| 291 |
""" |
| 292 |
Calling user.save() twice should trigger password_changed() once. |
| 293 |
""" |
| 294 |
user = User.objects.create_user(username="user", password="foo") |
| 295 |
user.set_password("bar") |
| 296 |
with mock.patch( |
| 297 |
"django.contrib.auth.password_validation.password_changed" |
| 298 |
) as pw_changed: |
| 299 |
user.save() |
| 300 |
self.assertEqual(pw_changed.call_count, 1) |
| 301 |
user.save() |
| 302 |
self.assertEqual(pw_changed.call_count, 1) |
| 303 |
|
| 304 |
@override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) |
| 305 |
def test_check_password_upgrade(self): |
| 306 |
""" |
| 307 |
password_changed() shouldn't be called if User.check_password() |
| 308 |
triggers a hash iteration upgrade. |
| 309 |
""" |
| 310 |
user = User.objects.create_user(username="user", password="foo") |
| 311 |
initial_password = user.password |
| 312 |
self.assertTrue(user.check_password("foo")) |
| 313 |
hasher = get_hasher("default") |
| 314 |
self.assertEqual("pbkdf2_sha256", hasher.algorithm) |
| 315 |
|
| 316 |
old_iterations = hasher.iterations |
| 317 |
try: |
| 318 |
# Upgrade the password iterations |
| 319 |
hasher.iterations = old_iterations + 1 |
| 320 |
with mock.patch( |
| 321 |
"django.contrib.auth.password_validation.password_changed" |
| 322 |
) as pw_changed: |
| 323 |
user.check_password("foo") |
| 324 |
self.assertEqual(pw_changed.call_count, 0) |
| 325 |
self.assertNotEqual(initial_password, user.password) |
| 326 |
finally: |
| 327 |
hasher.iterations = old_iterations |
| 328 |
|
| 329 |
@override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) |
| 330 |
async def test_acheck_password_upgrade(self): |
| 331 |
user = await User.objects.acreate_user(username="user", password="foo") |
| 332 |
initial_password = user.password |
| 333 |
self.assertIs(await user.acheck_password("foo"), True) |
| 334 |
hasher = get_hasher("default") |
| 335 |
self.assertEqual("pbkdf2_sha256", hasher.algorithm) |
| 336 |
|
| 337 |
old_iterations = hasher.iterations |
| 338 |
try: |
| 339 |
# Upgrade the password iterations. |
| 340 |
hasher.iterations = old_iterations + 1 |
| 341 |
with mock.patch( |
| 342 |
"django.contrib.auth.password_validation.password_changed" |
| 343 |
) as pw_changed: |
| 344 |
self.assertIs(await user.acheck_password("foo"), True) |
| 345 |
self.assertEqual(pw_changed.call_count, 0) |
| 346 |
self.assertNotEqual(initial_password, user.password) |
| 347 |
finally: |
| 348 |
hasher.iterations = old_iterations |
| 349 |
|
| 350 |
|
| 351 |
class CustomModelBackend(ModelBackend): |
| 352 |
def with_perm( |
| 353 |
self, perm, is_active=True, include_superusers=True, backend=None, obj=None |
| 354 |
): |
| 355 |
if obj is not None and obj.username == "charliebrown": |
| 356 |
return User.objects.filter(pk=obj.pk) |
| 357 |
return User.objects.filter(username__startswith="charlie") |
| 358 |
|
| 359 |
|
| 360 |
class UserWithPermTestCase(TestCase): |
| 361 |
@classmethod |
| 362 |
def setUpTestData(cls): |
| 363 |
content_type = ContentType.objects.get_for_model(Group) |
| 364 |
cls.permission = Permission.objects.create( |
| 365 |
name="test", |
| 366 |
content_type=content_type, |
| 367 |
codename="test", |
| 368 |
) |
| 369 |
# User with permission. |
| 370 |
cls.user1 = User.objects.create_user("user 1", "[email protected]") |
| 371 |
cls.user1.user_permissions.add(cls.permission) |
| 372 |
# User with group permission. |
| 373 |
group1 = Group.objects.create(name="group 1") |
| 374 |
group1.permissions.add(cls.permission) |
| 375 |
group2 = Group.objects.create(name="group 2") |
| 376 |
group2.permissions.add(cls.permission) |
| 377 |
cls.user2 = User.objects.create_user("user 2", "[email protected]") |
| 378 |
cls.user2.groups.add(group1, group2) |
| 379 |
# Users without permissions. |
| 380 |
cls.user_charlie = User.objects.create_user("charlie", "[email protected]") |
| 381 |
cls.user_charlie_b = User.objects.create_user( |
| 382 |
"charliebrown", "[email protected]" |
| 383 |
) |
| 384 |
# Superuser. |
| 385 |
cls.superuser = User.objects.create_superuser( |
| 386 |
"superuser", |
| 387 |
"[email protected]", |
| 388 |
"superpassword", |
| 389 |
) |
| 390 |
# Inactive user with permission. |
| 391 |
cls.inactive_user = User.objects.create_user( |
| 392 |
"inactive_user", |
| 393 |
"[email protected]", |
| 394 |
is_active=False, |
| 395 |
) |
| 396 |
cls.inactive_user.user_permissions.add(cls.permission) |
| 397 |
|
| 398 |
def test_invalid_permission_name(self): |
| 399 |
msg = "Permission name should be in the form app_label.permission_codename." |
| 400 |
for perm in ("nodots", "too.many.dots", "...", ""): |
| 401 |
with self.subTest(perm), self.assertRaisesMessage(ValueError, msg): |
| 402 |
User.objects.with_perm(perm) |
| 403 |
|
| 404 |
def test_invalid_permission_type(self): |
| 405 |
msg = "The `perm` argument must be a string or a permission instance." |
| 406 |
for perm in (b"auth.test", object(), None): |
| 407 |
with self.subTest(perm), self.assertRaisesMessage(TypeError, msg): |
| 408 |
User.objects.with_perm(perm) |
| 409 |
|
| 410 |
def test_invalid_backend_type(self): |
| 411 |
msg = "backend must be a dotted import path string (got %r)." |
| 412 |
for backend in (b"auth_tests.CustomModelBackend", object()): |
| 413 |
with self.subTest(backend): |
| 414 |
with self.assertRaisesMessage(TypeError, msg % backend): |
| 415 |
User.objects.with_perm("auth.test", backend=backend) |
| 416 |
|
| 417 |
def test_basic(self): |
| 418 |
active_users = [self.user1, self.user2] |
| 419 |
tests = [ |
| 420 |
({}, [*active_users, self.superuser]), |
| 421 |
({"obj": self.user1}, []), |
| 422 |
# Only inactive users. |
| 423 |
({"is_active": False}, [self.inactive_user]), |
| 424 |
# All users. |
| 425 |
({"is_active": None}, [*active_users, self.superuser, self.inactive_user]), |
| 426 |
# Exclude superusers. |
| 427 |
({"include_superusers": False}, active_users), |
| 428 |
( |
| 429 |
{"include_superusers": False, "is_active": False}, |
| 430 |
[self.inactive_user], |
| 431 |
), |
| 432 |
( |
| 433 |
{"include_superusers": False, "is_active": None}, |
| 434 |
[*active_users, self.inactive_user], |
| 435 |
), |
| 436 |
] |
| 437 |
for kwargs, expected_users in tests: |
| 438 |
for perm in ("auth.test", self.permission): |
| 439 |
with self.subTest(perm=perm, **kwargs): |
| 440 |
self.assertCountEqual( |
| 441 |
User.objects.with_perm(perm, **kwargs), |
| 442 |
expected_users, |
| 443 |
) |
| 444 |
|
| 445 |
@override_settings( |
| 446 |
AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.BaseBackend"] |
| 447 |
) |
| 448 |
def test_backend_without_with_perm(self): |
| 449 |
self.assertSequenceEqual(User.objects.with_perm("auth.test"), []) |
| 450 |
|
| 451 |
def test_nonexistent_permission(self): |
| 452 |
self.assertSequenceEqual(User.objects.with_perm("auth.perm"), [self.superuser]) |
| 453 |
|
| 454 |
def test_nonexistent_backend(self): |
| 455 |
with self.assertRaises(ImportError): |
| 456 |
User.objects.with_perm( |
| 457 |
"auth.test", |
| 458 |
backend="invalid.backend.CustomModelBackend", |
| 459 |
) |
| 460 |
|
| 461 |
def test_invalid_backend_submodule(self): |
| 462 |
with self.assertRaises(ImportError): |
| 463 |
User.objects.with_perm( |
| 464 |
"auth.test", |
| 465 |
backend="json.tool", |
| 466 |
) |
| 467 |
|
| 468 |
@override_settings( |
| 469 |
AUTHENTICATION_BACKENDS=["auth_tests.test_models.CustomModelBackend"] |
| 470 |
) |
| 471 |
def test_custom_backend(self): |
| 472 |
for perm in ("auth.test", self.permission): |
| 473 |
with self.subTest(perm): |
| 474 |
self.assertCountEqual( |
| 475 |
User.objects.with_perm(perm), |
| 476 |
[self.user_charlie, self.user_charlie_b], |
| 477 |
) |
| 478 |
|
| 479 |
@override_settings( |
| 480 |
AUTHENTICATION_BACKENDS=["auth_tests.test_models.CustomModelBackend"] |
| 481 |
) |
| 482 |
def test_custom_backend_pass_obj(self): |
| 483 |
for perm in ("auth.test", self.permission): |
| 484 |
with self.subTest(perm): |
| 485 |
self.assertSequenceEqual( |
| 486 |
User.objects.with_perm(perm, obj=self.user_charlie_b), |
| 487 |
[self.user_charlie_b], |
| 488 |
) |
| 489 |
|
| 490 |
@override_settings( |
| 491 |
AUTHENTICATION_BACKENDS=[ |
| 492 |
"auth_tests.test_models.CustomModelBackend", |
| 493 |
"django.contrib.auth.backends.ModelBackend", |
| 494 |
] |
| 495 |
) |
| 496 |
def test_multiple_backends(self): |
| 497 |
msg = ( |
| 498 |
"You have multiple authentication backends configured and " |
| 499 |
"therefore must provide the `backend` argument." |
| 500 |
) |
| 501 |
with self.assertRaisesMessage(ValueError, msg): |
| 502 |
User.objects.with_perm("auth.test") |
| 503 |
|
| 504 |
backend = "auth_tests.test_models.CustomModelBackend" |
| 505 |
self.assertCountEqual( |
| 506 |
User.objects.with_perm("auth.test", backend=backend), |
| 507 |
[self.user_charlie, self.user_charlie_b], |
| 508 |
) |
| 509 |
|
| 510 |
|
| 511 |
class IsActiveTestCase(TestCase): |
| 512 |
""" |
| 513 |
Tests the behavior of the guaranteed is_active attribute |
| 514 |
""" |
| 515 |
|
| 516 |
def test_builtin_user_isactive(self): |
| 517 |
user = User.objects.create(username="foo", email="[email protected]") |
| 518 |
# is_active is true by default |
| 519 |
self.assertIs(user.is_active, True) |
| 520 |
user.is_active = False |
| 521 |
user.save() |
| 522 |
user_fetched = User.objects.get(pk=user.pk) |
| 523 |
# the is_active flag is saved |
| 524 |
self.assertFalse(user_fetched.is_active) |
| 525 |
|
| 526 |
@override_settings(AUTH_USER_MODEL="auth_tests.IsActiveTestUser1") |
| 527 |
def test_is_active_field_default(self): |
| 528 |
""" |
| 529 |
tests that the default value for is_active is provided |
| 530 |
""" |
| 531 |
UserModel = get_user_model() |
| 532 |
user = UserModel(username="foo") |
| 533 |
self.assertIs(user.is_active, True) |
| 534 |
# you can set the attribute - but it will not save |
| 535 |
user.is_active = False |
| 536 |
# there should be no problem saving - but the attribute is not saved |
| 537 |
user.save() |
| 538 |
user_fetched = UserModel._default_manager.get(pk=user.pk) |
| 539 |
# the attribute is always true for newly retrieved instance |
| 540 |
self.assertIs(user_fetched.is_active, True) |
| 541 |
|
| 542 |
|
| 543 |
class TestCreateSuperUserSignals(TestCase): |
| 544 |
""" |
| 545 |
Simple test case for ticket #20541 |
| 546 |
""" |
| 547 |
|
| 548 |
def post_save_listener(self, *args, **kwargs): |
| 549 |
self.signals_count += 1 |
| 550 |
|
| 551 |
def setUp(self): |
| 552 |
self.signals_count = 0 |
| 553 |
post_save.connect(self.post_save_listener, sender=User) |
| 554 |
self.addCleanup(post_save.disconnect, self.post_save_listener, sender=User) |
| 555 |
|
| 556 |
def test_create_user(self): |
| 557 |
User.objects.create_user("JohnDoe") |
| 558 |
self.assertEqual(self.signals_count, 1) |
| 559 |
|
| 560 |
def test_create_superuser(self): |
| 561 |
User.objects.create_superuser("JohnDoe", "[email protected]", "1") |
| 562 |
self.assertEqual(self.signals_count, 1) |
| 563 |
|
| 564 |
|
| 565 |
class AnonymousUserTests(SimpleTestCase): |
| 566 |
no_repr_msg = "Django doesn't provide a DB representation for AnonymousUser." |
| 567 |
|
| 568 |
def setUp(self): |
| 569 |
self.user = AnonymousUser() |
| 570 |
|
| 571 |
def test_properties(self): |
| 572 |
self.assertIsNone(self.user.pk) |
| 573 |
self.assertEqual(self.user.username, "") |
| 574 |
self.assertEqual(self.user.get_username(), "") |
| 575 |
self.assertIs(self.user.is_anonymous, True) |
| 576 |
self.assertIs(self.user.is_authenticated, False) |
| 577 |
self.assertIs(self.user.is_staff, False) |
| 578 |
self.assertIs(self.user.is_active, False) |
| 579 |
self.assertIs(self.user.is_superuser, False) |
| 580 |
self.assertEqual(self.user.groups.count(), 0) |
| 581 |
self.assertEqual(self.user.user_permissions.count(), 0) |
| 582 |
self.assertEqual(self.user.get_user_permissions(), set()) |
| 583 |
self.assertEqual(self.user.get_group_permissions(), set()) |
| 584 |
|
| 585 |
async def test_properties_async_versions(self): |
| 586 |
self.assertEqual(await self.user.groups.acount(), 0) |
| 587 |
self.assertEqual(await self.user.user_permissions.acount(), 0) |
| 588 |
self.assertEqual(await self.user.aget_user_permissions(), set()) |
| 589 |
self.assertEqual(await self.user.aget_group_permissions(), set()) |
| 590 |
|
| 591 |
def test_str(self): |
| 592 |
self.assertEqual(str(self.user), "AnonymousUser") |
| 593 |
|
| 594 |
def test_eq(self): |
| 595 |
self.assertEqual(self.user, AnonymousUser()) |
| 596 |
self.assertNotEqual(self.user, User("super", "[email protected]", "super")) |
| 597 |
|
| 598 |
def test_hash(self): |
| 599 |
self.assertEqual(hash(self.user), 1) |
| 600 |
|
| 601 |
def test_int(self): |
| 602 |
msg = ( |
| 603 |
"Cannot cast AnonymousUser to int. Are you trying to use it in " |
| 604 |
"place of User?" |
| 605 |
) |
| 606 |
with self.assertRaisesMessage(TypeError, msg): |
| 607 |
int(self.user) |
| 608 |
|
| 609 |
def test_delete(self): |
| 610 |
with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): |
| 611 |
self.user.delete() |
| 612 |
|
| 613 |
def test_save(self): |
| 614 |
with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): |
| 615 |
self.user.save() |
| 616 |
|
| 617 |
def test_set_password(self): |
| 618 |
with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): |
| 619 |
self.user.set_password("password") |
| 620 |
|
| 621 |
def test_check_password(self): |
| 622 |
with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): |
| 623 |
self.user.check_password("password") |
| 624 |
|
| 625 |
|
| 626 |
class GroupTests(SimpleTestCase): |
| 627 |
def test_str(self): |
| 628 |
g = Group(name="Users") |
| 629 |
self.assertEqual(str(g), "Users") |
| 630 |
|
| 631 |
|
| 632 |
class PermissionTests(TestCase): |
| 633 |
def test_str(self): |
| 634 |
p = Permission.objects.get(codename="view_customemailfield") |
| 635 |
self.assertEqual( |
| 636 |
str(p), "Auth_Tests | custom email field | Can view custom email field" |
| 637 |
) |