test_models.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.conf.global_settings import PASSWORD_HASHERS
  4. from django.contrib.auth import get_user_model
  5. from django.contrib.auth.hashers import get_hasher
  6. from django.contrib.auth.models import (
  7. AbstractUser, Group, Permission, User, UserManager,
  8. )
  9. from django.contrib.contenttypes.models import ContentType
  10. from django.core import mail
  11. from django.db.models.signals import post_save
  12. from django.test import TestCase, mock, override_settings
  13. class NaturalKeysTestCase(TestCase):
  14. def test_user_natural_key(self):
  15. staff_user = User.objects.create_user(username='staff')
  16. self.assertEqual(User.objects.get_by_natural_key('staff'), staff_user)
  17. self.assertEqual(staff_user.natural_key(), ('staff',))
  18. def test_group_natural_key(self):
  19. users_group = Group.objects.create(name='users')
  20. self.assertEqual(Group.objects.get_by_natural_key('users'), users_group)
  21. class LoadDataWithoutNaturalKeysTestCase(TestCase):
  22. fixtures = ['regular.json']
  23. def test_user_is_created_and_added_to_group(self):
  24. user = User.objects.get(username='my_username')
  25. group = Group.objects.get(name='my_group')
  26. self.assertEqual(group, user.groups.get())
  27. class LoadDataWithNaturalKeysTestCase(TestCase):
  28. fixtures = ['natural.json']
  29. def test_user_is_created_and_added_to_group(self):
  30. user = User.objects.get(username='my_username')
  31. group = Group.objects.get(name='my_group')
  32. self.assertEqual(group, user.groups.get())
  33. class LoadDataWithNaturalKeysAndMultipleDatabasesTestCase(TestCase):
  34. multi_db = True
  35. def test_load_data_with_user_permissions(self):
  36. # Create test contenttypes for both databases
  37. default_objects = [
  38. ContentType.objects.db_manager('default').create(
  39. model='examplemodela',
  40. app_label='app_a',
  41. ),
  42. ContentType.objects.db_manager('default').create(
  43. model='examplemodelb',
  44. app_label='app_b',
  45. ),
  46. ]
  47. other_objects = [
  48. ContentType.objects.db_manager('other').create(
  49. model='examplemodelb',
  50. app_label='app_b',
  51. ),
  52. ContentType.objects.db_manager('other').create(
  53. model='examplemodela',
  54. app_label='app_a',
  55. ),
  56. ]
  57. # Now we create the test UserPermission
  58. Permission.objects.db_manager("default").create(
  59. name="Can delete example model b",
  60. codename="delete_examplemodelb",
  61. content_type=default_objects[1],
  62. )
  63. Permission.objects.db_manager("other").create(
  64. name="Can delete example model b",
  65. codename="delete_examplemodelb",
  66. content_type=other_objects[0],
  67. )
  68. perm_default = Permission.objects.get_by_natural_key(
  69. 'delete_examplemodelb',
  70. 'app_b',
  71. 'examplemodelb',
  72. )
  73. perm_other = Permission.objects.db_manager('other').get_by_natural_key(
  74. 'delete_examplemodelb',
  75. 'app_b',
  76. 'examplemodelb',
  77. )
  78. self.assertEqual(perm_default.content_type_id, default_objects[1].id)
  79. self.assertEqual(perm_other.content_type_id, other_objects[0].id)
  80. class UserManagerTestCase(TestCase):
  81. def test_create_user(self):
  82. email_lowercase = 'normal@normal.com'
  83. user = User.objects.create_user('user', email_lowercase)
  84. self.assertEqual(user.email, email_lowercase)
  85. self.assertEqual(user.username, 'user')
  86. self.assertFalse(user.has_usable_password())
  87. def test_create_user_email_domain_normalize_rfc3696(self):
  88. # According to http://tools.ietf.org/html/rfc3696#section-3
  89. # the "@" symbol can be part of the local part of an email address
  90. returned = UserManager.normalize_email(r'Abc\@DEF@EXAMPLE.com')
  91. self.assertEqual(returned, r'Abc\@DEF@example.com')
  92. def test_create_user_email_domain_normalize(self):
  93. returned = UserManager.normalize_email('normal@DOMAIN.COM')
  94. self.assertEqual(returned, 'normal@domain.com')
  95. def test_create_user_email_domain_normalize_with_whitespace(self):
  96. returned = UserManager.normalize_email('email\ with_whitespace@D.COM')
  97. self.assertEqual(returned, 'email\ with_whitespace@d.com')
  98. def test_empty_username(self):
  99. with self.assertRaisesMessage(ValueError, 'The given username must be set'):
  100. User.objects.create_user(username='')
  101. def test_create_user_is_staff(self):
  102. email = 'normal@normal.com'
  103. user = User.objects.create_user('user', email, is_staff=True)
  104. self.assertEqual(user.email, email)
  105. self.assertEqual(user.username, 'user')
  106. self.assertTrue(user.is_staff)
  107. def test_create_super_user_raises_error_on_false_is_superuser(self):
  108. with self.assertRaisesMessage(ValueError, 'Superuser must have is_superuser=True.'):
  109. User.objects.create_superuser(
  110. username='test', email='test@test.com',
  111. password='test', is_superuser=False,
  112. )
  113. def test_create_superuser_raises_error_on_false_is_staff(self):
  114. with self.assertRaisesMessage(ValueError, 'Superuser must have is_staff=True.'):
  115. User.objects.create_superuser(
  116. username='test', email='test@test.com',
  117. password='test', is_staff=False,
  118. )
  119. class AbstractBaseUserTests(TestCase):
  120. def test_clean_normalize_username(self):
  121. # The normalization happens in AbstractBaseUser.clean()
  122. ohm_username = 'iamtheΩ' # U+2126 OHM SIGN
  123. for model in ('auth.User', 'auth_tests.CustomUser'):
  124. with self.settings(AUTH_USER_MODEL=model):
  125. User = get_user_model()
  126. user = User(**{User.USERNAME_FIELD: ohm_username, 'password': 'foo'})
  127. user.clean()
  128. username = user.get_username()
  129. self.assertNotEqual(username, ohm_username)
  130. self.assertEqual(username, 'iamtheΩ') # U+03A9 GREEK CAPITAL LETTER OMEGA
  131. class AbstractUserTestCase(TestCase):
  132. def test_email_user(self):
  133. # valid send_mail parameters
  134. kwargs = {
  135. "fail_silently": False,
  136. "auth_user": None,
  137. "auth_password": None,
  138. "connection": None,
  139. "html_message": None,
  140. }
  141. abstract_user = AbstractUser(email='foo@bar.com')
  142. abstract_user.email_user(
  143. subject="Subject here",
  144. message="This is a message",
  145. from_email="from@domain.com",
  146. **kwargs
  147. )
  148. # Test that one message has been sent.
  149. self.assertEqual(len(mail.outbox), 1)
  150. # Verify that test email contains the correct attributes:
  151. message = mail.outbox[0]
  152. self.assertEqual(message.subject, "Subject here")
  153. self.assertEqual(message.body, "This is a message")
  154. self.assertEqual(message.from_email, "from@domain.com")
  155. self.assertEqual(message.to, [abstract_user.email])
  156. def test_last_login_default(self):
  157. user1 = User.objects.create(username='user1')
  158. self.assertIsNone(user1.last_login)
  159. user2 = User.objects.create_user(username='user2')
  160. self.assertIsNone(user2.last_login)
  161. def test_user_clean_normalize_email(self):
  162. user = User(username='user', password='foo', email='foo@BAR.com')
  163. user.clean()
  164. self.assertEqual(user.email, 'foo@bar.com')
  165. def test_user_double_save(self):
  166. """
  167. Calling user.save() twice should trigger password_changed() once.
  168. """
  169. user = User.objects.create_user(username='user', password='foo')
  170. user.set_password('bar')
  171. with mock.patch('django.contrib.auth.password_validation.password_changed') as pw_changed:
  172. user.save()
  173. self.assertEqual(pw_changed.call_count, 1)
  174. user.save()
  175. self.assertEqual(pw_changed.call_count, 1)
  176. @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS)
  177. def test_check_password_upgrade(self):
  178. """
  179. password_changed() shouldn't be called if User.check_password()
  180. triggers a hash iteration upgrade.
  181. """
  182. user = User.objects.create_user(username='user', password='foo')
  183. initial_password = user.password
  184. self.assertTrue(user.check_password('foo'))
  185. hasher = get_hasher('default')
  186. self.assertEqual('pbkdf2_sha256', hasher.algorithm)
  187. old_iterations = hasher.iterations
  188. try:
  189. # Upgrade the password iterations
  190. hasher.iterations = old_iterations + 1
  191. with mock.patch('django.contrib.auth.password_validation.password_changed') as pw_changed:
  192. user.check_password('foo')
  193. self.assertEqual(pw_changed.call_count, 0)
  194. self.assertNotEqual(initial_password, user.password)
  195. finally:
  196. hasher.iterations = old_iterations
  197. class IsActiveTestCase(TestCase):
  198. """
  199. Tests the behavior of the guaranteed is_active attribute
  200. """
  201. def test_builtin_user_isactive(self):
  202. user = User.objects.create(username='foo', email='foo@bar.com')
  203. # is_active is true by default
  204. self.assertIs(user.is_active, True)
  205. user.is_active = False
  206. user.save()
  207. user_fetched = User.objects.get(pk=user.pk)
  208. # the is_active flag is saved
  209. self.assertFalse(user_fetched.is_active)
  210. @override_settings(AUTH_USER_MODEL='auth_tests.IsActiveTestUser1')
  211. def test_is_active_field_default(self):
  212. """
  213. tests that the default value for is_active is provided
  214. """
  215. UserModel = get_user_model()
  216. user = UserModel(username='foo')
  217. self.assertIs(user.is_active, True)
  218. # you can set the attribute - but it will not save
  219. user.is_active = False
  220. # there should be no problem saving - but the attribute is not saved
  221. user.save()
  222. user_fetched = UserModel._default_manager.get(pk=user.pk)
  223. # the attribute is always true for newly retrieved instance
  224. self.assertIs(user_fetched.is_active, True)
  225. class TestCreateSuperUserSignals(TestCase):
  226. """
  227. Simple test case for ticket #20541
  228. """
  229. def post_save_listener(self, *args, **kwargs):
  230. self.signals_count += 1
  231. def setUp(self):
  232. self.signals_count = 0
  233. post_save.connect(self.post_save_listener, sender=User)
  234. def tearDown(self):
  235. post_save.disconnect(self.post_save_listener, sender=User)
  236. def test_create_user(self):
  237. User.objects.create_user("JohnDoe")
  238. self.assertEqual(self.signals_count, 1)
  239. def test_create_superuser(self):
  240. User.objects.create_superuser("JohnDoe", "mail@example.com", "1")
  241. self.assertEqual(self.signals_count, 1)