test_models.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. from django.contrib.auth import get_user_model
  2. from django.contrib.auth.models import (
  3. AbstractUser, Group, Permission, User, UserManager,
  4. )
  5. # Needed so model is installed when tests are run independently:
  6. from django.contrib.auth.tests.custom_user import IsActiveTestUser1 # NOQA
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.core import mail
  9. from django.db.models.signals import post_save
  10. from django.test import TestCase, override_settings
  11. @override_settings(USE_TZ=False)
  12. class NaturalKeysTestCase(TestCase):
  13. fixtures = ['authtestdata.json']
  14. def test_user_natural_key(self):
  15. staff_user = User.objects.get(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. @override_settings(USE_TZ=False)
  22. class LoadDataWithoutNaturalKeysTestCase(TestCase):
  23. fixtures = ['regular.json']
  24. def test_user_is_created_and_added_to_group(self):
  25. user = User.objects.get(username='my_username')
  26. group = Group.objects.get(name='my_group')
  27. self.assertEqual(group, user.groups.get())
  28. @override_settings(USE_TZ=False)
  29. class LoadDataWithNaturalKeysTestCase(TestCase):
  30. fixtures = ['natural.json']
  31. def test_user_is_created_and_added_to_group(self):
  32. user = User.objects.get(username='my_username')
  33. group = Group.objects.get(name='my_group')
  34. self.assertEqual(group, user.groups.get())
  35. class LoadDataWithNaturalKeysAndMultipleDatabasesTestCase(TestCase):
  36. multi_db = True
  37. def test_load_data_with_user_permissions(self):
  38. # Create test contenttypes for both databases
  39. default_objects = [
  40. ContentType.objects.db_manager('default').create(
  41. model='examplemodela',
  42. app_label='app_a',
  43. ),
  44. ContentType.objects.db_manager('default').create(
  45. model='examplemodelb',
  46. app_label='app_b',
  47. ),
  48. ]
  49. other_objects = [
  50. ContentType.objects.db_manager('other').create(
  51. model='examplemodelb',
  52. app_label='app_b',
  53. ),
  54. ContentType.objects.db_manager('other').create(
  55. model='examplemodela',
  56. app_label='app_a',
  57. ),
  58. ]
  59. # Now we create the test UserPermission
  60. Permission.objects.db_manager("default").create(
  61. name="Can delete example model b",
  62. codename="delete_examplemodelb",
  63. content_type=default_objects[1],
  64. )
  65. Permission.objects.db_manager("other").create(
  66. name="Can delete example model b",
  67. codename="delete_examplemodelb",
  68. content_type=other_objects[0],
  69. )
  70. perm_default = Permission.objects.get_by_natural_key(
  71. 'delete_examplemodelb',
  72. 'app_b',
  73. 'examplemodelb',
  74. )
  75. perm_other = Permission.objects.db_manager('other').get_by_natural_key(
  76. 'delete_examplemodelb',
  77. 'app_b',
  78. 'examplemodelb',
  79. )
  80. self.assertEqual(perm_default.content_type_id, default_objects[1].id)
  81. self.assertEqual(perm_other.content_type_id, other_objects[0].id)
  82. class UserManagerTestCase(TestCase):
  83. def test_create_user(self):
  84. email_lowercase = 'normal@normal.com'
  85. user = User.objects.create_user('user', email_lowercase)
  86. self.assertEqual(user.email, email_lowercase)
  87. self.assertEqual(user.username, 'user')
  88. self.assertFalse(user.has_usable_password())
  89. def test_create_user_email_domain_normalize_rfc3696(self):
  90. # According to http://tools.ietf.org/html/rfc3696#section-3
  91. # the "@" symbol can be part of the local part of an email address
  92. returned = UserManager.normalize_email(r'Abc\@DEF@EXAMPLE.com')
  93. self.assertEqual(returned, r'Abc\@DEF@example.com')
  94. def test_create_user_email_domain_normalize(self):
  95. returned = UserManager.normalize_email('normal@DOMAIN.COM')
  96. self.assertEqual(returned, 'normal@domain.com')
  97. def test_create_user_email_domain_normalize_with_whitespace(self):
  98. returned = UserManager.normalize_email('email\ with_whitespace@D.COM')
  99. self.assertEqual(returned, 'email\ with_whitespace@d.com')
  100. def test_empty_username(self):
  101. self.assertRaisesMessage(
  102. ValueError,
  103. 'The given username must be set',
  104. User.objects.create_user, username=''
  105. )
  106. class AbstractUserTestCase(TestCase):
  107. def test_email_user(self):
  108. # valid send_mail parameters
  109. kwargs = {
  110. "fail_silently": False,
  111. "auth_user": None,
  112. "auth_password": None,
  113. "connection": None,
  114. "html_message": None,
  115. }
  116. abstract_user = AbstractUser(email='foo@bar.com')
  117. abstract_user.email_user(subject="Subject here",
  118. message="This is a message", from_email="from@domain.com", **kwargs)
  119. # Test that one message has been sent.
  120. self.assertEqual(len(mail.outbox), 1)
  121. # Verify that test email contains the correct attributes:
  122. message = mail.outbox[0]
  123. self.assertEqual(message.subject, "Subject here")
  124. self.assertEqual(message.body, "This is a message")
  125. self.assertEqual(message.from_email, "from@domain.com")
  126. self.assertEqual(message.to, [abstract_user.email])
  127. def test_last_login_default(self):
  128. user1 = User.objects.create(username='user1')
  129. self.assertIsNone(user1.last_login)
  130. user2 = User.objects.create_user(username='user2')
  131. self.assertIsNone(user2.last_login)
  132. class IsActiveTestCase(TestCase):
  133. """
  134. Tests the behavior of the guaranteed is_active attribute
  135. """
  136. def test_builtin_user_isactive(self):
  137. user = User.objects.create(username='foo', email='foo@bar.com')
  138. # is_active is true by default
  139. self.assertEqual(user.is_active, True)
  140. user.is_active = False
  141. user.save()
  142. user_fetched = User.objects.get(pk=user.pk)
  143. # the is_active flag is saved
  144. self.assertFalse(user_fetched.is_active)
  145. @override_settings(AUTH_USER_MODEL='auth.IsActiveTestUser1')
  146. def test_is_active_field_default(self):
  147. """
  148. tests that the default value for is_active is provided
  149. """
  150. UserModel = get_user_model()
  151. user = UserModel(username='foo')
  152. self.assertEqual(user.is_active, True)
  153. # you can set the attribute - but it will not save
  154. user.is_active = False
  155. # there should be no problem saving - but the attribute is not saved
  156. user.save()
  157. user_fetched = UserModel._default_manager.get(pk=user.pk)
  158. # the attribute is always true for newly retrieved instance
  159. self.assertEqual(user_fetched.is_active, True)
  160. class TestCreateSuperUserSignals(TestCase):
  161. """
  162. Simple test case for ticket #20541
  163. """
  164. def post_save_listener(self, *args, **kwargs):
  165. self.signals_count += 1
  166. def setUp(self):
  167. self.signals_count = 0
  168. post_save.connect(self.post_save_listener, sender=User)
  169. def tearDown(self):
  170. post_save.disconnect(self.post_save_listener, sender=User)
  171. def test_create_user(self):
  172. User.objects.create_user("JohnDoe")
  173. self.assertEqual(self.signals_count, 1)
  174. def test_create_superuser(self):
  175. User.objects.create_superuser("JohnDoe", "mail@example.com", "1")
  176. self.assertEqual(self.signals_count, 1)