diff --git a/django/test/client.py b/django/test/client.py index b1421901e27..47232ef1461 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -431,12 +431,14 @@ class Client(object): def logout(self): """ - Removes the authenticated user's cookies. + Removes the authenticated user's cookies and session object. Causes the authenticated user to be logged out. """ session = import_module(settings.SESSION_ENGINE).SessionStore() - session.delete(session_key=self.cookies[settings.SESSION_COOKIE_NAME].value) + session_cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) + if session_cookie: + session.delete(session_key=session_cookie.value) self.cookies = SimpleCookie() def _handle_redirects(self, response): diff --git a/tests/modeltests/test_client/models.py b/tests/modeltests/test_client/models.py index dfc84169f39..c8f1d427259 100644 --- a/tests/modeltests/test_client/models.py +++ b/tests/modeltests/test_client/models.py @@ -423,4 +423,3 @@ class ClientTest(TestCase): self.assertEqual(mail.outbox[1].from_email, 'from@example.com') self.assertEqual(mail.outbox[1].to[0], 'second@example.com') self.assertEqual(mail.outbox[1].to[1], 'third@example.com') - diff --git a/tests/regressiontests/test_client_regress/models.py b/tests/regressiontests/test_client_regress/models.py index 5d650923a4a..71d6a149d08 100644 --- a/tests/regressiontests/test_client_regress/models.py +++ b/tests/regressiontests/test_client_regress/models.py @@ -505,6 +505,14 @@ class SessionTests(TestCase): self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'YES') + def test_logout(self): + """Logout should work whether the user is logged in or not (#9978).""" + self.client.logout() + login = self.client.login(username='testclient',password='password') + self.failUnless(login, 'Could not log in') + self.client.logout() + self.client.logout() + class RequestMethodTests(TestCase): def test_get(self): "Request a view via request method GET"