Commit 867d287b authored by Tim Graham's avatar Tim Graham
Browse files

Added a test to ensure empty sessions are saved.

parent 333cbdcd
Loading
Loading
Loading
Loading
+39 −0
Original line number Diff line number Diff line
@@ -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):