From 3560ef043e5c70de30ca7d5d7d6d09c150eb6eb4 Mon Sep 17 00:00:00 2001 From: Matt Robenolt Date: Thu, 14 Nov 2013 11:55:13 -0800 Subject: [PATCH] Propagate get_user_model exception from get_user Fixes #21439 --- django/contrib/auth/backends.py | 2 +- .../contrib/auth/tests/test_auth_backends.py | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py index 7304ccd14e..a39a701888 100644 --- a/django/contrib/auth/backends.py +++ b/django/contrib/auth/backends.py @@ -64,8 +64,8 @@ class ModelBackend(object): return False def get_user(self, user_id): + UserModel = get_user_model() try: - UserModel = get_user_model() return UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None diff --git a/django/contrib/auth/tests/test_auth_backends.py b/django/contrib/auth/tests/test_auth_backends.py index d73a1f36f2..757ad290a7 100644 --- a/django/contrib/auth/tests/test_auth_backends.py +++ b/django/contrib/auth/tests/test_auth_backends.py @@ -508,3 +508,27 @@ class TypeErrorBackendTest(TestCase): @override_settings(AUTHENTICATION_BACKENDS=(backend, )) def test_type_error_raised(self): self.assertRaises(TypeError, authenticate, username='test', password='test') + + +@skipIfCustomUser +class ImproperlyConfiguredUserModelTest(TestCase): + """ + Tests that an exception from within get_user_model is propagated and doesn't + raise an UnboundLocalError. + + Regression test for ticket #21439 + """ + def setUp(self): + self.user1 = User.objects.create_user('test', 'test@example.com', 'test') + self.client.login( + username='test', + password='test' + ) + + @override_settings(AUTH_USER_MODEL='thismodel.doesntexist') + def test_does_not_shadow_exception(self): + # Prepare a request object + request = HttpRequest() + request.session = self.client.session + + self.assertRaises(ImproperlyConfigured, get_user, request)