Ticket #16708: cached_db_exists_check_cache_v2.diff

File cached_db_exists_check_cache_v2.diff, 2.5 KB (added by jvale, 4 years ago)
  • django/contrib/sessions/tests.py

     
    1212from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession
    1313from django.contrib.sessions.models import Session
    1414from django.contrib.sessions.middleware import SessionMiddleware
     15from django.core.cache import cache
    1516from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
    1617from django.http import HttpResponse
    1718from django.test import TestCase, RequestFactory
     
    276277        self.assertEqual(self.session['y'], 2)
    277278
    278279
     280class MockDatabaseStore(DatabaseSession):
     281    db_exists_called = False
     282    db_exists_call_count = 0
     283
     284    def exists(self, session_key):
     285        self.db_exists_called = True
     286        self.db_exists_call_count += 1
     287        return super(MockDatabaseStore, self).exists(session_key)
     288
     289class MockCacheDBSession(CacheDBSession, MockDatabaseStore):
     290    pass
     291
    279292class CacheDBSessionTests(SessionTestsMixin, TestCase):
    280293
    281     backend = CacheDBSession
     294    backend = MockCacheDBSession
    282295
     296    def test_exists_cached(self):
     297        self.session['cat'] = "dog"
     298        self.session.save()
     299
     300        self.assertTrue(self.session.exists(self.session.session_key))
     301
     302        self.assertTrue(self.session.db_exists_called)
     303        self.assertEqual(self.session.db_exists_call_count, 1)
     304
     305    def test_exists_not_cached(self):
     306        self.session['cat'] = "dog"
     307        self.session.save()
     308
     309        cache.delete(self.session.session_key)
     310
     311        self.assertTrue(self.session.exists(self.session.session_key))
     312
     313        self.assertTrue(self.session.db_exists_called)
     314        self.assertEqual(self.session.db_exists_call_count, 2)
     315
    283316# Don't need DB flushing for these tests, so can use unittest.TestCase as base class
    284317class FileSessionTests(SessionTestsMixin, unittest.TestCase):
    285318
  • django/contrib/sessions/backends/cached_db.py

     
    2222        return data
    2323
    2424    def exists(self, session_key):
     25        if cache.get(session_key) is not None:
     26            return True
    2527        return super(SessionStore, self).exists(session_key)
    2628
    2729    def save(self, must_create=False):
Back to Top