| 6 | from unittest import TestCase |
| 7 | from django.contrib import auth |
| 8 | from django.http import HttpRequest |
| 9 | from django.contrib.auth.models import User, AnonymousUser |
| 10 | from django.conf import settings |
| 11 | |
| 12 | class StubBackend: |
| 13 | TestUser_1 = User() |
| 14 | def get_user(self, id): |
| 15 | if id == 1: |
| 16 | return StubBackend.TestUser_1 |
| 17 | |
| 18 | class GetUserTests(TestCase): |
| 19 | def load_backend(self, backend_path): |
| 20 | if backend_path == "some.backend": |
| 21 | return StubBackend() |
| 22 | |
| 23 | def setUp(self): |
| 24 | self.old_load_backend = auth.load_backend |
| 25 | self.old_auth_backends = settings.AUTHENTICATION_BACKENDS |
| 26 | |
| 27 | auth.load_backend = self.load_backend |
| 28 | settings.AUTHENTICATION_BACKENDS = ("some.backend",) |
| 29 | |
| 30 | self.request = HttpRequest() |
| 31 | self.request.session = {} |
| 32 | |
| 33 | def set_up_session(self, uid, backend): |
| 34 | self.request.session[auth.SESSION_KEY] = uid |
| 35 | self.request.session[auth.BACKEND_SESSION_KEY] = backend |
| 36 | |
| 37 | def tearDown(self): |
| 38 | auth.load_backend = self.old_load_backend |
| 39 | settings.AUTHENTICATION_BACKENDS = self.old_auth_backends |
| 40 | |
| 41 | def test_user_loaded_with_backend(self): |
| 42 | self.set_up_session(uid=1, backend="some.backend") |
| 43 | user = auth.get_user(self.request) |
| 44 | self.assertEquals(user, StubBackend.TestUser_1) |
| 45 | |
| 46 | def test_user_loaded_with_backend_invalid_uid(self): |
| 47 | self.set_up_session(uid='INVALID', backend="some.backend") |
| 48 | user = auth.get_user(self.request) |
| 49 | self.assert_(isinstance(user,AnonymousUser)) |
| 50 | |
| 51 | def test_user_loaded_with_invalid_backend(self): |
| 52 | self.set_up_session(uid=1, backend="invalid.backend") |
| 53 | user = auth.get_user(self.request) |
| 54 | self.assert_(isinstance(user,AnonymousUser)) |
| 55 | |