test_models.py 23 KB

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