test_handlers.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from django.contrib.auth.handlers.modwsgi import (
  2. check_password, groups_for_user,
  3. )
  4. from django.contrib.auth.models import Group, User
  5. from django.test import TransactionTestCase, override_settings
  6. from .models import CustomUser
  7. # This must be a TransactionTestCase because the WSGI auth handler performs
  8. # its own transaction management.
  9. class ModWsgiHandlerTestCase(TransactionTestCase):
  10. """
  11. Tests for the mod_wsgi authentication handler
  12. """
  13. available_apps = [
  14. 'django.contrib.auth',
  15. 'django.contrib.contenttypes',
  16. 'auth_tests',
  17. ]
  18. def test_check_password(self):
  19. """
  20. check_password() returns the correct values as per
  21. https://modwsgi.readthedocs.io/en/develop/user-guides/access-control-mechanisms.html#apache-authentication-provider
  22. """
  23. User.objects.create_user('test', 'test@example.com', 'test')
  24. # User not in database
  25. self.assertIsNone(check_password({}, 'unknown', ''))
  26. # Valid user with correct password
  27. self.assertTrue(check_password({}, 'test', 'test'))
  28. # correct password, but user is inactive
  29. User.objects.filter(username='test').update(is_active=False)
  30. self.assertFalse(check_password({}, 'test', 'test'))
  31. # Valid user with incorrect password
  32. self.assertFalse(check_password({}, 'test', 'incorrect'))
  33. @override_settings(AUTH_USER_MODEL='auth_tests.CustomUser')
  34. def test_check_password_custom_user(self):
  35. """
  36. check_password() returns the correct values as per
  37. https://modwsgi.readthedocs.io/en/develop/user-guides/access-control-mechanisms.html#apache-authentication-provider
  38. with a custom user installed.
  39. """
  40. CustomUser._default_manager.create_user('test@example.com', '1990-01-01', 'test')
  41. # User not in database
  42. self.assertIsNone(check_password({}, 'unknown', ''))
  43. # Valid user with correct password'
  44. self.assertTrue(check_password({}, 'test@example.com', 'test'))
  45. # Valid user with incorrect password
  46. self.assertFalse(check_password({}, 'test@example.com', 'incorrect'))
  47. def test_groups_for_user(self):
  48. """
  49. groups_for_user() returns correct values as per
  50. https://modwsgi.readthedocs.io/en/develop/user-guides/access-control-mechanisms.html#apache-group-authorisation
  51. """
  52. user1 = User.objects.create_user('test', 'test@example.com', 'test')
  53. User.objects.create_user('test1', 'test1@example.com', 'test1')
  54. group = Group.objects.create(name='test_group')
  55. user1.groups.add(group)
  56. # User not in database
  57. self.assertEqual(groups_for_user({}, 'unknown'), [])
  58. self.assertEqual(groups_for_user({}, 'test'), [b'test_group'])
  59. self.assertEqual(groups_for_user({}, 'test1'), [])