From 47744a0a4ed0b9e2d3f52de65abcf6cef9a14e31 Mon Sep 17 00:00:00 2001 From: Anton Samarchyan Date: Wed, 30 Nov 2016 13:37:07 -0500 Subject: [PATCH] Fixed #27542 -- Made Client.force_login() skip auth backends without get_user(). --- django/test/client.py | 8 +++++++- tests/test_client/auth_backends.py | 4 ++++ tests/test_client/tests.py | 11 +++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/django/test/client.py b/django/test/client.py index d27d462689..129377c232 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -631,8 +631,14 @@ class Client(RequestFactory): return False def force_login(self, user, backend=None): + def get_backend(): + from django.contrib.auth import load_backend + for backend_path in settings.AUTHENTICATION_BACKENDS: + backend = load_backend(backend_path) + if hasattr(backend, 'get_user'): + return backend_path if backend is None: - backend = settings.AUTHENTICATION_BACKENDS[0] + backend = get_backend() user.backend = backend self._login(user, backend) diff --git a/tests/test_client/auth_backends.py b/tests/test_client/auth_backends.py index c886dce336..1bb1d96eeb 100644 --- a/tests/test_client/auth_backends.py +++ b/tests/test_client/auth_backends.py @@ -3,3 +3,7 @@ from django.contrib.auth.backends import ModelBackend class TestClientBackend(ModelBackend): pass + + +class BackendWithoutGetUserMethod(object): + pass diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index d3eb782347..a499ee7fce 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -549,6 +549,17 @@ class ClientTest(TestCase): self.assertEqual(response.context['user'].username, 'testclient') self.assertEqual(self.u1.backend, 'django.contrib.auth.backends.ModelBackend') + @override_settings(AUTHENTICATION_BACKENDS=[ + 'test_client.auth_backends.BackendWithoutGetUserMethod', + 'django.contrib.auth.backends.ModelBackend', + ]) + def test_force_login_with_backend_missing_get_user(self): + """ + force_login() skips auth backends without a get_user() method. + """ + self.client.force_login(self.u1) + self.assertEqual(self.u1.backend, 'django.contrib.auth.backends.ModelBackend') + @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies") def test_logout_cookie_sessions(self): self.test_logout()