sudo_testutils.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from django.contrib.auth.models import AbstractBaseUser, AnonymousUser, User
  2. from django.db import models
  3. from django.test import RequestFactory, TestCase
  4. class StubPasswordBackend:
  5. """Stub backend
  6. Always authenticates when the password matches self.password
  7. """
  8. password = "stub"
  9. def authenticate(self, request, username, password):
  10. if password == self.password:
  11. return User()
  12. class FooPasswordBackend(StubPasswordBackend):
  13. password = "foo"
  14. class BaseTestCase(TestCase):
  15. def setUp(self):
  16. self.request = self.get("/foo")
  17. self.request.session = {}
  18. self.setUser(AnonymousUser())
  19. def get(self, *args, **kwargs):
  20. return RequestFactory().get(*args, **kwargs)
  21. def post(self, *args, **kwargs):
  22. return RequestFactory().post(*args, **kwargs)
  23. def setUser(self, user):
  24. self.user = self.request.user = user
  25. def login(self, user_class=User):
  26. user = user_class()
  27. self.setUser(user)
  28. class EmailUser(AbstractBaseUser):
  29. email = models.CharField(max_length=254, unique=True)
  30. USERNAME_FIELD = "email"
  31. def get_username(self):
  32. return self.email
  33. class Meta:
  34. app_label = "sudo_tests"