test_models.py 22 KB

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