From 867d287b3acfdb6b7de0f193b86b93ec52d034e5 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Tue, 18 Aug 2015 17:57:01 -0400 Subject: [PATCH] Added a test to ensure empty sessions are saved. --- tests/sessions_tests/tests.py | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py index 713ff9e553..76e625aa76 100644 --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -695,6 +695,45 @@ class SessionMiddlewareTests(TestCase): # The session is accessed so "Vary: Cookie" should be set. self.assertEqual(response['Vary'], 'Cookie') + def test_empty_session_saved(self): + """" + If a session is emptied of data but still has a key, it should still + be updated. + """ + request = RequestFactory().get('/') + response = HttpResponse('Session test') + middleware = SessionMiddleware() + + # Set a session key and some data. + middleware.process_request(request) + request.session['foo'] = 'bar' + # Handle the response through the middleware. + response = middleware.process_response(request, response) + self.assertEqual(tuple(request.session.items()), (('foo', 'bar'),)) + # A cookie should be set, along with Vary: Cookie. + self.assertIn( + 'Set-Cookie: sessionid=%s' % request.session.session_key, + str(response.cookies) + ) + self.assertEqual(response['Vary'], 'Cookie') + + # Empty the session data. + del request.session['foo'] + # Handle the response through the middleware. + response = HttpResponse('Session test') + response = middleware.process_response(request, response) + self.assertEqual(dict(request.session.values()), {}) + session = Session.objects.get(session_key=request.session.session_key) + self.assertEqual(session.get_decoded(), {}) + # While the session is empty, it hasn't been flushed so a cookie should + # still be set, along with Vary: Cookie. + self.assertGreater(len(request.session.session_key), 8) + self.assertIn( + 'Set-Cookie: sessionid=%s' % request.session.session_key, + str(response.cookies) + ) + self.assertEqual(response['Vary'], 'Cookie') + # Don't need DB flushing for these tests, so can use unittest.TestCase as base class class CookieSessionTests(SessionTestsMixin, unittest.TestCase):