2006-08-27 21:59:47 +08:00
|
|
|
# Unit tests for cache framework
|
|
|
|
# Uses whatever cache backend is set in the test settings file.
|
2015-01-28 20:35:27 +08:00
|
|
|
import copy
|
2016-06-02 03:29:24 +08:00
|
|
|
import io
|
2008-08-02 13:56:57 +08:00
|
|
|
import os
|
2017-01-07 19:11:46 +08:00
|
|
|
import pickle
|
2011-08-23 11:51:10 +08:00
|
|
|
import re
|
2013-10-19 06:49:24 +08:00
|
|
|
import shutil
|
2020-08-21 18:43:45 +08:00
|
|
|
import sys
|
2008-08-02 13:56:57 +08:00
|
|
|
import tempfile
|
2013-10-19 06:49:24 +08:00
|
|
|
import threading
|
2007-12-05 02:03:56 +08:00
|
|
|
import time
|
2013-07-02 04:49:07 +08:00
|
|
|
import unittest
|
2019-11-06 17:01:01 +08:00
|
|
|
from pathlib import Path
|
2020-08-21 18:43:45 +08:00
|
|
|
from unittest import mock, skipIf
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2009-03-11 21:27:03 +08:00
|
|
|
from django.conf import settings
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core import management, signals
|
|
|
|
from django.core.cache import (
|
2017-10-22 23:30:42 +08:00
|
|
|
DEFAULT_CACHE_ALIAS, CacheHandler, CacheKeyWarning, InvalidCacheKey, cache,
|
|
|
|
caches,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
2019-12-15 01:03:24 +08:00
|
|
|
from django.core.cache.backends.base import InvalidCacheBackendError
|
2021-05-24 08:01:50 +08:00
|
|
|
from django.core.cache.backends.redis import RedisCacheClient
|
2013-02-24 19:58:02 +08:00
|
|
|
from django.core.cache.utils import make_template_fragment_key
|
2016-09-15 02:25:09 +08:00
|
|
|
from django.db import close_old_connections, connection, connections
|
2021-05-02 16:42:23 +08:00
|
|
|
from django.db.backends.utils import CursorWrapper
|
2016-09-12 22:19:36 +08:00
|
|
|
from django.http import (
|
|
|
|
HttpRequest, HttpResponse, HttpResponseNotModified, StreamingHttpResponse,
|
|
|
|
)
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.middleware.cache import (
|
|
|
|
CacheMiddleware, FetchFromCacheMiddleware, UpdateCacheMiddleware,
|
|
|
|
)
|
2014-04-21 04:10:32 +08:00
|
|
|
from django.middleware.csrf import CsrfViewMiddleware
|
2015-01-10 05:59:00 +08:00
|
|
|
from django.template import engines
|
2014-12-03 06:23:51 +08:00
|
|
|
from django.template.context_processors import csrf
|
2011-09-08 21:25:31 +08:00
|
|
|
from django.template.response import TemplateResponse
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.test import (
|
2016-04-03 18:15:10 +08:00
|
|
|
RequestFactory, SimpleTestCase, TestCase, TransactionTestCase,
|
2021-09-16 15:37:03 +08:00
|
|
|
override_settings,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
2014-10-19 02:03:10 +08:00
|
|
|
from django.test.signals import setting_changed
|
2021-05-26 00:31:26 +08:00
|
|
|
from django.test.utils import CaptureQueriesContext
|
2017-01-07 19:11:46 +08:00
|
|
|
from django.utils import timezone, translation
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.cache import (
|
2017-09-03 09:09:22 +08:00
|
|
|
get_cache_key, learn_cache_key, patch_cache_control, patch_vary_headers,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
2018-02-06 13:44:53 +08:00
|
|
|
from django.views.decorators.cache import cache_control, cache_page
|
2011-02-17 11:50:55 +08:00
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from .models import Poll, expensive_calculation
|
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2007-07-15 14:24:54 +08:00
|
|
|
# functions/classes for complex data type tests
|
2006-08-27 21:59:47 +08:00
|
|
|
def f():
|
|
|
|
return 42
|
2011-10-27 04:55:36 +08:00
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2006-08-27 21:59:47 +08:00
|
|
|
class C:
|
|
|
|
def m(n):
|
|
|
|
return 24
|
|
|
|
|
2011-10-27 04:55:36 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Unpicklable:
|
2013-11-24 00:50:28 +08:00
|
|
|
def __getstate__(self):
|
|
|
|
raise pickle.PickleError()
|
|
|
|
|
|
|
|
|
2019-09-27 01:06:35 +08:00
|
|
|
def empty_response(request):
|
|
|
|
return HttpResponse()
|
|
|
|
|
|
|
|
|
2017-10-30 23:30:00 +08:00
|
|
|
KEY_ERRORS_WITH_MEMCACHED_MSG = (
|
|
|
|
'Cache key contains characters that will cause errors if used with '
|
|
|
|
'memcached: %r'
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
@override_settings(CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
|
|
|
|
}
|
|
|
|
})
|
2015-04-18 05:38:20 +08:00
|
|
|
class DummyCacheTests(SimpleTestCase):
|
2009-03-11 21:27:03 +08:00
|
|
|
# The Dummy cache backend doesn't really behave like a test backend,
|
2013-10-19 06:49:24 +08:00
|
|
|
# so it has its own test case.
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_simple(self):
|
|
|
|
"Dummy cache backend ignores cache set calls"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("key", "value")
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("key"))
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_add(self):
|
|
|
|
"Add doesn't do anything in dummy cache backend"
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add("addkey1", "value"), True)
|
|
|
|
self.assertIs(cache.add("addkey1", "newvalue"), True)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("addkey1"))
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_non_existent(self):
|
2017-02-03 09:43:21 +08:00
|
|
|
"Nonexistent keys aren't found in the dummy cache backend"
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("does_not_exist"))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!")
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_get_many(self):
|
|
|
|
"get_many returns nothing for the dummy cache backend"
|
2018-08-16 21:02:21 +08:00
|
|
|
cache.set_many({'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'})
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get_many(['a', 'c', 'd']), {})
|
|
|
|
self.assertEqual(cache.get_many(['a', 'b', 'e']), {})
|
2009-03-11 21:27:03 +08:00
|
|
|
|
2017-10-30 23:30:00 +08:00
|
|
|
def test_get_many_invalid_key(self):
|
2020-01-30 17:35:02 +08:00
|
|
|
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ':1:key with spaces'
|
|
|
|
with self.assertWarnsMessage(CacheKeyWarning, msg):
|
2017-10-30 23:30:00 +08:00
|
|
|
cache.get_many(['key with spaces'])
|
|
|
|
|
2009-03-11 21:27:03 +08:00
|
|
|
def test_delete(self):
|
|
|
|
"Cache deletion is transparently ignored on the dummy cache backend"
|
2018-08-16 21:02:21 +08:00
|
|
|
cache.set_many({'key1': 'spam', 'key2': 'eggs'})
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("key1"))
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.delete("key1"), False)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("key1"))
|
|
|
|
self.assertIsNone(cache.get("key2"))
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_has_key(self):
|
|
|
|
"The has_key method doesn't ever return True for the dummy cache backend"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("hello1", "goodbye1")
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key("hello1"), False)
|
|
|
|
self.assertIs(cache.has_key("goodbye1"), False)
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_in(self):
|
|
|
|
"The in operator doesn't ever return True for the dummy cache backend"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("hello2", "goodbye2")
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertNotIn("hello2", cache)
|
|
|
|
self.assertNotIn("goodbye2", cache)
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_incr(self):
|
|
|
|
"Dummy cache values can't be incremented"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer', 42)
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr('answer')
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr('does_not_exist')
|
2021-08-31 13:25:16 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr('does_not_exist', -1)
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_decr(self):
|
|
|
|
"Dummy cache values can't be decremented"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer', 42)
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.decr('answer')
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.decr('does_not_exist')
|
2021-08-31 13:25:16 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.decr('does_not_exist', -1)
|
2009-03-11 21:27:03 +08:00
|
|
|
|
2018-04-28 05:48:35 +08:00
|
|
|
def test_touch(self):
|
|
|
|
"""Dummy cache can't do touch()."""
|
|
|
|
self.assertIs(cache.touch('whatever'), False)
|
|
|
|
|
2009-03-11 21:27:03 +08:00
|
|
|
def test_data_types(self):
|
|
|
|
"All data types are ignored equally by the dummy cache"
|
|
|
|
stuff = {
|
2013-10-27 09:27:42 +08:00
|
|
|
'string': 'this is a string',
|
|
|
|
'int': 42,
|
|
|
|
'list': [1, 2, 3, 4],
|
|
|
|
'tuple': (1, 2, 3, 4),
|
|
|
|
'dict': {'A': 1, 'B': 2},
|
|
|
|
'function': f,
|
|
|
|
'class': C,
|
2009-03-11 21:27:03 +08:00
|
|
|
}
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("stuff", stuff)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("stuff"))
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_expiration(self):
|
|
|
|
"Expiration has no effect on the dummy cache"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('expire1', 'very quickly', 1)
|
|
|
|
cache.set('expire2', 'very quickly', 1)
|
|
|
|
cache.set('expire3', 'very quickly', 1)
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
time.sleep(2)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("expire1"))
|
2009-03-11 21:27:03 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add("expire2", "newvalue"), True)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("expire2"))
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key("expire3"), False)
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_unicode(self):
|
|
|
|
"Unicode values are ignored by the dummy cache"
|
|
|
|
stuff = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'ascii': 'ascii_value',
|
|
|
|
'unicode_ascii': 'Iñtërnâtiônàlizætiøn1',
|
|
|
|
'Iñtërnâtiônàlizætiøn': 'Iñtërnâtiônàlizætiøn2',
|
2013-10-27 09:27:42 +08:00
|
|
|
'ascii2': {'x': 1}
|
2013-10-18 17:02:43 +08:00
|
|
|
}
|
2009-03-11 21:27:03 +08:00
|
|
|
for (key, value) in stuff.items():
|
2017-03-08 05:00:43 +08:00
|
|
|
with self.subTest(key=key):
|
|
|
|
cache.set(key, value)
|
|
|
|
self.assertIsNone(cache.get(key))
|
2009-03-11 21:27:03 +08:00
|
|
|
|
2010-01-27 16:21:35 +08:00
|
|
|
def test_set_many(self):
|
|
|
|
"set_many does nothing for the dummy cache backend"
|
2017-10-30 23:25:33 +08:00
|
|
|
self.assertEqual(cache.set_many({'a': 1, 'b': 2}), [])
|
|
|
|
self.assertEqual(cache.set_many({'a': 1, 'b': 2}, timeout=2, version='1'), [])
|
2010-01-27 16:21:35 +08:00
|
|
|
|
2017-10-30 23:30:00 +08:00
|
|
|
def test_set_many_invalid_key(self):
|
2020-01-30 17:35:02 +08:00
|
|
|
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ':1:key with spaces'
|
|
|
|
with self.assertWarnsMessage(CacheKeyWarning, msg):
|
2017-10-30 23:30:00 +08:00
|
|
|
cache.set_many({'key with spaces': 'foo'})
|
|
|
|
|
2010-01-27 16:21:35 +08:00
|
|
|
def test_delete_many(self):
|
|
|
|
"delete_many does nothing for the dummy cache backend"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.delete_many(['a', 'b'])
|
2010-01-27 16:21:35 +08:00
|
|
|
|
2017-10-30 23:30:00 +08:00
|
|
|
def test_delete_many_invalid_key(self):
|
2020-01-30 17:35:02 +08:00
|
|
|
msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ':1:key with spaces'
|
|
|
|
with self.assertWarnsMessage(CacheKeyWarning, msg):
|
2021-08-27 03:19:36 +08:00
|
|
|
cache.delete_many(['key with spaces'])
|
2017-10-30 23:30:00 +08:00
|
|
|
|
2010-01-27 16:21:35 +08:00
|
|
|
def test_clear(self):
|
|
|
|
"clear does nothing for the dummy cache backend"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.clear()
|
2010-01-27 16:21:35 +08:00
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
def test_incr_version(self):
|
|
|
|
"Dummy cache versions can't be incremented"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer', 42)
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr_version('answer')
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr_version('does_not_exist')
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
def test_decr_version(self):
|
|
|
|
"Dummy cache versions can't be decremented"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer', 42)
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.decr_version('answer')
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.decr_version('does_not_exist')
|
2013-10-19 06:49:24 +08:00
|
|
|
|
2015-12-02 18:34:31 +08:00
|
|
|
def test_get_or_set(self):
|
|
|
|
self.assertEqual(cache.get_or_set('mykey', 'default'), 'default')
|
2019-10-21 16:55:05 +08:00
|
|
|
self.assertIsNone(cache.get_or_set('mykey', None))
|
2015-12-02 18:34:31 +08:00
|
|
|
|
|
|
|
def test_get_or_set_callable(self):
|
|
|
|
def my_callable():
|
|
|
|
return 'default'
|
|
|
|
|
|
|
|
self.assertEqual(cache.get_or_set('mykey', my_callable), 'default')
|
2016-06-23 02:28:43 +08:00
|
|
|
self.assertEqual(cache.get_or_set('mykey', my_callable()), 'default')
|
2015-12-02 18:34:31 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
|
|
|
|
def custom_key_func(key, key_prefix, version):
|
|
|
|
"A customized cache key function"
|
|
|
|
return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
|
|
|
|
|
|
|
|
|
|
|
|
_caches_setting_base = {
|
|
|
|
'default': {},
|
2013-11-24 17:14:21 +08:00
|
|
|
'prefix': {'KEY_PREFIX': 'cacheprefix{}'.format(os.getpid())},
|
2013-10-19 06:49:24 +08:00
|
|
|
'v2': {'VERSION': 2},
|
|
|
|
'custom_key': {'KEY_FUNCTION': custom_key_func},
|
|
|
|
'custom_key2': {'KEY_FUNCTION': 'cache.tests.custom_key_func'},
|
|
|
|
'cull': {'OPTIONS': {'MAX_ENTRIES': 30}},
|
|
|
|
'zero_cull': {'OPTIONS': {'CULL_FREQUENCY': 0, 'MAX_ENTRIES': 30}},
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2016-08-27 02:29:22 +08:00
|
|
|
def caches_setting_for_tests(base=None, exclude=None, **params):
|
2013-11-24 18:49:32 +08:00
|
|
|
# `base` is used to pull in the memcached config from the original settings,
|
2016-08-27 02:29:22 +08:00
|
|
|
# `exclude` is a set of cache names denoting which `_caches_setting_base` keys
|
|
|
|
# should be omitted.
|
2013-11-24 18:49:32 +08:00
|
|
|
# `params` are test specific overrides and `_caches_settings_base` is the
|
|
|
|
# base config for the tests.
|
|
|
|
# This results in the following search order:
|
|
|
|
# params -> _caches_setting_base -> base
|
|
|
|
base = base or {}
|
2016-08-27 02:29:22 +08:00
|
|
|
exclude = exclude or set()
|
2017-05-28 07:08:46 +08:00
|
|
|
setting = {k: base.copy() for k in _caches_setting_base if k not in exclude}
|
2013-11-24 18:49:32 +08:00
|
|
|
for key, cache_params in setting.items():
|
|
|
|
cache_params.update(_caches_setting_base[key])
|
2013-10-19 06:49:24 +08:00
|
|
|
cache_params.update(params)
|
|
|
|
return setting
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2009-03-11 21:27:03 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class BaseCacheTests:
|
2009-03-11 21:27:03 +08:00
|
|
|
# A common set of tests to apply to all cache backends
|
2018-11-27 03:01:27 +08:00
|
|
|
factory = RequestFactory()
|
2011-12-12 05:04:56 +08:00
|
|
|
|
2020-12-14 18:42:22 +08:00
|
|
|
# Some clients raise custom exceptions when .incr() or .decr() are called
|
|
|
|
# with a non-integer value.
|
|
|
|
incr_decr_type_error = TypeError
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
def tearDown(self):
|
|
|
|
cache.clear()
|
|
|
|
|
2006-08-27 21:59:47 +08:00
|
|
|
def test_simple(self):
|
2009-03-11 21:27:03 +08:00
|
|
|
# Simple cache set/get works
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("key", "value")
|
|
|
|
self.assertEqual(cache.get("key"), "value")
|
2006-08-27 21:59:47 +08:00
|
|
|
|
2019-02-15 08:57:38 +08:00
|
|
|
def test_default_used_when_none_is_set(self):
|
|
|
|
"""If None is cached, get() returns it instead of the default."""
|
|
|
|
cache.set('key_default_none', None)
|
|
|
|
self.assertIsNone(cache.get('key_default_none', default='default'))
|
|
|
|
|
2007-10-20 23:16:34 +08:00
|
|
|
def test_add(self):
|
2009-03-11 21:27:03 +08:00
|
|
|
# A key can be added to a cache
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add("addkey1", "value"), True)
|
|
|
|
self.assertIs(cache.add("addkey1", "newvalue"), False)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get("addkey1"), "value")
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
def test_prefix(self):
|
|
|
|
# Test for same cache key conflicts between shared backend
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('somekey', 'value')
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# should not be set in the prefixed cache
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['prefix'].has_key('somekey'), False)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['prefix'].set('somekey', 'value2')
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('somekey'), 'value')
|
|
|
|
self.assertEqual(caches['prefix'].get('somekey'), 'value2')
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2006-08-27 21:59:47 +08:00
|
|
|
def test_non_existent(self):
|
2017-02-03 09:43:21 +08:00
|
|
|
"""Nonexistent cache keys return as None/default."""
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("does_not_exist"))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!")
|
2006-08-27 21:59:47 +08:00
|
|
|
|
|
|
|
def test_get_many(self):
|
2009-03-11 21:27:03 +08:00
|
|
|
# Multiple cache keys can be returned using get_many
|
2018-08-16 21:02:21 +08:00
|
|
|
cache.set_many({'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'})
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(cache.get_many(['a', 'c', 'd']), {'a': 'a', 'c': 'c', 'd': 'd'})
|
|
|
|
self.assertEqual(cache.get_many(['a', 'b', 'e']), {'a': 'a', 'b': 'b'})
|
2018-07-07 02:03:58 +08:00
|
|
|
self.assertEqual(cache.get_many(iter(['a', 'b', 'e'])), {'a': 'a', 'b': 'b'})
|
2020-12-14 18:42:22 +08:00
|
|
|
cache.set_many({'x': None, 'y': 1})
|
|
|
|
self.assertEqual(cache.get_many(['x', 'y']), {'x': None, 'y': 1})
|
2006-08-27 21:59:47 +08:00
|
|
|
|
|
|
|
def test_delete(self):
|
2009-03-11 21:27:03 +08:00
|
|
|
# Cache keys can be deleted
|
2018-08-16 21:02:21 +08:00
|
|
|
cache.set_many({'key1': 'spam', 'key2': 'eggs'})
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get("key1"), "spam")
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.delete("key1"), True)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("key1"))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get("key2"), "eggs")
|
2006-08-27 21:59:47 +08:00
|
|
|
|
2019-10-08 17:02:40 +08:00
|
|
|
def test_delete_nonexistent(self):
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.delete('nonexistent_key'), False)
|
2019-10-08 17:02:40 +08:00
|
|
|
|
2006-08-27 21:59:47 +08:00
|
|
|
def test_has_key(self):
|
2009-03-11 21:27:03 +08:00
|
|
|
# The cache can be inspected for cache keys
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("hello1", "goodbye1")
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key("hello1"), True)
|
|
|
|
self.assertIs(cache.has_key("goodbye1"), False)
|
2014-05-09 18:23:28 +08:00
|
|
|
cache.set("no_expiry", "here", None)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key("no_expiry"), True)
|
2020-12-14 18:42:22 +08:00
|
|
|
cache.set('null', None)
|
2021-09-16 15:37:03 +08:00
|
|
|
self.assertIs(cache.has_key('null'), True)
|
2006-08-27 21:59:47 +08:00
|
|
|
|
2007-07-15 14:24:54 +08:00
|
|
|
def test_in(self):
|
2011-08-12 22:14:15 +08:00
|
|
|
# The in operator can be used to inspect cache contents
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("hello2", "goodbye2")
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIn("hello2", cache)
|
|
|
|
self.assertNotIn("goodbye2", cache)
|
2020-12-14 18:42:22 +08:00
|
|
|
cache.set('null', None)
|
2021-09-16 15:37:03 +08:00
|
|
|
self.assertIn('null', cache)
|
2007-05-08 12:13:46 +08:00
|
|
|
|
2009-03-11 21:27:03 +08:00
|
|
|
def test_incr(self):
|
|
|
|
# Cache values can be incremented
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer', 41)
|
|
|
|
self.assertEqual(cache.incr('answer'), 42)
|
|
|
|
self.assertEqual(cache.get('answer'), 42)
|
|
|
|
self.assertEqual(cache.incr('answer', 10), 52)
|
|
|
|
self.assertEqual(cache.get('answer'), 52)
|
|
|
|
self.assertEqual(cache.incr('answer', -10), 42)
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr('does_not_exist')
|
2021-08-30 21:12:05 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr('does_not_exist', -1)
|
2020-12-14 18:42:22 +08:00
|
|
|
cache.set('null', None)
|
|
|
|
with self.assertRaises(self.incr_decr_type_error):
|
|
|
|
cache.incr('null')
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def test_decr(self):
|
|
|
|
# Cache values can be decremented
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer', 43)
|
|
|
|
self.assertEqual(cache.decr('answer'), 42)
|
|
|
|
self.assertEqual(cache.get('answer'), 42)
|
|
|
|
self.assertEqual(cache.decr('answer', 10), 32)
|
|
|
|
self.assertEqual(cache.get('answer'), 32)
|
|
|
|
self.assertEqual(cache.decr('answer', -10), 42)
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.decr('does_not_exist')
|
2021-08-30 21:12:05 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr('does_not_exist', -1)
|
2020-12-14 18:42:22 +08:00
|
|
|
cache.set('null', None)
|
|
|
|
with self.assertRaises(self.incr_decr_type_error):
|
|
|
|
cache.decr('null')
|
2009-03-11 21:27:03 +08:00
|
|
|
|
2012-07-18 20:00:31 +08:00
|
|
|
def test_close(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertTrue(hasattr(cache, 'close'))
|
|
|
|
cache.close()
|
2012-07-18 20:00:31 +08:00
|
|
|
|
2006-08-27 21:59:47 +08:00
|
|
|
def test_data_types(self):
|
2009-03-11 21:27:03 +08:00
|
|
|
# Many different data types can be cached
|
2006-08-27 21:59:47 +08:00
|
|
|
stuff = {
|
2013-10-27 09:27:42 +08:00
|
|
|
'string': 'this is a string',
|
|
|
|
'int': 42,
|
|
|
|
'list': [1, 2, 3, 4],
|
|
|
|
'tuple': (1, 2, 3, 4),
|
|
|
|
'dict': {'A': 1, 'B': 2},
|
|
|
|
'function': f,
|
|
|
|
'class': C,
|
2006-08-27 21:59:47 +08:00
|
|
|
}
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("stuff", stuff)
|
|
|
|
self.assertEqual(cache.get("stuff"), stuff)
|
2007-07-15 14:24:54 +08:00
|
|
|
|
2009-10-29 22:32:01 +08:00
|
|
|
def test_cache_read_for_model_instance(self):
|
|
|
|
# Don't want fields with callable as default to be called on cache read
|
|
|
|
expensive_calculation.num_runs = 0
|
|
|
|
Poll.objects.all().delete()
|
|
|
|
my_poll = Poll.objects.create(question="Well?")
|
|
|
|
self.assertEqual(Poll.objects.count(), 1)
|
|
|
|
pub_date = my_poll.pub_date
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('question', my_poll)
|
|
|
|
cached_poll = cache.get('question')
|
2009-10-29 22:32:01 +08:00
|
|
|
self.assertEqual(cached_poll.pub_date, pub_date)
|
|
|
|
# We only want the default expensive calculation run once
|
|
|
|
self.assertEqual(expensive_calculation.num_runs, 1)
|
|
|
|
|
|
|
|
def test_cache_write_for_model_instance_with_deferred(self):
|
|
|
|
# Don't want fields with callable as default to be called on cache write
|
|
|
|
expensive_calculation.num_runs = 0
|
|
|
|
Poll.objects.all().delete()
|
2013-09-09 03:20:01 +08:00
|
|
|
Poll.objects.create(question="What?")
|
2009-10-29 22:32:01 +08:00
|
|
|
self.assertEqual(expensive_calculation.num_runs, 1)
|
|
|
|
defer_qs = Poll.objects.all().defer('question')
|
|
|
|
self.assertEqual(defer_qs.count(), 1)
|
|
|
|
self.assertEqual(expensive_calculation.num_runs, 1)
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('deferred_queryset', defer_qs)
|
2009-10-29 22:32:01 +08:00
|
|
|
# cache set should not re-evaluate default functions
|
|
|
|
self.assertEqual(expensive_calculation.num_runs, 1)
|
|
|
|
|
|
|
|
def test_cache_read_for_model_instance_with_deferred(self):
|
|
|
|
# Don't want fields with callable as default to be called on cache read
|
|
|
|
expensive_calculation.num_runs = 0
|
|
|
|
Poll.objects.all().delete()
|
2013-09-09 03:20:01 +08:00
|
|
|
Poll.objects.create(question="What?")
|
2009-10-29 22:32:01 +08:00
|
|
|
self.assertEqual(expensive_calculation.num_runs, 1)
|
|
|
|
defer_qs = Poll.objects.all().defer('question')
|
|
|
|
self.assertEqual(defer_qs.count(), 1)
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('deferred_queryset', defer_qs)
|
2009-10-29 22:32:01 +08:00
|
|
|
self.assertEqual(expensive_calculation.num_runs, 1)
|
|
|
|
runs_before_cache_read = expensive_calculation.num_runs
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.get('deferred_queryset')
|
2009-10-29 22:32:01 +08:00
|
|
|
# We only want the default expensive calculation run on creation and set
|
|
|
|
self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read)
|
|
|
|
|
2006-08-27 21:59:47 +08:00
|
|
|
def test_expiration(self):
|
2009-03-11 21:27:03 +08:00
|
|
|
# Cache values can be set to expire
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('expire1', 'very quickly', 1)
|
|
|
|
cache.set('expire2', 'very quickly', 1)
|
|
|
|
cache.set('expire3', 'very quickly', 1)
|
2007-12-05 02:03:56 +08:00
|
|
|
|
2008-08-02 13:56:57 +08:00
|
|
|
time.sleep(2)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("expire1"))
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add("expire2", "newvalue"), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get("expire2"), "newvalue")
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key("expire3"), False)
|
2006-08-27 21:59:47 +08:00
|
|
|
|
2018-04-28 05:48:35 +08:00
|
|
|
def test_touch(self):
|
|
|
|
# cache.touch() updates the timeout.
|
|
|
|
cache.set('expire1', 'very quickly', timeout=1)
|
2020-10-20 01:54:23 +08:00
|
|
|
self.assertIs(cache.touch('expire1', timeout=4), True)
|
|
|
|
time.sleep(2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key('expire1'), True)
|
2020-10-20 01:54:23 +08:00
|
|
|
time.sleep(3)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key('expire1'), False)
|
2018-04-28 05:48:35 +08:00
|
|
|
# cache.touch() works without the timeout argument.
|
|
|
|
cache.set('expire1', 'very quickly', timeout=1)
|
|
|
|
self.assertIs(cache.touch('expire1'), True)
|
2020-10-20 01:54:23 +08:00
|
|
|
time.sleep(2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key('expire1'), True)
|
2018-04-28 05:48:35 +08:00
|
|
|
|
|
|
|
self.assertIs(cache.touch('nonexistent'), False)
|
|
|
|
|
2007-07-16 17:36:10 +08:00
|
|
|
def test_unicode(self):
|
2009-03-11 21:27:03 +08:00
|
|
|
# Unicode values can be cached
|
2007-07-16 17:36:10 +08:00
|
|
|
stuff = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'ascii': 'ascii_value',
|
|
|
|
'unicode_ascii': 'Iñtërnâtiônàlizætiøn1',
|
|
|
|
'Iñtërnâtiônàlizætiøn': 'Iñtërnâtiônàlizætiøn2',
|
2013-10-27 09:27:42 +08:00
|
|
|
'ascii2': {'x': 1}
|
2013-10-18 17:02:43 +08:00
|
|
|
}
|
2011-03-19 10:42:40 +08:00
|
|
|
# Test `set`
|
2007-07-16 17:36:10 +08:00
|
|
|
for (key, value) in stuff.items():
|
2017-03-08 05:00:43 +08:00
|
|
|
with self.subTest(key=key):
|
|
|
|
cache.set(key, value)
|
|
|
|
self.assertEqual(cache.get(key), value)
|
2007-07-16 17:36:10 +08:00
|
|
|
|
2011-03-19 10:42:40 +08:00
|
|
|
# Test `add`
|
|
|
|
for (key, value) in stuff.items():
|
2017-03-08 05:00:43 +08:00
|
|
|
with self.subTest(key=key):
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.delete(key), True)
|
|
|
|
self.assertIs(cache.add(key, value), True)
|
2017-03-08 05:00:43 +08:00
|
|
|
self.assertEqual(cache.get(key), value)
|
2011-03-19 10:42:40 +08:00
|
|
|
|
|
|
|
# Test `set_many`
|
|
|
|
for (key, value) in stuff.items():
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.delete(key), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many(stuff)
|
2011-03-19 10:42:40 +08:00
|
|
|
for (key, value) in stuff.items():
|
2017-03-08 05:00:43 +08:00
|
|
|
with self.subTest(key=key):
|
|
|
|
self.assertEqual(cache.get(key), value)
|
2011-03-19 10:42:40 +08:00
|
|
|
|
2010-03-02 04:11:24 +08:00
|
|
|
def test_binary_string(self):
|
2011-08-12 22:14:15 +08:00
|
|
|
# Binary strings should be cacheable
|
2010-03-02 04:11:24 +08:00
|
|
|
from zlib import compress, decompress
|
|
|
|
value = 'value_to_be_compressed'
|
2012-08-15 20:29:40 +08:00
|
|
|
compressed_value = compress(value.encode())
|
2011-03-19 10:42:40 +08:00
|
|
|
|
|
|
|
# Test set
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('binary1', compressed_value)
|
|
|
|
compressed_result = cache.get('binary1')
|
2010-03-02 04:11:24 +08:00
|
|
|
self.assertEqual(compressed_value, compressed_result)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(value, decompress(compressed_result).decode())
|
2010-03-02 04:11:24 +08:00
|
|
|
|
2011-03-19 10:42:40 +08:00
|
|
|
# Test add
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('binary1-add', compressed_value), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
compressed_result = cache.get('binary1-add')
|
2011-03-19 10:42:40 +08:00
|
|
|
self.assertEqual(compressed_value, compressed_result)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(value, decompress(compressed_result).decode())
|
2011-03-19 10:42:40 +08:00
|
|
|
|
|
|
|
# Test set_many
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many({'binary1-set_many': compressed_value})
|
|
|
|
compressed_result = cache.get('binary1-set_many')
|
2011-03-19 10:42:40 +08:00
|
|
|
self.assertEqual(compressed_value, compressed_result)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(value, decompress(compressed_result).decode())
|
2011-03-19 10:42:40 +08:00
|
|
|
|
2010-01-27 16:21:35 +08:00
|
|
|
def test_set_many(self):
|
|
|
|
# Multiple keys can be set using set_many
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many({"key1": "spam", "key2": "eggs"})
|
|
|
|
self.assertEqual(cache.get("key1"), "spam")
|
|
|
|
self.assertEqual(cache.get("key2"), "eggs")
|
2010-01-27 16:21:35 +08:00
|
|
|
|
2016-11-06 19:57:38 +08:00
|
|
|
def test_set_many_returns_empty_list_on_success(self):
|
|
|
|
"""set_many() returns an empty list when all keys are inserted."""
|
|
|
|
failing_keys = cache.set_many({'key1': 'spam', 'key2': 'eggs'})
|
|
|
|
self.assertEqual(failing_keys, [])
|
|
|
|
|
2010-01-27 16:21:35 +08:00
|
|
|
def test_set_many_expiration(self):
|
|
|
|
# set_many takes a second ``timeout`` parameter
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many({"key1": "spam", "key2": "eggs"}, 1)
|
2010-01-27 16:21:35 +08:00
|
|
|
time.sleep(2)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("key1"))
|
|
|
|
self.assertIsNone(cache.get("key2"))
|
2010-01-27 16:21:35 +08:00
|
|
|
|
|
|
|
def test_delete_many(self):
|
|
|
|
# Multiple keys can be deleted using delete_many
|
2018-08-16 21:02:21 +08:00
|
|
|
cache.set_many({'key1': 'spam', 'key2': 'eggs', 'key3': 'ham'})
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.delete_many(["key1", "key2"])
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("key1"))
|
|
|
|
self.assertIsNone(cache.get("key2"))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get("key3"), "ham")
|
2010-01-27 16:21:35 +08:00
|
|
|
|
|
|
|
def test_clear(self):
|
|
|
|
# The cache can be emptied using clear
|
2018-08-16 21:02:21 +08:00
|
|
|
cache.set_many({'key1': 'spam', 'key2': 'eggs'})
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.clear()
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get("key1"))
|
|
|
|
self.assertIsNone(cache.get("key2"))
|
2010-01-27 16:21:35 +08:00
|
|
|
|
2010-02-11 20:06:26 +08:00
|
|
|
def test_long_timeout(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""
|
2019-12-12 00:39:21 +08:00
|
|
|
Follow memcached's convention where a timeout greater than 30 days is
|
2016-10-27 15:53:39 +08:00
|
|
|
treated as an absolute expiration timestamp instead of a relative
|
|
|
|
offset (#12399).
|
|
|
|
"""
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('key1', 'eggs', 60 * 60 * 24 * 30 + 1) # 30 days + 1 second
|
|
|
|
self.assertEqual(cache.get('key1'), 'eggs')
|
2010-02-11 20:06:26 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('key2', 'ham', 60 * 60 * 24 * 30 + 1), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('key2'), 'ham')
|
2010-02-11 20:06:26 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, 60 * 60 * 24 * 30 + 1)
|
|
|
|
self.assertEqual(cache.get('key3'), 'sausage')
|
|
|
|
self.assertEqual(cache.get('key4'), 'lobster bisque')
|
2010-02-11 20:06:26 +08:00
|
|
|
|
2013-05-18 18:54:59 +08:00
|
|
|
def test_forever_timeout(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""
|
2013-05-18 18:54:59 +08:00
|
|
|
Passing in None into timeout results in a value that is cached forever
|
2016-10-27 15:53:39 +08:00
|
|
|
"""
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('key1', 'eggs', None)
|
|
|
|
self.assertEqual(cache.get('key1'), 'eggs')
|
2013-05-18 18:54:59 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('key2', 'ham', None), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('key2'), 'ham')
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('key1', 'new eggs', None), False)
|
2014-04-23 19:06:23 +08:00
|
|
|
self.assertEqual(cache.get('key1'), 'eggs')
|
2013-05-18 18:54:59 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, None)
|
|
|
|
self.assertEqual(cache.get('key3'), 'sausage')
|
|
|
|
self.assertEqual(cache.get('key4'), 'lobster bisque')
|
2013-05-18 18:54:59 +08:00
|
|
|
|
2018-04-28 05:48:35 +08:00
|
|
|
cache.set('key5', 'belgian fries', timeout=1)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.touch('key5', timeout=None), True)
|
2018-04-28 05:48:35 +08:00
|
|
|
time.sleep(2)
|
|
|
|
self.assertEqual(cache.get('key5'), 'belgian fries')
|
|
|
|
|
2013-05-18 18:54:59 +08:00
|
|
|
def test_zero_timeout(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""
|
2014-03-05 14:35:07 +08:00
|
|
|
Passing in zero into timeout results in a value that is not cached
|
2016-10-27 15:53:39 +08:00
|
|
|
"""
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('key1', 'eggs', 0)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('key1'))
|
2013-05-18 18:54:59 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('key2', 'ham', 0), True)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('key2'))
|
2013-05-18 18:54:59 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, 0)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('key3'))
|
|
|
|
self.assertIsNone(cache.get('key4'))
|
2013-05-18 18:54:59 +08:00
|
|
|
|
2018-04-28 05:48:35 +08:00
|
|
|
cache.set('key5', 'belgian fries', timeout=5)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.touch('key5', timeout=0), True)
|
2018-04-28 05:48:35 +08:00
|
|
|
self.assertIsNone(cache.get('key5'))
|
|
|
|
|
2011-07-29 17:39:23 +08:00
|
|
|
def test_float_timeout(self):
|
|
|
|
# Make sure a timeout given as a float doesn't crash anything.
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set("key1", "spam", 100.2)
|
|
|
|
self.assertEqual(cache.get("key1"), "spam")
|
|
|
|
|
2019-12-15 01:03:24 +08:00
|
|
|
def _perform_cull_test(self, cull_cache_name, initial_count, final_count):
|
|
|
|
try:
|
|
|
|
cull_cache = caches[cull_cache_name]
|
|
|
|
except InvalidCacheBackendError:
|
|
|
|
self.skipTest("Culling isn't implemented.")
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
# Create initial cache key entries. This will overflow the cache,
|
|
|
|
# causing a cull.
|
2010-08-31 08:44:46 +08:00
|
|
|
for i in range(1, initial_count):
|
2013-10-19 06:49:24 +08:00
|
|
|
cull_cache.set('cull%d' % i, 'value', 1000)
|
2010-08-31 08:44:46 +08:00
|
|
|
count = 0
|
|
|
|
# Count how many keys are left in the cache.
|
|
|
|
for i in range(1, initial_count):
|
2013-10-19 06:49:24 +08:00
|
|
|
if cull_cache.has_key('cull%d' % i):
|
2016-07-21 16:28:40 +08:00
|
|
|
count += 1
|
2010-08-31 08:44:46 +08:00
|
|
|
self.assertEqual(count, final_count)
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
def test_cull(self):
|
2019-12-15 01:03:24 +08:00
|
|
|
self._perform_cull_test('cull', 50, 29)
|
2013-10-19 06:49:24 +08:00
|
|
|
|
|
|
|
def test_zero_cull(self):
|
2019-12-15 01:03:24 +08:00
|
|
|
self._perform_cull_test('zero_cull', 50, 19)
|
2013-10-19 06:49:24 +08:00
|
|
|
|
2020-06-20 15:33:24 +08:00
|
|
|
def test_cull_delete_when_store_empty(self):
|
|
|
|
try:
|
|
|
|
cull_cache = caches['cull']
|
|
|
|
except InvalidCacheBackendError:
|
|
|
|
self.skipTest("Culling isn't implemented.")
|
|
|
|
old_max_entries = cull_cache._max_entries
|
|
|
|
# Force _cull to delete on first cached record.
|
|
|
|
cull_cache._max_entries = -1
|
|
|
|
try:
|
|
|
|
cull_cache.set('force_cull_delete', 'value', 1000)
|
|
|
|
self.assertIs(cull_cache.has_key('force_cull_delete'), True)
|
|
|
|
finally:
|
|
|
|
cull_cache._max_entries = old_max_entries
|
|
|
|
|
2021-09-03 17:26:27 +08:00
|
|
|
def _perform_invalid_key_test(self, key, expected_warning, key_func=None):
|
2010-09-13 02:45:26 +08:00
|
|
|
"""
|
2020-05-20 17:45:31 +08:00
|
|
|
All the builtin backends should warn (except memcached that should
|
|
|
|
error) on keys that would be refused by memcached. This encourages
|
|
|
|
portable caching code without making it too difficult to use production
|
|
|
|
backends with more liberal key rules. Refs #6447.
|
2010-09-13 02:45:26 +08:00
|
|
|
"""
|
2010-11-19 23:39:35 +08:00
|
|
|
# mimic custom ``make_key`` method being defined since the default will
|
|
|
|
# never show the below warnings
|
|
|
|
def func(key, *args):
|
|
|
|
return key
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
old_func = cache.key_func
|
2021-09-03 17:26:27 +08:00
|
|
|
cache.key_func = key_func or func
|
2010-09-13 02:45:26 +08:00
|
|
|
|
2020-08-21 00:18:25 +08:00
|
|
|
tests = [
|
|
|
|
('add', [key, 1]),
|
|
|
|
('get', [key]),
|
|
|
|
('set', [key, 1]),
|
|
|
|
('incr', [key]),
|
|
|
|
('decr', [key]),
|
2020-08-19 21:05:05 +08:00
|
|
|
('touch', [key]),
|
2020-08-21 00:18:25 +08:00
|
|
|
('delete', [key]),
|
|
|
|
('get_many', [[key, 'b']]),
|
|
|
|
('set_many', [{key: 1, 'b': 2}]),
|
2021-08-27 03:19:36 +08:00
|
|
|
('delete_many', [[key, 'b']]),
|
2020-08-21 00:18:25 +08:00
|
|
|
]
|
2010-11-11 23:06:20 +08:00
|
|
|
try:
|
2020-08-21 00:18:25 +08:00
|
|
|
for operation, args in tests:
|
|
|
|
with self.subTest(operation=operation):
|
|
|
|
with self.assertWarns(CacheKeyWarning) as cm:
|
|
|
|
getattr(cache, operation)(*args)
|
|
|
|
self.assertEqual(str(cm.warning), expected_warning)
|
2010-11-11 23:06:20 +08:00
|
|
|
finally:
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.key_func = old_func
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2016-08-28 09:59:28 +08:00
|
|
|
def test_invalid_key_characters(self):
|
|
|
|
# memcached doesn't allow whitespace or control characters in keys.
|
|
|
|
key = 'key with spaces and 清'
|
2017-10-30 23:30:00 +08:00
|
|
|
self._perform_invalid_key_test(key, KEY_ERRORS_WITH_MEMCACHED_MSG % key)
|
2016-08-28 09:59:28 +08:00
|
|
|
|
|
|
|
def test_invalid_key_length(self):
|
|
|
|
# memcached limits key length to 250.
|
|
|
|
key = ('a' * 250) + '清'
|
|
|
|
expected_warning = (
|
|
|
|
'Cache key will cause errors if used with memcached: '
|
|
|
|
'%r (longer than %s)' % (key, 250)
|
|
|
|
)
|
|
|
|
self._perform_invalid_key_test(key, expected_warning)
|
|
|
|
|
2021-09-03 17:26:27 +08:00
|
|
|
def test_invalid_with_version_key_length(self):
|
|
|
|
# Custom make_key() that adds a version to the key and exceeds the
|
|
|
|
# limit.
|
|
|
|
def key_func(key, *args):
|
|
|
|
return key + ':1'
|
|
|
|
|
|
|
|
key = 'a' * 249
|
|
|
|
expected_warning = (
|
|
|
|
'Cache key will cause errors if used with memcached: '
|
|
|
|
'%r (longer than %s)' % (key_func(key), 250)
|
|
|
|
)
|
|
|
|
self._perform_invalid_key_test(key, expected_warning, key_func=key_func)
|
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
def test_cache_versioning_get_set(self):
|
|
|
|
# set, using default version = 1
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer1', 42)
|
|
|
|
self.assertEqual(cache.get('answer1'), 42)
|
|
|
|
self.assertEqual(cache.get('answer1', version=1), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer1', version=2))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer1'))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer1', version=1), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer1', version=2))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# set, default version = 1, but manually override version = 2
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer2', 42, version=2)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer2'))
|
|
|
|
self.assertIsNone(cache.get('answer2', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer2', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer2'), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer2', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer2', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# v2 set, using default version = 2
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['v2'].set('answer3', 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer3'))
|
|
|
|
self.assertIsNone(cache.get('answer3', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer3', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer3'), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer3', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer3', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# v2 set, default version = 2, but manually override version = 1
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['v2'].set('answer4', 42, version=1)
|
|
|
|
self.assertEqual(cache.get('answer4'), 42)
|
|
|
|
self.assertEqual(cache.get('answer4', version=1), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer4', version=2))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer4'))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer4', version=1), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer4', version=2))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
def test_cache_versioning_add(self):
|
|
|
|
|
|
|
|
# add, default version = 1, but manually override version = 2
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('answer1', 42, version=2), True)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer1', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer1', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('answer1', 37, version=2), False)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer1', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer1', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('answer1', 37, version=1), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer1', version=1), 37)
|
|
|
|
self.assertEqual(cache.get('answer1', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# v2 add, using default version = 2
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].add('answer2', 42), True)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer2', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer2', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].add('answer2', 37), False)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer2', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer2', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].add('answer2', 37, version=1), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer2', version=1), 37)
|
|
|
|
self.assertEqual(cache.get('answer2', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# v2 add, default version = 2, but manually override version = 1
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].add('answer3', 42, version=1), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer3', version=1), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer3', version=2))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].add('answer3', 37, version=1), False)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer3', version=1), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer3', version=2))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].add('answer3', 37), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer3', version=1), 42)
|
|
|
|
self.assertEqual(cache.get('answer3', version=2), 37)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
def test_cache_versioning_has_key(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer1', 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# has_key
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.has_key('answer1'), True)
|
|
|
|
self.assertIs(cache.has_key('answer1', version=1), True)
|
|
|
|
self.assertIs(cache.has_key('answer1', version=2), False)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].has_key('answer1'), False)
|
|
|
|
self.assertIs(caches['v2'].has_key('answer1', version=1), True)
|
|
|
|
self.assertIs(caches['v2'].has_key('answer1', version=2), False)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
def test_cache_versioning_delete(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer1', 37, version=1)
|
|
|
|
cache.set('answer1', 42, version=2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.delete('answer1'), True)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer1', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer1', version=2), 42)
|
|
|
|
|
|
|
|
cache.set('answer2', 37, version=1)
|
|
|
|
cache.set('answer2', 42, version=2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.delete('answer2', version=2), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer2', version=1), 37)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer2', version=2))
|
2013-10-19 06:49:24 +08:00
|
|
|
|
|
|
|
cache.set('answer3', 37, version=1)
|
|
|
|
cache.set('answer3', 42, version=2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].delete('answer3'), True)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer3', version=1), 37)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer3', version=2))
|
2013-10-19 06:49:24 +08:00
|
|
|
|
|
|
|
cache.set('answer4', 37, version=1)
|
|
|
|
cache.set('answer4', 42, version=2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(caches['v2'].delete('answer4', version=1), True)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer4', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer4', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
def test_cache_versioning_incr_decr(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer1', 37, version=1)
|
|
|
|
cache.set('answer1', 42, version=2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(cache.incr('answer1'), 38)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer1', version=1), 38)
|
|
|
|
self.assertEqual(cache.get('answer1', version=2), 42)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(cache.decr('answer1'), 37)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer1', version=1), 37)
|
|
|
|
self.assertEqual(cache.get('answer1', version=2), 42)
|
|
|
|
|
|
|
|
cache.set('answer2', 37, version=1)
|
|
|
|
cache.set('answer2', 42, version=2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(cache.incr('answer2', version=2), 43)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer2', version=1), 37)
|
|
|
|
self.assertEqual(cache.get('answer2', version=2), 43)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(cache.decr('answer2', version=2), 42)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer2', version=1), 37)
|
|
|
|
self.assertEqual(cache.get('answer2', version=2), 42)
|
|
|
|
|
|
|
|
cache.set('answer3', 37, version=1)
|
|
|
|
cache.set('answer3', 42, version=2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(caches['v2'].incr('answer3'), 43)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer3', version=1), 37)
|
|
|
|
self.assertEqual(cache.get('answer3', version=2), 43)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(caches['v2'].decr('answer3'), 42)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer3', version=1), 37)
|
|
|
|
self.assertEqual(cache.get('answer3', version=2), 42)
|
|
|
|
|
|
|
|
cache.set('answer4', 37, version=1)
|
|
|
|
cache.set('answer4', 42, version=2)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(caches['v2'].incr('answer4', version=1), 38)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer4', version=1), 38)
|
|
|
|
self.assertEqual(cache.get('answer4', version=2), 42)
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(caches['v2'].decr('answer4', version=1), 37)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer4', version=1), 37)
|
|
|
|
self.assertEqual(cache.get('answer4', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
def test_cache_versioning_get_set_many(self):
|
|
|
|
# set, using default version = 1
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many({'ford1': 37, 'arthur1': 42})
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(cache.get_many(['ford1', 'arthur1']), {'ford1': 37, 'arthur1': 42})
|
|
|
|
self.assertEqual(cache.get_many(['ford1', 'arthur1'], version=1), {'ford1': 37, 'arthur1': 42})
|
|
|
|
self.assertEqual(cache.get_many(['ford1', 'arthur1'], version=2), {})
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(caches['v2'].get_many(['ford1', 'arthur1']), {})
|
|
|
|
self.assertEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=1), {'ford1': 37, 'arthur1': 42})
|
|
|
|
self.assertEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=2), {})
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# set, default version = 1, but manually override version = 2
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set_many({'ford2': 37, 'arthur2': 42}, version=2)
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(cache.get_many(['ford2', 'arthur2']), {})
|
|
|
|
self.assertEqual(cache.get_many(['ford2', 'arthur2'], version=1), {})
|
|
|
|
self.assertEqual(cache.get_many(['ford2', 'arthur2'], version=2), {'ford2': 37, 'arthur2': 42})
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(caches['v2'].get_many(['ford2', 'arthur2']), {'ford2': 37, 'arthur2': 42})
|
|
|
|
self.assertEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=1), {})
|
|
|
|
self.assertEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=2), {'ford2': 37, 'arthur2': 42})
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# v2 set, using default version = 2
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['v2'].set_many({'ford3': 37, 'arthur3': 42})
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(cache.get_many(['ford3', 'arthur3']), {})
|
|
|
|
self.assertEqual(cache.get_many(['ford3', 'arthur3'], version=1), {})
|
|
|
|
self.assertEqual(cache.get_many(['ford3', 'arthur3'], version=2), {'ford3': 37, 'arthur3': 42})
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(caches['v2'].get_many(['ford3', 'arthur3']), {'ford3': 37, 'arthur3': 42})
|
|
|
|
self.assertEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=1), {})
|
|
|
|
self.assertEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=2), {'ford3': 37, 'arthur3': 42})
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# v2 set, default version = 2, but manually override version = 1
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['v2'].set_many({'ford4': 37, 'arthur4': 42}, version=1)
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(cache.get_many(['ford4', 'arthur4']), {'ford4': 37, 'arthur4': 42})
|
|
|
|
self.assertEqual(cache.get_many(['ford4', 'arthur4'], version=1), {'ford4': 37, 'arthur4': 42})
|
|
|
|
self.assertEqual(cache.get_many(['ford4', 'arthur4'], version=2), {})
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2017-03-17 19:51:48 +08:00
|
|
|
self.assertEqual(caches['v2'].get_many(['ford4', 'arthur4']), {})
|
|
|
|
self.assertEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=1), {'ford4': 37, 'arthur4': 42})
|
|
|
|
self.assertEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=2), {})
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
def test_incr_version(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer', 42, version=2)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer'))
|
|
|
|
self.assertIsNone(cache.get('answer', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer', version=2), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer', version=3))
|
2013-10-19 06:49:24 +08:00
|
|
|
|
|
|
|
self.assertEqual(cache.incr_version('answer', version=2), 3)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer'))
|
|
|
|
self.assertIsNone(cache.get('answer', version=1))
|
|
|
|
self.assertIsNone(cache.get('answer', version=2))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer', version=3), 42)
|
|
|
|
|
|
|
|
caches['v2'].set('answer2', 42)
|
|
|
|
self.assertEqual(caches['v2'].get('answer2'), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer2', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer2', version=2), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer2', version=3))
|
2013-10-19 06:49:24 +08:00
|
|
|
|
|
|
|
self.assertEqual(caches['v2'].incr_version('answer2'), 3)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer2'))
|
|
|
|
self.assertIsNone(caches['v2'].get('answer2', version=1))
|
|
|
|
self.assertIsNone(caches['v2'].get('answer2', version=2))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer2', version=3), 42)
|
|
|
|
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.incr_version('does_not_exist')
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2020-12-14 18:42:22 +08:00
|
|
|
cache.set('null', None)
|
2021-09-16 15:37:03 +08:00
|
|
|
self.assertEqual(cache.incr_version('null'), 2)
|
2020-12-14 18:42:22 +08:00
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
def test_decr_version(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer', 42, version=2)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer'))
|
|
|
|
self.assertIsNone(cache.get('answer', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.get('answer', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(cache.decr_version('answer', version=2), 1)
|
|
|
|
self.assertEqual(cache.get('answer'), 42)
|
|
|
|
self.assertEqual(cache.get('answer', version=1), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer', version=2))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['v2'].set('answer2', 42)
|
|
|
|
self.assertEqual(caches['v2'].get('answer2'), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer2', version=1))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer2', version=2), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].decr_version('answer2'), 1)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer2'))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['v2'].get('answer2', version=1), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['v2'].get('answer2', version=2))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
cache.decr_version('does_not_exist', version=2)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2020-12-14 18:42:22 +08:00
|
|
|
cache.set('null', None, version=2)
|
2021-09-16 15:37:03 +08:00
|
|
|
self.assertEqual(cache.decr_version('null', version=2), 1)
|
2020-12-14 18:42:22 +08:00
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
def test_custom_key_func(self):
|
|
|
|
# Two caches with different key functions aren't visible to each other
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('answer1', 42)
|
|
|
|
self.assertEqual(cache.get('answer1'), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['custom_key'].get('answer1'))
|
|
|
|
self.assertIsNone(caches['custom_key2'].get('answer1'))
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['custom_key'].set('answer2', 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.get('answer2'))
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['custom_key'].get('answer2'), 42)
|
|
|
|
self.assertEqual(caches['custom_key2'].get('answer2'), 42)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2021-11-03 15:46:34 +08:00
|
|
|
@override_settings(CACHE_MIDDLEWARE_ALIAS=DEFAULT_CACHE_ALIAS)
|
2015-10-21 23:56:30 +08:00
|
|
|
def test_cache_write_unpicklable_object(self):
|
2019-09-27 01:06:35 +08:00
|
|
|
fetch_middleware = FetchFromCacheMiddleware(empty_response)
|
2011-12-12 05:04:56 +08:00
|
|
|
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get('/cache/test')
|
|
|
|
request._cache_update_cache = True
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(get_cache_data)
|
2011-12-12 05:04:56 +08:00
|
|
|
|
|
|
|
content = 'Testing cookie serialization.'
|
|
|
|
|
2019-09-27 01:06:35 +08:00
|
|
|
def get_response(req):
|
|
|
|
response = HttpResponse(content)
|
|
|
|
response.set_cookie('foo', 'bar')
|
|
|
|
return response
|
|
|
|
|
|
|
|
update_middleware = UpdateCacheMiddleware(get_response)
|
|
|
|
response = update_middleware(request)
|
2011-12-12 05:04:56 +08:00
|
|
|
|
|
|
|
get_cache_data = fetch_middleware.process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(get_cache_data)
|
2017-02-08 01:05:47 +08:00
|
|
|
self.assertEqual(get_cache_data.content, content.encode())
|
2011-12-12 05:04:56 +08:00
|
|
|
self.assertEqual(get_cache_data.cookies, response.cookies)
|
|
|
|
|
2019-09-27 01:06:35 +08:00
|
|
|
UpdateCacheMiddleware(lambda req: get_cache_data)(request)
|
2011-12-12 05:04:56 +08:00
|
|
|
get_cache_data = fetch_middleware.process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(get_cache_data)
|
2017-02-08 01:05:47 +08:00
|
|
|
self.assertEqual(get_cache_data.content, content.encode())
|
2011-12-12 05:04:56 +08:00
|
|
|
self.assertEqual(get_cache_data.cookies, response.cookies)
|
|
|
|
|
2013-11-24 00:50:28 +08:00
|
|
|
def test_add_fail_on_pickleerror(self):
|
2015-10-21 23:56:30 +08:00
|
|
|
# Shouldn't fail silently if trying to cache an unpicklable type.
|
2013-11-24 22:33:22 +08:00
|
|
|
with self.assertRaises(pickle.PickleError):
|
2015-10-21 23:56:30 +08:00
|
|
|
cache.add('unpicklable', Unpicklable())
|
2013-11-24 00:50:28 +08:00
|
|
|
|
|
|
|
def test_set_fail_on_pickleerror(self):
|
|
|
|
with self.assertRaises(pickle.PickleError):
|
2015-10-21 23:56:30 +08:00
|
|
|
cache.set('unpicklable', Unpicklable())
|
2013-11-24 00:50:28 +08:00
|
|
|
|
2014-11-24 02:33:07 +08:00
|
|
|
def test_get_or_set(self):
|
|
|
|
self.assertIsNone(cache.get('projector'))
|
|
|
|
self.assertEqual(cache.get_or_set('projector', 42), 42)
|
|
|
|
self.assertEqual(cache.get('projector'), 42)
|
2019-10-21 16:55:05 +08:00
|
|
|
self.assertIsNone(cache.get_or_set('null', None))
|
2021-09-16 15:37:03 +08:00
|
|
|
# Previous get_or_set() stores None in the cache.
|
|
|
|
self.assertIsNone(cache.get('null', 'default'))
|
2014-11-24 02:33:07 +08:00
|
|
|
|
|
|
|
def test_get_or_set_callable(self):
|
|
|
|
def my_callable():
|
|
|
|
return 'value'
|
|
|
|
|
|
|
|
self.assertEqual(cache.get_or_set('mykey', my_callable), 'value')
|
2016-06-23 02:28:43 +08:00
|
|
|
self.assertEqual(cache.get_or_set('mykey', my_callable()), 'value')
|
2014-11-24 02:33:07 +08:00
|
|
|
|
2020-12-14 18:42:22 +08:00
|
|
|
self.assertIsNone(cache.get_or_set('null', lambda: None))
|
2021-09-16 15:37:03 +08:00
|
|
|
# Previous get_or_set() stores None in the cache.
|
|
|
|
self.assertIsNone(cache.get('null', 'default'))
|
2017-09-16 05:16:44 +08:00
|
|
|
|
2014-11-24 02:33:07 +08:00
|
|
|
def test_get_or_set_version(self):
|
2016-12-01 18:38:01 +08:00
|
|
|
msg = "get_or_set() missing 1 required positional argument: 'default'"
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(cache.get_or_set('brian', 1979, version=2), 1979)
|
2016-06-23 02:28:43 +08:00
|
|
|
with self.assertRaisesMessage(TypeError, msg):
|
2014-11-24 02:33:07 +08:00
|
|
|
cache.get_or_set('brian')
|
2016-06-23 02:28:43 +08:00
|
|
|
with self.assertRaisesMessage(TypeError, msg):
|
2014-11-24 02:33:07 +08:00
|
|
|
cache.get_or_set('brian', version=1)
|
|
|
|
self.assertIsNone(cache.get('brian', version=1))
|
|
|
|
self.assertEqual(cache.get_or_set('brian', 42, version=1), 42)
|
|
|
|
self.assertEqual(cache.get_or_set('brian', 1979, version=2), 1979)
|
|
|
|
self.assertIsNone(cache.get('brian', version=3))
|
|
|
|
|
2016-03-06 18:34:23 +08:00
|
|
|
def test_get_or_set_racing(self):
|
|
|
|
with mock.patch('%s.%s' % (settings.CACHES['default']['BACKEND'], 'add')) as cache_add:
|
|
|
|
# Simulate cache.add() failing to add a value. In that case, the
|
|
|
|
# default value should be returned.
|
|
|
|
cache_add.return_value = False
|
|
|
|
self.assertEqual(cache.get_or_set('key', 'default'), 'default')
|
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
BACKEND='django.core.cache.backends.db.DatabaseCache',
|
|
|
|
# Spaces are used in the table name to ensure quoting/escaping is working
|
|
|
|
LOCATION='test cache table'
|
|
|
|
))
|
2011-11-21 15:08:39 +08:00
|
|
|
class DBCacheTests(BaseCacheTests, TransactionTestCase):
|
2013-06-04 14:09:29 +08:00
|
|
|
|
2013-06-14 22:00:47 +08:00
|
|
|
available_apps = ['cache']
|
2011-04-03 06:13:21 +08:00
|
|
|
|
2009-03-11 21:27:03 +08:00
|
|
|
def setUp(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
# The super calls needs to happen first for the settings override.
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUp()
|
2013-10-19 06:49:24 +08:00
|
|
|
self.create_table()
|
2009-03-11 21:27:03 +08:00
|
|
|
|
|
|
|
def tearDown(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
# The super call needs to happen first because it uses the database.
|
2017-01-21 21:13:44 +08:00
|
|
|
super().tearDown()
|
2013-10-19 06:49:24 +08:00
|
|
|
self.drop_table()
|
2009-03-11 21:27:03 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
def create_table(self):
|
2017-06-16 20:47:17 +08:00
|
|
|
management.call_command('createcachetable', verbosity=0)
|
2013-10-19 06:49:24 +08:00
|
|
|
|
|
|
|
def drop_table(self):
|
2014-01-09 23:05:15 +08:00
|
|
|
with connection.cursor() as cursor:
|
|
|
|
table_name = connection.ops.quote_name('test cache table')
|
|
|
|
cursor.execute('DROP TABLE %s' % table_name)
|
2010-08-31 08:44:46 +08:00
|
|
|
|
2018-08-02 13:20:46 +08:00
|
|
|
def test_get_many_num_queries(self):
|
|
|
|
cache.set_many({'a': 1, 'b': 2})
|
|
|
|
cache.set('expired', 'expired', 0.01)
|
|
|
|
with self.assertNumQueries(1):
|
|
|
|
self.assertEqual(cache.get_many(['a', 'b']), {'a': 1, 'b': 2})
|
|
|
|
time.sleep(0.02)
|
|
|
|
with self.assertNumQueries(2):
|
|
|
|
self.assertEqual(cache.get_many(['a', 'b', 'expired']), {'a': 1, 'b': 2})
|
|
|
|
|
|
|
|
def test_delete_many_num_queries(self):
|
|
|
|
cache.set_many({'a': 1, 'b': 2, 'c': 3})
|
|
|
|
with self.assertNumQueries(1):
|
|
|
|
cache.delete_many(['a', 'b', 'c'])
|
|
|
|
|
2021-05-26 00:31:26 +08:00
|
|
|
def test_cull_count_queries(self):
|
|
|
|
old_max_entries = cache._max_entries
|
|
|
|
# Force _cull to delete on first cached record.
|
|
|
|
cache._max_entries = -1
|
|
|
|
with CaptureQueriesContext(connection) as captured_queries:
|
|
|
|
try:
|
|
|
|
cache.set('force_cull', 'value', 1000)
|
|
|
|
finally:
|
|
|
|
cache._max_entries = old_max_entries
|
|
|
|
num_count_queries = sum('COUNT' in query['sql'] for query in captured_queries)
|
|
|
|
self.assertEqual(num_count_queries, 1)
|
|
|
|
|
2021-05-02 16:42:23 +08:00
|
|
|
def test_delete_cursor_rowcount(self):
|
|
|
|
"""
|
|
|
|
The rowcount attribute should not be checked on a closed cursor.
|
|
|
|
"""
|
|
|
|
class MockedCursorWrapper(CursorWrapper):
|
|
|
|
is_closed = False
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
self.cursor.close()
|
|
|
|
self.is_closed = True
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rowcount(self):
|
|
|
|
if self.is_closed:
|
|
|
|
raise Exception('Cursor is closed.')
|
|
|
|
return self.cursor.rowcount
|
|
|
|
|
|
|
|
cache.set_many({'a': 1, 'b': 2})
|
|
|
|
with mock.patch('django.db.backends.utils.CursorWrapper', MockedCursorWrapper):
|
|
|
|
self.assertIs(cache.delete('a'), True)
|
|
|
|
|
2010-11-02 13:55:08 +08:00
|
|
|
def test_zero_cull(self):
|
2019-12-15 01:03:24 +08:00
|
|
|
self._perform_cull_test('zero_cull', 50, 18)
|
2010-12-21 23:19:19 +08:00
|
|
|
|
2012-01-09 04:00:30 +08:00
|
|
|
def test_second_call_doesnt_crash(self):
|
2017-01-07 19:11:46 +08:00
|
|
|
out = io.StringIO()
|
2014-10-22 01:15:10 +08:00
|
|
|
management.call_command('createcachetable', stdout=out)
|
2016-04-08 10:04:45 +08:00
|
|
|
self.assertEqual(out.getvalue(), "Cache table 'test cache table' already exists.\n" * len(settings.CACHES))
|
2013-01-06 06:43:01 +08:00
|
|
|
|
2015-04-02 05:33:27 +08:00
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
BACKEND='django.core.cache.backends.db.DatabaseCache',
|
|
|
|
# Use another table name to avoid the 'table already exists' message.
|
|
|
|
LOCATION='createcachetable_dry_run_mode'
|
|
|
|
))
|
|
|
|
def test_createcachetable_dry_run_mode(self):
|
2017-01-07 19:11:46 +08:00
|
|
|
out = io.StringIO()
|
2015-04-02 05:33:27 +08:00
|
|
|
management.call_command('createcachetable', dry_run=True, stdout=out)
|
|
|
|
output = out.getvalue()
|
|
|
|
self.assertTrue(output.startswith("CREATE TABLE"))
|
|
|
|
|
2013-01-06 06:43:01 +08:00
|
|
|
def test_createcachetable_with_table_argument(self):
|
|
|
|
"""
|
|
|
|
Delete and recreate cache table with legacy behavior (explicitly
|
|
|
|
specifying the table name).
|
|
|
|
"""
|
2013-10-19 06:49:24 +08:00
|
|
|
self.drop_table()
|
2017-01-07 19:11:46 +08:00
|
|
|
out = io.StringIO()
|
2013-01-06 06:43:01 +08:00
|
|
|
management.call_command(
|
|
|
|
'createcachetable',
|
2013-10-19 06:49:24 +08:00
|
|
|
'test cache table',
|
2013-01-06 06:43:01 +08:00
|
|
|
verbosity=2,
|
2014-10-22 01:15:10 +08:00
|
|
|
stdout=out,
|
2013-01-06 06:43:01 +08:00
|
|
|
)
|
2016-04-08 10:04:45 +08:00
|
|
|
self.assertEqual(out.getvalue(), "Cache table 'test cache table' created.\n")
|
2012-01-09 04:00:30 +08:00
|
|
|
|
2011-07-05 05:53:17 +08:00
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
@override_settings(USE_TZ=True)
|
|
|
|
class DBCacheWithTimeZoneTests(DBCacheTests):
|
|
|
|
pass
|
2011-11-20 18:17:12 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class DBCacheRouter:
|
2011-11-20 03:56:31 +08:00
|
|
|
"""A router that puts the cache table on the 'other' database."""
|
|
|
|
|
|
|
|
def db_for_read(self, model, **hints):
|
|
|
|
if model._meta.app_label == 'django_cache':
|
|
|
|
return 'other'
|
2015-02-19 15:27:58 +08:00
|
|
|
return None
|
2011-11-20 03:56:31 +08:00
|
|
|
|
|
|
|
def db_for_write(self, model, **hints):
|
|
|
|
if model._meta.app_label == 'django_cache':
|
|
|
|
return 'other'
|
2015-02-19 15:27:58 +08:00
|
|
|
return None
|
2011-11-20 03:56:31 +08:00
|
|
|
|
2015-02-19 15:27:58 +08:00
|
|
|
def allow_migrate(self, db, app_label, **hints):
|
|
|
|
if app_label == 'django_cache':
|
2011-11-20 03:56:31 +08:00
|
|
|
return db == 'other'
|
2015-02-19 15:27:58 +08:00
|
|
|
return None
|
2011-11-20 03:56:31 +08:00
|
|
|
|
|
|
|
|
2013-01-06 06:43:01 +08:00
|
|
|
@override_settings(
|
|
|
|
CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
|
|
|
|
'LOCATION': 'my_cache_table',
|
|
|
|
},
|
|
|
|
},
|
|
|
|
)
|
2011-11-20 03:56:31 +08:00
|
|
|
class CreateCacheTableForDBCacheTests(TestCase):
|
2018-07-12 12:12:20 +08:00
|
|
|
databases = {'default', 'other'}
|
2011-11-20 03:56:31 +08:00
|
|
|
|
2014-11-30 01:09:40 +08:00
|
|
|
@override_settings(DATABASE_ROUTERS=[DBCacheRouter()])
|
2011-11-20 03:56:31 +08:00
|
|
|
def test_createcachetable_observes_database_router(self):
|
2014-11-30 01:09:40 +08:00
|
|
|
# cache table should not be created on 'default'
|
|
|
|
with self.assertNumQueries(0, using='default'):
|
2017-06-16 20:47:17 +08:00
|
|
|
management.call_command('createcachetable', database='default', verbosity=0)
|
2014-11-30 01:09:40 +08:00
|
|
|
# cache table should be created on 'other'
|
|
|
|
# Queries:
|
|
|
|
# 1: check table doesn't already exist
|
|
|
|
# 2: create savepoint (if transactional DDL is supported)
|
|
|
|
# 3: create the table
|
|
|
|
# 4: create the index
|
|
|
|
# 5: release savepoint (if transactional DDL is supported)
|
|
|
|
num = 5 if connections['other'].features.can_rollback_ddl else 3
|
|
|
|
with self.assertNumQueries(num, using='other'):
|
2017-06-16 20:47:17 +08:00
|
|
|
management.call_command('createcachetable', database='other', verbosity=0)
|
2011-11-20 03:56:31 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class PicklingSideEffect:
|
2014-02-08 18:49:27 +08:00
|
|
|
|
|
|
|
def __init__(self, cache):
|
|
|
|
self.cache = cache
|
|
|
|
self.locked = False
|
|
|
|
|
|
|
|
def __getstate__(self):
|
2018-01-25 01:26:19 +08:00
|
|
|
self.locked = self.cache._lock.locked()
|
2014-02-08 18:49:27 +08:00
|
|
|
return {}
|
|
|
|
|
|
|
|
|
2018-01-25 01:26:19 +08:00
|
|
|
limit_locmem_entries = override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
BACKEND='django.core.cache.backends.locmem.LocMemCache',
|
|
|
|
OPTIONS={'MAX_ENTRIES': 9},
|
|
|
|
))
|
|
|
|
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
BACKEND='django.core.cache.backends.locmem.LocMemCache',
|
|
|
|
))
|
|
|
|
class LocMemCacheTests(BaseCacheTests, TestCase):
|
2011-04-03 06:13:21 +08:00
|
|
|
|
2009-03-11 21:27:03 +08:00
|
|
|
def setUp(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUp()
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
# LocMem requires a hack to make the other caches
|
|
|
|
# share a data store with the 'normal' cache.
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['prefix']._cache = cache._cache
|
|
|
|
caches['prefix']._expire_info = cache._expire_info
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['v2']._cache = cache._cache
|
|
|
|
caches['v2']._expire_info = cache._expire_info
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['custom_key']._cache = cache._cache
|
|
|
|
caches['custom_key']._expire_info = cache._expire_info
|
2010-08-31 08:44:46 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['custom_key2']._cache = cache._cache
|
|
|
|
caches['custom_key2']._expire_info = cache._expire_info
|
2010-12-21 23:19:19 +08:00
|
|
|
|
2013-11-24 23:19:47 +08:00
|
|
|
@override_settings(CACHES={
|
|
|
|
'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'},
|
|
|
|
'other': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
|
|
|
'LOCATION': 'other'
|
|
|
|
},
|
|
|
|
})
|
2010-12-22 15:52:44 +08:00
|
|
|
def test_multiple_caches(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"Multiple locmem caches are isolated"
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('value', 42)
|
|
|
|
self.assertEqual(caches['default'].get('value'), 42)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(caches['other'].get('value'))
|
2010-12-22 15:52:44 +08:00
|
|
|
|
2014-02-08 18:49:27 +08:00
|
|
|
def test_locking_on_pickle(self):
|
|
|
|
"""#20613/#18541 -- Ensures pickling is done outside of the lock."""
|
|
|
|
bad_obj = PicklingSideEffect(cache)
|
|
|
|
cache.set('set', bad_obj)
|
|
|
|
self.assertFalse(bad_obj.locked, "Cache was locked during pickling")
|
|
|
|
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertIs(cache.add('add', bad_obj), True)
|
2014-02-08 18:49:27 +08:00
|
|
|
self.assertFalse(bad_obj.locked, "Cache was locked during pickling")
|
|
|
|
|
2011-11-27 06:27:16 +08:00
|
|
|
def test_incr_decr_timeout(self):
|
|
|
|
"""incr/decr does not modify expiry time (matches memcached behavior)"""
|
|
|
|
key = 'value'
|
2013-10-19 06:49:24 +08:00
|
|
|
_key = cache.make_key(key)
|
|
|
|
cache.set(key, 1, timeout=cache.default_timeout * 10)
|
|
|
|
expire = cache._expire_info[_key]
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(cache.incr(key), 2)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(expire, cache._expire_info[_key])
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(cache.decr(key), 1)
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(expire, cache._expire_info[_key])
|
2011-10-27 04:55:36 +08:00
|
|
|
|
2018-01-25 01:26:19 +08:00
|
|
|
@limit_locmem_entries
|
|
|
|
def test_lru_get(self):
|
|
|
|
"""get() moves cache keys."""
|
|
|
|
for key in range(9):
|
|
|
|
cache.set(key, key, timeout=None)
|
|
|
|
for key in range(6):
|
|
|
|
self.assertEqual(cache.get(key), key)
|
|
|
|
cache.set(9, 9, timeout=None)
|
|
|
|
for key in range(6):
|
|
|
|
self.assertEqual(cache.get(key), key)
|
|
|
|
for key in range(6, 9):
|
|
|
|
self.assertIsNone(cache.get(key))
|
|
|
|
self.assertEqual(cache.get(9), 9)
|
|
|
|
|
|
|
|
@limit_locmem_entries
|
|
|
|
def test_lru_set(self):
|
|
|
|
"""set() moves cache keys."""
|
|
|
|
for key in range(9):
|
|
|
|
cache.set(key, key, timeout=None)
|
|
|
|
for key in range(3, 9):
|
|
|
|
cache.set(key, key, timeout=None)
|
|
|
|
cache.set(9, 9, timeout=None)
|
|
|
|
for key in range(3, 10):
|
|
|
|
self.assertEqual(cache.get(key), key)
|
|
|
|
for key in range(3):
|
|
|
|
self.assertIsNone(cache.get(key))
|
|
|
|
|
|
|
|
@limit_locmem_entries
|
|
|
|
def test_lru_incr(self):
|
|
|
|
"""incr() moves cache keys."""
|
|
|
|
for key in range(9):
|
|
|
|
cache.set(key, key, timeout=None)
|
|
|
|
for key in range(6):
|
2019-12-11 12:27:03 +08:00
|
|
|
self.assertEqual(cache.incr(key), key + 1)
|
2018-01-25 01:26:19 +08:00
|
|
|
cache.set(9, 9, timeout=None)
|
|
|
|
for key in range(6):
|
|
|
|
self.assertEqual(cache.get(key), key + 1)
|
|
|
|
for key in range(6, 9):
|
|
|
|
self.assertIsNone(cache.get(key))
|
|
|
|
self.assertEqual(cache.get(9), 9)
|
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2021-05-24 08:01:50 +08:00
|
|
|
# memcached and redis backends aren't guaranteed to be available.
|
|
|
|
# To check the backends, the test settings file will need to contain at least
|
|
|
|
# one cache backend setting that points at your cache server.
|
2016-08-29 22:23:54 +08:00
|
|
|
configured_caches = {}
|
2013-10-19 06:49:24 +08:00
|
|
|
for _cache_params in settings.CACHES.values():
|
2016-08-29 22:23:54 +08:00
|
|
|
configured_caches[_cache_params['BACKEND']] = _cache_params
|
|
|
|
|
|
|
|
PyLibMCCache_params = configured_caches.get('django.core.cache.backends.memcached.PyLibMCCache')
|
2019-01-19 07:26:50 +08:00
|
|
|
PyMemcacheCache_params = configured_caches.get('django.core.cache.backends.memcached.PyMemcacheCache')
|
2011-04-03 06:13:21 +08:00
|
|
|
|
2016-08-27 02:29:22 +08:00
|
|
|
# The memcached backends don't support cull-related options like `MAX_ENTRIES`.
|
|
|
|
memcached_excluded_caches = {'cull', 'zero_cull'}
|
2014-06-16 16:46:34 +08:00
|
|
|
|
2021-05-24 08:01:50 +08:00
|
|
|
RedisCache_params = configured_caches.get('django.core.cache.backends.redis.RedisCache')
|
|
|
|
|
|
|
|
# The redis backend does not support cull-related options like `MAX_ENTRIES`.
|
|
|
|
redis_excluded_caches = {'cull', 'zero_cull'}
|
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2016-08-29 22:23:54 +08:00
|
|
|
class BaseMemcachedTests(BaseCacheTests):
|
2010-11-02 13:55:08 +08:00
|
|
|
|
2016-09-02 16:33:59 +08:00
|
|
|
# By default it's assumed that the client doesn't clean up connections
|
|
|
|
# properly, in which case the backend must do so after each request.
|
|
|
|
should_disconnect_on_close = True
|
|
|
|
|
2016-09-01 01:14:29 +08:00
|
|
|
def test_location_multiple_servers(self):
|
|
|
|
locations = [
|
|
|
|
['server1.tld', 'server2:11211'],
|
|
|
|
'server1.tld;server2:11211',
|
2016-09-01 01:15:22 +08:00
|
|
|
'server1.tld,server2:11211',
|
2016-09-01 01:14:29 +08:00
|
|
|
]
|
|
|
|
for location in locations:
|
2017-03-08 05:00:43 +08:00
|
|
|
with self.subTest(location=location):
|
|
|
|
params = {'BACKEND': self.base_params['BACKEND'], 'LOCATION': location}
|
|
|
|
with self.settings(CACHES={'default': params}):
|
|
|
|
self.assertEqual(cache._servers, ['server1.tld', 'server2:11211'])
|
2016-09-01 01:14:29 +08:00
|
|
|
|
2020-05-20 17:45:31 +08:00
|
|
|
def _perform_invalid_key_test(self, key, expected_warning):
|
2010-11-02 13:55:08 +08:00
|
|
|
"""
|
2020-05-26 00:05:22 +08:00
|
|
|
While other backends merely warn, memcached should raise for an invalid
|
|
|
|
key.
|
2010-11-02 13:55:08 +08:00
|
|
|
"""
|
2020-06-03 18:37:37 +08:00
|
|
|
msg = expected_warning.replace(key, cache.make_key(key))
|
2020-08-21 00:18:25 +08:00
|
|
|
tests = [
|
|
|
|
('add', [key, 1]),
|
2020-08-19 21:05:05 +08:00
|
|
|
('get', [key]),
|
2020-08-21 00:18:25 +08:00
|
|
|
('set', [key, 1]),
|
|
|
|
('incr', [key]),
|
|
|
|
('decr', [key]),
|
2020-08-19 21:05:05 +08:00
|
|
|
('touch', [key]),
|
|
|
|
('delete', [key]),
|
2020-08-21 00:18:25 +08:00
|
|
|
('get_many', [[key, 'b']]),
|
|
|
|
('set_many', [{key: 1, 'b': 2}]),
|
2021-08-27 03:19:36 +08:00
|
|
|
('delete_many', [[key, 'b']]),
|
2020-08-21 00:18:25 +08:00
|
|
|
]
|
|
|
|
for operation, args in tests:
|
|
|
|
with self.subTest(operation=operation):
|
|
|
|
with self.assertRaises(InvalidCacheKey) as cm:
|
|
|
|
getattr(cache, operation)(*args)
|
|
|
|
self.assertEqual(str(cm.exception), msg)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2021-09-03 17:13:39 +08:00
|
|
|
def test_invalid_with_version_key_length(self):
|
|
|
|
# make_key() adds a version to the key and exceeds the limit.
|
|
|
|
key = 'a' * 248
|
|
|
|
expected_warning = (
|
|
|
|
'Cache key will cause errors if used with memcached: '
|
|
|
|
'%r (longer than %s)' % (key, 250)
|
|
|
|
)
|
|
|
|
self._perform_invalid_key_test(key, expected_warning)
|
|
|
|
|
2014-06-16 16:46:34 +08:00
|
|
|
def test_default_never_expiring_timeout(self):
|
|
|
|
# Regression test for #22845
|
2016-08-29 22:23:54 +08:00
|
|
|
with self.settings(CACHES=caches_setting_for_tests(
|
|
|
|
base=self.base_params,
|
|
|
|
exclude=memcached_excluded_caches,
|
|
|
|
TIMEOUT=None)):
|
|
|
|
cache.set('infinite_foo', 'bar')
|
|
|
|
self.assertEqual(cache.get('infinite_foo'), 'bar')
|
2014-06-16 16:46:34 +08:00
|
|
|
|
|
|
|
def test_default_far_future_timeout(self):
|
|
|
|
# Regression test for #22845
|
2016-08-29 22:23:54 +08:00
|
|
|
with self.settings(CACHES=caches_setting_for_tests(
|
|
|
|
base=self.base_params,
|
|
|
|
exclude=memcached_excluded_caches,
|
|
|
|
# 60*60*24*365, 1 year
|
|
|
|
TIMEOUT=31536000)):
|
|
|
|
cache.set('future_foo', 'bar')
|
|
|
|
self.assertEqual(cache.get('future_foo'), 'bar')
|
2014-06-16 16:46:34 +08:00
|
|
|
|
2014-11-07 12:47:04 +08:00
|
|
|
def test_memcached_deletes_key_on_failed_set(self):
|
|
|
|
# By default memcached allows objects up to 1MB. For the cache_db session
|
|
|
|
# backend to always use the current session, memcached needs to delete
|
|
|
|
# the old key if it fails to set.
|
2020-12-10 04:27:32 +08:00
|
|
|
max_value_length = 2 ** 20
|
2014-11-07 12:47:04 +08:00
|
|
|
|
|
|
|
cache.set('small_value', 'a')
|
|
|
|
self.assertEqual(cache.get('small_value'), 'a')
|
|
|
|
|
|
|
|
large_value = 'a' * (max_value_length + 1)
|
2016-08-29 22:24:36 +08:00
|
|
|
try:
|
|
|
|
cache.set('small_value', large_value)
|
|
|
|
except Exception:
|
2020-12-10 04:27:32 +08:00
|
|
|
# Most clients (e.g. pymemcache or pylibmc) raise when the value is
|
|
|
|
# too large. This test is primarily checking that the key was
|
|
|
|
# deleted, so the return/exception behavior for the set() itself is
|
|
|
|
# not important.
|
2016-08-29 22:24:36 +08:00
|
|
|
pass
|
2014-11-07 12:47:04 +08:00
|
|
|
# small_value should be deleted, or set if configured to accept larger values
|
|
|
|
value = cache.get('small_value')
|
|
|
|
self.assertTrue(value is None or value == large_value)
|
|
|
|
|
2016-09-02 16:33:59 +08:00
|
|
|
def test_close(self):
|
|
|
|
# For clients that don't manage their connections properly, the
|
|
|
|
# connection is closed when the request is complete.
|
2016-09-15 02:25:09 +08:00
|
|
|
signals.request_finished.disconnect(close_old_connections)
|
|
|
|
try:
|
2020-08-15 06:17:04 +08:00
|
|
|
with mock.patch.object(cache._class, 'disconnect_all', autospec=True) as mock_disconnect:
|
2016-09-15 02:25:09 +08:00
|
|
|
signals.request_finished.send(self.__class__)
|
|
|
|
self.assertIs(mock_disconnect.called, self.should_disconnect_on_close)
|
|
|
|
finally:
|
|
|
|
signals.request_finished.connect(close_old_connections)
|
2016-09-02 16:33:59 +08:00
|
|
|
|
2016-11-06 19:57:38 +08:00
|
|
|
def test_set_many_returns_failing_keys(self):
|
|
|
|
def fail_set_multi(mapping, *args, **kwargs):
|
|
|
|
return mapping.keys()
|
2020-08-15 06:17:04 +08:00
|
|
|
with mock.patch.object(cache._class, 'set_multi', side_effect=fail_set_multi):
|
2016-11-06 19:57:38 +08:00
|
|
|
failing_keys = cache.set_many({'key': 'value'})
|
|
|
|
self.assertEqual(failing_keys, ['key'])
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
|
2016-08-29 22:23:54 +08:00
|
|
|
@unittest.skipUnless(PyLibMCCache_params, "PyLibMCCache backend not configured")
|
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
base=PyLibMCCache_params,
|
|
|
|
exclude=memcached_excluded_caches,
|
|
|
|
))
|
|
|
|
class PyLibMCCacheTests(BaseMemcachedTests, TestCase):
|
|
|
|
base_params = PyLibMCCache_params
|
2016-09-02 16:33:59 +08:00
|
|
|
# libmemcached manages its own connections.
|
|
|
|
should_disconnect_on_close = False
|
2016-08-29 22:23:54 +08:00
|
|
|
|
2020-12-14 18:42:22 +08:00
|
|
|
@property
|
|
|
|
def incr_decr_type_error(self):
|
|
|
|
return cache._lib.ClientError
|
|
|
|
|
2016-08-31 20:12:40 +08:00
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
base=PyLibMCCache_params,
|
|
|
|
exclude=memcached_excluded_caches,
|
|
|
|
OPTIONS={
|
|
|
|
'binary': True,
|
|
|
|
'behaviors': {'tcp_nodelay': True},
|
|
|
|
},
|
|
|
|
))
|
|
|
|
def test_pylibmc_options(self):
|
|
|
|
self.assertTrue(cache._cache.binary)
|
|
|
|
self.assertEqual(cache._cache.behaviors['tcp_nodelay'], int(True))
|
|
|
|
|
2020-08-16 04:34:32 +08:00
|
|
|
def test_pylibmc_client_servers(self):
|
|
|
|
backend = self.base_params['BACKEND']
|
|
|
|
tests = [
|
|
|
|
('unix:/run/memcached/socket', '/run/memcached/socket'),
|
|
|
|
('/run/memcached/socket', '/run/memcached/socket'),
|
2020-09-02 17:56:23 +08:00
|
|
|
('localhost', 'localhost'),
|
|
|
|
('localhost:11211', 'localhost:11211'),
|
|
|
|
('[::1]', '[::1]'),
|
|
|
|
('[::1]:11211', '[::1]:11211'),
|
|
|
|
('127.0.0.1', '127.0.0.1'),
|
2020-08-16 04:34:32 +08:00
|
|
|
('127.0.0.1:11211', '127.0.0.1:11211'),
|
|
|
|
]
|
|
|
|
for location, expected in tests:
|
|
|
|
settings = {'default': {'BACKEND': backend, 'LOCATION': location}}
|
|
|
|
with self.subTest(location), self.settings(CACHES=settings):
|
|
|
|
self.assertEqual(cache.client_servers, [expected])
|
|
|
|
|
2016-08-29 22:23:54 +08:00
|
|
|
|
2019-01-19 07:26:50 +08:00
|
|
|
@unittest.skipUnless(PyMemcacheCache_params, 'PyMemcacheCache backend not configured')
|
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
base=PyMemcacheCache_params,
|
|
|
|
exclude=memcached_excluded_caches,
|
|
|
|
))
|
|
|
|
class PyMemcacheCacheTests(BaseMemcachedTests, TestCase):
|
|
|
|
base_params = PyMemcacheCache_params
|
|
|
|
|
2020-12-14 18:42:22 +08:00
|
|
|
@property
|
|
|
|
def incr_decr_type_error(self):
|
|
|
|
return cache._lib.exceptions.MemcacheClientError
|
|
|
|
|
2019-01-19 07:26:50 +08:00
|
|
|
def test_pymemcache_highest_pickle_version(self):
|
|
|
|
self.assertEqual(
|
|
|
|
cache._cache.default_kwargs['serde']._serialize_func.keywords['pickle_version'],
|
|
|
|
pickle.HIGHEST_PROTOCOL,
|
|
|
|
)
|
|
|
|
for cache_key in settings.CACHES:
|
|
|
|
for client_key, client in caches[cache_key]._cache.clients.items():
|
|
|
|
with self.subTest(cache_key=cache_key, server=client_key):
|
|
|
|
self.assertEqual(
|
|
|
|
client.serde._serialize_func.keywords['pickle_version'],
|
|
|
|
pickle.HIGHEST_PROTOCOL,
|
|
|
|
)
|
|
|
|
|
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
base=PyMemcacheCache_params,
|
|
|
|
exclude=memcached_excluded_caches,
|
|
|
|
OPTIONS={'no_delay': True},
|
|
|
|
))
|
|
|
|
def test_pymemcache_options(self):
|
|
|
|
self.assertIs(cache._cache.default_kwargs['no_delay'], True)
|
|
|
|
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
BACKEND='django.core.cache.backends.filebased.FileBasedCache',
|
|
|
|
))
|
|
|
|
class FileBasedCacheTests(BaseCacheTests, TestCase):
|
2007-12-05 02:03:56 +08:00
|
|
|
"""
|
|
|
|
Specific test cases for the file-based cache.
|
|
|
|
"""
|
2011-04-03 06:13:21 +08:00
|
|
|
|
2007-12-05 02:03:56 +08:00
|
|
|
def setUp(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUp()
|
2019-11-06 17:01:01 +08:00
|
|
|
self.dirname = self.mkdtemp()
|
2014-10-19 02:03:10 +08:00
|
|
|
# Caches location cannot be modified through override_settings / modify_settings,
|
|
|
|
# hence settings are manipulated directly here and the setting_changed signal
|
|
|
|
# is triggered manually.
|
2013-10-19 06:49:24 +08:00
|
|
|
for cache_params in settings.CACHES.values():
|
2019-11-06 17:01:01 +08:00
|
|
|
cache_params['LOCATION'] = self.dirname
|
2014-10-19 02:03:10 +08:00
|
|
|
setting_changed.send(self.__class__, setting='CACHES', enter=False)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
|
|
|
def tearDown(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().tearDown()
|
2014-06-23 20:05:57 +08:00
|
|
|
# Call parent first, as cache.clear() may recreate cache base directory
|
|
|
|
shutil.rmtree(self.dirname)
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2019-11-06 17:01:01 +08:00
|
|
|
def mkdtemp(self):
|
|
|
|
return tempfile.mkdtemp()
|
|
|
|
|
2013-08-26 22:34:02 +08:00
|
|
|
def test_ignores_non_cache_files(self):
|
|
|
|
fname = os.path.join(self.dirname, 'not-a-cache-file')
|
|
|
|
with open(fname, 'w'):
|
|
|
|
os.utime(fname, None)
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.clear()
|
2013-08-26 22:34:02 +08:00
|
|
|
self.assertTrue(os.path.exists(fname),
|
|
|
|
'Expected cache.clear to ignore non cache files')
|
|
|
|
os.remove(fname)
|
2007-12-05 02:03:56 +08:00
|
|
|
|
2013-08-26 22:34:02 +08:00
|
|
|
def test_clear_does_not_remove_cache_dir(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.clear()
|
2013-08-26 22:34:02 +08:00
|
|
|
self.assertTrue(os.path.exists(self.dirname),
|
|
|
|
'Expected cache.clear to keep the cache dir')
|
2007-11-19 11:12:19 +08:00
|
|
|
|
2013-08-26 22:34:02 +08:00
|
|
|
def test_creates_cache_dir_if_nonexistent(self):
|
|
|
|
os.rmdir(self.dirname)
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.set('foo', 'bar')
|
2019-01-27 05:38:46 +08:00
|
|
|
self.assertTrue(os.path.exists(self.dirname))
|
2013-08-26 22:34:02 +08:00
|
|
|
|
2016-06-02 03:29:24 +08:00
|
|
|
def test_get_ignores_enoent(self):
|
|
|
|
cache.set('foo', 'bar')
|
|
|
|
os.unlink(cache._key_to_file('foo'))
|
|
|
|
# Returns the default instead of erroring.
|
|
|
|
self.assertEqual(cache.get('foo', 'baz'), 'baz')
|
|
|
|
|
2020-08-21 18:43:45 +08:00
|
|
|
@skipIf(
|
|
|
|
sys.platform == 'win32',
|
|
|
|
'Windows only partially supports umasks and chmod.',
|
|
|
|
)
|
|
|
|
def test_cache_dir_permissions(self):
|
|
|
|
os.rmdir(self.dirname)
|
|
|
|
dir_path = Path(self.dirname) / 'nested' / 'filebasedcache'
|
|
|
|
for cache_params in settings.CACHES.values():
|
|
|
|
cache_params['LOCATION'] = dir_path
|
|
|
|
setting_changed.send(self.__class__, setting='CACHES', enter=False)
|
|
|
|
cache.set('foo', 'bar')
|
|
|
|
self.assertIs(dir_path.exists(), True)
|
|
|
|
tests = [
|
|
|
|
dir_path,
|
|
|
|
dir_path.parent,
|
|
|
|
dir_path.parent.parent,
|
|
|
|
]
|
|
|
|
for directory in tests:
|
|
|
|
with self.subTest(directory=directory):
|
|
|
|
dir_mode = directory.stat().st_mode & 0o777
|
|
|
|
self.assertEqual(dir_mode, 0o700)
|
|
|
|
|
2017-01-25 23:13:08 +08:00
|
|
|
def test_get_does_not_ignore_non_filenotfound_exceptions(self):
|
2019-01-28 23:01:35 +08:00
|
|
|
with mock.patch('builtins.open', side_effect=OSError):
|
|
|
|
with self.assertRaises(OSError):
|
2016-06-02 03:29:24 +08:00
|
|
|
cache.get('foo')
|
|
|
|
|
2017-08-31 12:22:26 +08:00
|
|
|
def test_empty_cache_file_considered_expired(self):
|
|
|
|
cache_file = cache._key_to_file('foo')
|
|
|
|
with open(cache_file, 'wb') as fh:
|
|
|
|
fh.write(b'')
|
|
|
|
with open(cache_file, 'rb') as fh:
|
|
|
|
self.assertIs(cache._is_expired(fh), True)
|
|
|
|
|
2010-08-31 08:44:46 +08:00
|
|
|
|
2021-05-24 08:01:50 +08:00
|
|
|
@unittest.skipUnless(RedisCache_params, "Redis backend not configured")
|
|
|
|
@override_settings(CACHES=caches_setting_for_tests(
|
|
|
|
base=RedisCache_params,
|
|
|
|
exclude=redis_excluded_caches,
|
|
|
|
))
|
|
|
|
class RedisCacheTests(BaseCacheTests, TestCase):
|
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
import redis
|
|
|
|
super().setUp()
|
|
|
|
self.lib = redis
|
|
|
|
|
|
|
|
@property
|
|
|
|
def incr_decr_type_error(self):
|
|
|
|
return self.lib.ResponseError
|
|
|
|
|
|
|
|
def test_cache_client_class(self):
|
|
|
|
self.assertIs(cache._class, RedisCacheClient)
|
|
|
|
self.assertIsInstance(cache._cache, RedisCacheClient)
|
|
|
|
|
|
|
|
def test_get_backend_timeout_method(self):
|
|
|
|
positive_timeout = 10
|
|
|
|
positive_backend_timeout = cache.get_backend_timeout(positive_timeout)
|
|
|
|
self.assertEqual(positive_backend_timeout, positive_timeout)
|
|
|
|
|
|
|
|
negative_timeout = -5
|
|
|
|
negative_backend_timeout = cache.get_backend_timeout(negative_timeout)
|
|
|
|
self.assertEqual(negative_backend_timeout, 0)
|
|
|
|
|
|
|
|
none_timeout = None
|
|
|
|
none_backend_timeout = cache.get_backend_timeout(none_timeout)
|
|
|
|
self.assertIsNone(none_backend_timeout)
|
|
|
|
|
|
|
|
def test_get_connection_pool_index(self):
|
|
|
|
pool_index = cache._cache._get_connection_pool_index(write=True)
|
|
|
|
self.assertEqual(pool_index, 0)
|
|
|
|
pool_index = cache._cache._get_connection_pool_index(write=False)
|
|
|
|
if len(cache._cache._servers) == 1:
|
|
|
|
self.assertEqual(pool_index, 0)
|
|
|
|
else:
|
|
|
|
self.assertGreater(pool_index, 0)
|
|
|
|
self.assertLess(pool_index, len(cache._cache._servers))
|
|
|
|
|
|
|
|
def test_get_connection_pool(self):
|
|
|
|
pool = cache._cache._get_connection_pool(write=True)
|
|
|
|
self.assertIsInstance(pool, self.lib.ConnectionPool)
|
|
|
|
|
|
|
|
pool = cache._cache._get_connection_pool(write=False)
|
|
|
|
self.assertIsInstance(pool, self.lib.ConnectionPool)
|
|
|
|
|
|
|
|
def test_get_client(self):
|
|
|
|
self.assertIsInstance(cache._cache.get_client(), self.lib.Redis)
|
|
|
|
|
|
|
|
|
2019-11-06 17:01:01 +08:00
|
|
|
class FileBasedCachePathLibTests(FileBasedCacheTests):
|
|
|
|
def mkdtemp(self):
|
|
|
|
tmp_dir = super().mkdtemp()
|
|
|
|
return Path(tmp_dir)
|
|
|
|
|
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
@override_settings(CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'cache.liberal_backend.CacheClass',
|
|
|
|
},
|
|
|
|
})
|
2015-04-18 05:38:20 +08:00
|
|
|
class CustomCacheKeyValidationTests(SimpleTestCase):
|
2010-09-13 02:45:26 +08:00
|
|
|
"""
|
|
|
|
Tests for the ability to mixin a custom ``validate_key`` method to
|
|
|
|
a custom cache backend that otherwise inherits from a builtin
|
|
|
|
backend, and override the default key validation. Refs #6447.
|
|
|
|
"""
|
|
|
|
def test_custom_key_validation(self):
|
|
|
|
# this key is both longer than 250 characters, and has spaces
|
|
|
|
key = 'some key with spaces' * 15
|
|
|
|
val = 'a value'
|
|
|
|
cache.set(key, val)
|
|
|
|
self.assertEqual(cache.get(key), val)
|
|
|
|
|
2011-07-05 17:10:58 +08:00
|
|
|
|
2013-11-24 23:19:47 +08:00
|
|
|
@override_settings(
|
|
|
|
CACHES={
|
2013-11-25 11:07:21 +08:00
|
|
|
'default': {
|
|
|
|
'BACKEND': 'cache.closeable_cache.CacheClass',
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
2015-04-18 05:38:20 +08:00
|
|
|
class CacheClosingTests(SimpleTestCase):
|
2011-07-05 17:10:58 +08:00
|
|
|
|
2012-02-10 02:58:25 +08:00
|
|
|
def test_close(self):
|
2013-11-24 23:19:47 +08:00
|
|
|
self.assertFalse(cache.closed)
|
|
|
|
signals.request_finished.send(self.__class__)
|
|
|
|
self.assertTrue(cache.closed)
|
|
|
|
|
2021-05-14 17:53:17 +08:00
|
|
|
def test_close_only_initialized(self):
|
|
|
|
with self.settings(CACHES={
|
|
|
|
'cache_1': {
|
|
|
|
'BACKEND': 'cache.closeable_cache.CacheClass',
|
|
|
|
},
|
|
|
|
'cache_2': {
|
|
|
|
'BACKEND': 'cache.closeable_cache.CacheClass',
|
|
|
|
},
|
|
|
|
}):
|
|
|
|
self.assertEqual(caches.all(initialized_only=True), [])
|
|
|
|
signals.request_finished.send(self.__class__)
|
|
|
|
self.assertEqual(caches.all(initialized_only=True), [])
|
|
|
|
|
2011-10-27 04:55:36 +08:00
|
|
|
|
2014-02-24 06:58:26 +08:00
|
|
|
DEFAULT_MEMORY_CACHES_SETTINGS = {
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
|
|
|
'LOCATION': 'unique-snowflake',
|
|
|
|
}
|
|
|
|
}
|
|
|
|
NEVER_EXPIRING_CACHES_SETTINGS = copy.deepcopy(DEFAULT_MEMORY_CACHES_SETTINGS)
|
|
|
|
NEVER_EXPIRING_CACHES_SETTINGS['default']['TIMEOUT'] = None
|
|
|
|
|
|
|
|
|
2015-04-18 05:38:20 +08:00
|
|
|
class DefaultNonExpiringCacheKeyTests(SimpleTestCase):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""
|
|
|
|
Settings having Cache arguments with a TIMEOUT=None create Caches that will
|
|
|
|
set non-expiring keys.
|
2014-02-24 06:58:26 +08:00
|
|
|
"""
|
|
|
|
def setUp(self):
|
|
|
|
# The 5 minute (300 seconds) default expiration time for keys is
|
|
|
|
# defined in the implementation of the initializer method of the
|
|
|
|
# BaseCache type.
|
|
|
|
self.DEFAULT_TIMEOUT = caches[DEFAULT_CACHE_ALIAS].default_timeout
|
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
del(self.DEFAULT_TIMEOUT)
|
|
|
|
|
|
|
|
def test_default_expiration_time_for_keys_is_5_minutes(self):
|
|
|
|
"""The default expiration time of a cache key is 5 minutes.
|
|
|
|
|
2016-10-27 15:53:39 +08:00
|
|
|
This value is defined in
|
|
|
|
django.core.cache.backends.base.BaseCache.__init__().
|
2014-02-24 06:58:26 +08:00
|
|
|
"""
|
2014-03-10 04:37:05 +08:00
|
|
|
self.assertEqual(300, self.DEFAULT_TIMEOUT)
|
2014-02-24 06:58:26 +08:00
|
|
|
|
|
|
|
def test_caches_with_unset_timeout_has_correct_default_timeout(self):
|
|
|
|
"""Caches that have the TIMEOUT parameter undefined in the default
|
|
|
|
settings will use the default 5 minute timeout.
|
|
|
|
"""
|
|
|
|
cache = caches[DEFAULT_CACHE_ALIAS]
|
2014-03-10 04:37:05 +08:00
|
|
|
self.assertEqual(self.DEFAULT_TIMEOUT, cache.default_timeout)
|
2014-02-24 06:58:26 +08:00
|
|
|
|
|
|
|
@override_settings(CACHES=NEVER_EXPIRING_CACHES_SETTINGS)
|
|
|
|
def test_caches_set_with_timeout_as_none_has_correct_default_timeout(self):
|
|
|
|
"""Memory caches that have the TIMEOUT parameter set to `None` in the
|
|
|
|
default settings with have `None` as the default timeout.
|
|
|
|
|
|
|
|
This means "no timeout".
|
|
|
|
"""
|
|
|
|
cache = caches[DEFAULT_CACHE_ALIAS]
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache.default_timeout)
|
|
|
|
self.assertIsNone(cache.get_backend_timeout())
|
2014-02-24 06:58:26 +08:00
|
|
|
|
|
|
|
@override_settings(CACHES=DEFAULT_MEMORY_CACHES_SETTINGS)
|
|
|
|
def test_caches_with_unset_timeout_set_expiring_key(self):
|
|
|
|
"""Memory caches that have the TIMEOUT parameter unset will set cache
|
|
|
|
keys having the default 5 minute timeout.
|
|
|
|
"""
|
|
|
|
key = "my-key"
|
|
|
|
value = "my-value"
|
|
|
|
cache = caches[DEFAULT_CACHE_ALIAS]
|
|
|
|
cache.set(key, value)
|
|
|
|
cache_key = cache.make_key(key)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(cache._expire_info[cache_key])
|
2014-02-24 06:58:26 +08:00
|
|
|
|
|
|
|
@override_settings(CACHES=NEVER_EXPIRING_CACHES_SETTINGS)
|
2016-03-06 16:48:06 +08:00
|
|
|
def test_caches_set_with_timeout_as_none_set_non_expiring_key(self):
|
2014-02-24 06:58:26 +08:00
|
|
|
"""Memory caches that have the TIMEOUT parameter set to `None` will set
|
|
|
|
a non expiring key by default.
|
|
|
|
"""
|
|
|
|
key = "another-key"
|
|
|
|
value = "another-value"
|
|
|
|
cache = caches[DEFAULT_CACHE_ALIAS]
|
|
|
|
cache.set(key, value)
|
|
|
|
cache_key = cache.make_key(key)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(cache._expire_info[cache_key])
|
2014-02-24 06:58:26 +08:00
|
|
|
|
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
|
|
|
|
CACHE_MIDDLEWARE_SECONDS=1,
|
|
|
|
CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
2012-03-30 17:08:29 +08:00
|
|
|
},
|
2013-10-20 07:33:10 +08:00
|
|
|
},
|
|
|
|
USE_I18N=False,
|
2016-06-04 06:02:38 +08:00
|
|
|
ALLOWED_HOSTS=['.example.com'],
|
2012-03-30 17:08:29 +08:00
|
|
|
)
|
2015-04-18 05:38:20 +08:00
|
|
|
class CacheUtils(SimpleTestCase):
|
2007-11-19 11:12:19 +08:00
|
|
|
"""TestCase for django.utils.cache functions."""
|
2018-11-27 03:01:27 +08:00
|
|
|
host = 'www.example.com'
|
|
|
|
path = '/cache/test/'
|
|
|
|
factory = RequestFactory(HTTP_HOST=host)
|
2013-12-27 12:14:08 +08:00
|
|
|
|
2015-01-09 01:47:45 +08:00
|
|
|
def tearDown(self):
|
|
|
|
cache.clear()
|
|
|
|
|
2013-12-27 12:14:08 +08:00
|
|
|
def _get_request_cache(self, method='GET', query_string=None, update_cache=None):
|
|
|
|
request = self._get_request(self.host, self.path,
|
|
|
|
method, query_string=query_string)
|
2020-09-25 00:37:55 +08:00
|
|
|
request._cache_update_cache = update_cache if update_cache else True
|
2013-12-27 12:14:08 +08:00
|
|
|
return request
|
|
|
|
|
2007-11-19 11:12:19 +08:00
|
|
|
def test_patch_vary_headers(self):
|
2008-08-02 13:56:57 +08:00
|
|
|
headers = (
|
2007-11-19 11:12:19 +08:00
|
|
|
# Initial vary, new headers, resulting vary.
|
|
|
|
(None, ('Accept-Encoding',), 'Accept-Encoding'),
|
|
|
|
('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
|
|
|
|
('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
|
|
|
|
('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
|
|
|
|
('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
|
|
|
|
('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
|
|
|
|
(None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
|
|
|
|
('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
|
|
|
|
('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
|
2019-08-14 04:40:09 +08:00
|
|
|
('*', ('Accept-Language', 'Cookie'), '*'),
|
|
|
|
('Accept-Language, Cookie', ('*',), '*'),
|
2007-11-19 11:12:19 +08:00
|
|
|
)
|
|
|
|
for initial_vary, newheaders, resulting_vary in headers:
|
2017-03-08 05:00:43 +08:00
|
|
|
with self.subTest(initial_vary=initial_vary, newheaders=newheaders):
|
|
|
|
response = HttpResponse()
|
|
|
|
if initial_vary is not None:
|
2020-07-14 19:32:24 +08:00
|
|
|
response.headers['Vary'] = initial_vary
|
2017-03-08 05:00:43 +08:00
|
|
|
patch_vary_headers(response, newheaders)
|
2020-07-14 19:32:24 +08:00
|
|
|
self.assertEqual(response.headers['Vary'], resulting_vary)
|
2007-11-19 11:12:19 +08:00
|
|
|
|
2009-04-02 02:19:32 +08:00
|
|
|
def test_get_cache_key(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
2009-04-02 02:19:32 +08:00
|
|
|
response = HttpResponse()
|
|
|
|
# Expect None if no headers have been set yet.
|
2015-01-09 01:47:45 +08:00
|
|
|
self.assertIsNone(get_cache_key(request))
|
2009-04-02 02:19:32 +08:00
|
|
|
# Set headers to an empty list.
|
|
|
|
learn_cache_key(request, response)
|
2013-12-27 12:14:08 +08:00
|
|
|
|
|
|
|
self.assertEqual(
|
|
|
|
get_cache_key(request),
|
|
|
|
'views.decorators.cache.cache_page.settingsprefix.GET.'
|
|
|
|
'18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e'
|
|
|
|
)
|
2016-10-27 15:53:39 +08:00
|
|
|
# A specified key_prefix is taken into account.
|
2014-12-07 02:59:49 +08:00
|
|
|
key_prefix = 'localprefix'
|
2009-04-02 02:19:32 +08:00
|
|
|
learn_cache_key(request, response, key_prefix=key_prefix)
|
2013-12-27 12:14:08 +08:00
|
|
|
self.assertEqual(
|
|
|
|
get_cache_key(request, key_prefix=key_prefix),
|
|
|
|
'views.decorators.cache.cache_page.localprefix.GET.'
|
|
|
|
'18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e'
|
|
|
|
)
|
2009-04-02 02:19:32 +08:00
|
|
|
|
2011-03-02 20:47:36 +08:00
|
|
|
def test_get_cache_key_with_query(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path, {'test': 1})
|
2011-03-02 20:47:36 +08:00
|
|
|
response = HttpResponse()
|
|
|
|
# Expect None if no headers have been set yet.
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(get_cache_key(request))
|
2011-03-02 20:47:36 +08:00
|
|
|
# Set headers to an empty list.
|
|
|
|
learn_cache_key(request, response)
|
2016-10-27 15:53:39 +08:00
|
|
|
# The querystring is taken into account.
|
2013-12-27 12:14:08 +08:00
|
|
|
self.assertEqual(
|
|
|
|
get_cache_key(request),
|
|
|
|
'views.decorators.cache.cache_page.settingsprefix.GET.'
|
|
|
|
'beaf87a9a99ee81c673ea2d67ccbec2a.d41d8cd98f00b204e9800998ecf8427e'
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_cache_key_varies_by_url(self):
|
|
|
|
"""
|
2014-03-02 22:25:53 +08:00
|
|
|
get_cache_key keys differ by fully-qualified URL instead of path
|
2013-12-27 12:14:08 +08:00
|
|
|
"""
|
|
|
|
request1 = self.factory.get(self.path, HTTP_HOST='sub-1.example.com')
|
|
|
|
learn_cache_key(request1, HttpResponse())
|
|
|
|
request2 = self.factory.get(self.path, HTTP_HOST='sub-2.example.com')
|
|
|
|
learn_cache_key(request2, HttpResponse())
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertNotEqual(get_cache_key(request1), get_cache_key(request2))
|
2011-03-02 20:47:36 +08:00
|
|
|
|
2009-04-02 02:19:32 +08:00
|
|
|
def test_learn_cache_key(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.head(self.path)
|
2009-04-02 02:19:32 +08:00
|
|
|
response = HttpResponse()
|
2020-07-14 19:32:24 +08:00
|
|
|
response.headers['Vary'] = 'Pony'
|
2009-04-02 02:19:32 +08:00
|
|
|
# Make sure that the Vary header is added to the key hash
|
|
|
|
learn_cache_key(request, response)
|
2013-12-27 12:14:08 +08:00
|
|
|
|
|
|
|
self.assertEqual(
|
|
|
|
get_cache_key(request),
|
|
|
|
'views.decorators.cache.cache_page.settingsprefix.GET.'
|
|
|
|
'18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e'
|
|
|
|
)
|
2010-10-29 09:31:15 +08:00
|
|
|
|
2011-08-23 11:51:10 +08:00
|
|
|
def test_patch_cache_control(self):
|
|
|
|
tests = (
|
|
|
|
# Initial Cache-Control, kwargs to patch_cache_control, expected Cache-Control parts
|
2014-09-26 20:31:50 +08:00
|
|
|
(None, {'private': True}, {'private'}),
|
2015-11-07 23:26:38 +08:00
|
|
|
('', {'private': True}, {'private'}),
|
2019-10-10 18:16:32 +08:00
|
|
|
# no-cache.
|
|
|
|
('', {'no_cache': 'Set-Cookie'}, {'no-cache=Set-Cookie'}),
|
|
|
|
('', {'no-cache': 'Set-Cookie'}, {'no-cache=Set-Cookie'}),
|
|
|
|
('no-cache=Set-Cookie', {'no_cache': True}, {'no-cache'}),
|
|
|
|
('no-cache=Set-Cookie,no-cache=Link', {'no_cache': True}, {'no-cache'}),
|
2019-09-27 04:58:14 +08:00
|
|
|
('no-cache=Set-Cookie', {'no_cache': 'Link'}, {'no-cache=Set-Cookie', 'no-cache=Link'}),
|
|
|
|
(
|
|
|
|
'no-cache=Set-Cookie,no-cache=Link',
|
|
|
|
{'no_cache': 'Custom'},
|
|
|
|
{'no-cache=Set-Cookie', 'no-cache=Link', 'no-cache=Custom'},
|
|
|
|
),
|
2011-08-23 11:51:10 +08:00
|
|
|
# Test whether private/public attributes are mutually exclusive
|
2014-09-26 20:31:50 +08:00
|
|
|
('private', {'private': True}, {'private'}),
|
|
|
|
('private', {'public': True}, {'public'}),
|
|
|
|
('public', {'public': True}, {'public'}),
|
|
|
|
('public', {'private': True}, {'private'}),
|
|
|
|
('must-revalidate,max-age=60,private', {'public': True}, {'must-revalidate', 'max-age=60', 'public'}),
|
|
|
|
('must-revalidate,max-age=60,public', {'private': True}, {'must-revalidate', 'max-age=60', 'private'}),
|
|
|
|
('must-revalidate,max-age=60', {'public': True}, {'must-revalidate', 'max-age=60', 'public'}),
|
2011-08-23 11:51:10 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
cc_delim_re = re.compile(r'\s*,\s*')
|
|
|
|
|
|
|
|
for initial_cc, newheaders, expected_cc in tests:
|
2017-03-08 05:00:43 +08:00
|
|
|
with self.subTest(initial_cc=initial_cc, newheaders=newheaders):
|
|
|
|
response = HttpResponse()
|
|
|
|
if initial_cc is not None:
|
2020-07-14 19:32:24 +08:00
|
|
|
response.headers['Cache-Control'] = initial_cc
|
2017-03-08 05:00:43 +08:00
|
|
|
patch_cache_control(response, **newheaders)
|
2020-07-14 19:32:24 +08:00
|
|
|
parts = set(cc_delim_re.split(response.headers['Cache-Control']))
|
2017-03-08 05:00:43 +08:00
|
|
|
self.assertEqual(parts, expected_cc)
|
2011-08-23 11:51:10 +08:00
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
|
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
|
|
|
'KEY_PREFIX': 'cacheprefix',
|
2011-10-27 04:55:36 +08:00
|
|
|
},
|
2013-10-20 07:33:10 +08:00
|
|
|
},
|
2012-03-30 17:08:29 +08:00
|
|
|
)
|
|
|
|
class PrefixedCacheUtils(CacheUtils):
|
|
|
|
pass
|
|
|
|
|
2011-10-27 04:55:36 +08:00
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHE_MIDDLEWARE_SECONDS=60,
|
|
|
|
CACHE_MIDDLEWARE_KEY_PREFIX='test',
|
|
|
|
CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
2011-10-27 04:55:36 +08:00
|
|
|
},
|
2013-10-20 07:33:10 +08:00
|
|
|
},
|
2012-03-30 17:08:29 +08:00
|
|
|
)
|
2015-04-18 05:38:20 +08:00
|
|
|
class CacheHEADTest(SimpleTestCase):
|
2018-11-27 03:01:27 +08:00
|
|
|
path = '/cache/test/'
|
|
|
|
factory = RequestFactory()
|
2011-10-27 06:47:04 +08:00
|
|
|
|
|
|
|
def tearDown(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.clear()
|
2010-10-29 09:31:15 +08:00
|
|
|
|
|
|
|
def _set_cache(self, request, msg):
|
2019-09-27 01:06:35 +08:00
|
|
|
return UpdateCacheMiddleware(lambda req: HttpResponse(msg))(request)
|
2010-10-29 09:31:15 +08:00
|
|
|
|
|
|
|
def test_head_caches_correctly(self):
|
|
|
|
test_content = 'test content'
|
|
|
|
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.head(self.path)
|
|
|
|
request._cache_update_cache = True
|
2010-10-29 09:31:15 +08:00
|
|
|
self._set_cache(request, test_content)
|
|
|
|
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.head(self.path)
|
|
|
|
request._cache_update_cache = True
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(get_cache_data)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(test_content.encode(), get_cache_data.content)
|
2010-10-29 09:31:15 +08:00
|
|
|
|
|
|
|
def test_head_with_cached_get(self):
|
|
|
|
test_content = 'test content'
|
|
|
|
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
|
|
|
request._cache_update_cache = True
|
2010-10-29 09:31:15 +08:00
|
|
|
self._set_cache(request, test_content)
|
|
|
|
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.head(self.path)
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(get_cache_data)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(test_content.encode(), get_cache_data.content)
|
2007-11-19 11:12:19 +08:00
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
|
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
|
|
|
|
CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
2011-10-27 04:55:36 +08:00
|
|
|
},
|
2013-10-20 07:33:10 +08:00
|
|
|
},
|
2015-01-22 00:55:57 +08:00
|
|
|
LANGUAGES=[
|
2013-10-20 07:33:10 +08:00
|
|
|
('en', 'English'),
|
|
|
|
('es', 'Spanish'),
|
2015-01-22 00:55:57 +08:00
|
|
|
],
|
2012-03-30 17:08:29 +08:00
|
|
|
)
|
2018-11-27 03:05:02 +08:00
|
|
|
class CacheI18nTest(SimpleTestCase):
|
2018-11-27 03:01:27 +08:00
|
|
|
path = '/cache/test/'
|
|
|
|
factory = RequestFactory()
|
2010-02-24 04:45:28 +08:00
|
|
|
|
2011-10-27 06:47:04 +08:00
|
|
|
def tearDown(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.clear()
|
2011-10-27 06:47:04 +08:00
|
|
|
|
2020-05-23 01:43:03 +08:00
|
|
|
@override_settings(USE_I18N=True, USE_TZ=False)
|
2011-11-01 22:02:31 +08:00
|
|
|
def test_cache_key_i18n_translation(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
2010-02-24 04:45:28 +08:00
|
|
|
lang = translation.get_language()
|
|
|
|
response = HttpResponse()
|
|
|
|
key = learn_cache_key(request, response)
|
2011-11-01 22:02:31 +08:00
|
|
|
self.assertIn(lang, key, "Cache keys should include the language name when translation is active")
|
2010-02-24 04:45:28 +08:00
|
|
|
key2 = get_cache_key(request)
|
|
|
|
self.assertEqual(key, key2)
|
|
|
|
|
2013-02-26 07:10:57 +08:00
|
|
|
def check_accept_language_vary(self, accept_language, vary, reference_key):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
2013-02-26 07:10:57 +08:00
|
|
|
request.META['HTTP_ACCEPT_LANGUAGE'] = accept_language
|
2013-02-27 11:26:15 +08:00
|
|
|
request.META['HTTP_ACCEPT_ENCODING'] = 'gzip;q=1.0, identity; q=0.5, *;q=0'
|
2013-02-26 07:10:57 +08:00
|
|
|
response = HttpResponse()
|
2020-07-14 19:32:24 +08:00
|
|
|
response.headers['Vary'] = vary
|
2013-02-26 07:10:57 +08:00
|
|
|
key = learn_cache_key(request, response)
|
|
|
|
key2 = get_cache_key(request)
|
|
|
|
self.assertEqual(key, reference_key)
|
|
|
|
self.assertEqual(key2, reference_key)
|
|
|
|
|
2020-05-23 01:43:03 +08:00
|
|
|
@override_settings(USE_I18N=True, USE_TZ=False)
|
2013-02-26 07:10:57 +08:00
|
|
|
def test_cache_key_i18n_translation_accept_language(self):
|
|
|
|
lang = translation.get_language()
|
|
|
|
self.assertEqual(lang, 'en')
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
2013-02-27 11:26:15 +08:00
|
|
|
request.META['HTTP_ACCEPT_ENCODING'] = 'gzip;q=1.0, identity; q=0.5, *;q=0'
|
2013-02-26 07:10:57 +08:00
|
|
|
response = HttpResponse()
|
2020-07-14 19:32:24 +08:00
|
|
|
response.headers['Vary'] = 'accept-encoding'
|
2013-02-26 07:10:57 +08:00
|
|
|
key = learn_cache_key(request, response)
|
|
|
|
self.assertIn(lang, key, "Cache keys should include the language name when translation is active")
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'en-us',
|
2013-02-26 07:10:57 +08:00
|
|
|
'cookie, accept-language, accept-encoding',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'en-US',
|
2013-02-26 07:10:57 +08:00
|
|
|
'cookie, accept-encoding, accept-language',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'en-US,en;q=0.8',
|
2013-02-26 07:10:57 +08:00
|
|
|
'accept-encoding, accept-language, cookie',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'en-US,en;q=0.8,ko;q=0.6',
|
2013-02-26 07:10:57 +08:00
|
|
|
'accept-language, cookie, accept-encoding',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3 ',
|
2013-02-26 07:10:57 +08:00
|
|
|
'accept-encoding, cookie, accept-language',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4',
|
2013-02-26 07:10:57 +08:00
|
|
|
'accept-language, accept-encoding, cookie',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'ko;q=1.0,en;q=0.5',
|
2013-02-26 07:10:57 +08:00
|
|
|
'cookie, accept-language, accept-encoding',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'ko, en',
|
2013-02-26 07:10:57 +08:00
|
|
|
'cookie, accept-encoding, accept-language',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
self.check_accept_language_vary(
|
2013-02-27 11:26:15 +08:00
|
|
|
'ko-KR, en-US',
|
2013-02-26 07:10:57 +08:00
|
|
|
'accept-encoding, accept-language, cookie',
|
|
|
|
key
|
|
|
|
)
|
|
|
|
|
2020-05-23 01:43:03 +08:00
|
|
|
@override_settings(USE_I18N=False, USE_TZ=True)
|
2011-11-18 21:01:06 +08:00
|
|
|
def test_cache_key_i18n_timezone(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
2017-01-24 19:22:42 +08:00
|
|
|
tz = timezone.get_current_timezone_name()
|
2011-11-18 21:01:06 +08:00
|
|
|
response = HttpResponse()
|
|
|
|
key = learn_cache_key(request, response)
|
|
|
|
self.assertIn(tz, key, "Cache keys should include the time zone name when time zones are active")
|
|
|
|
key2 = get_cache_key(request)
|
|
|
|
self.assertEqual(key, key2)
|
|
|
|
|
2020-05-23 01:43:03 +08:00
|
|
|
@override_settings(USE_I18N=False)
|
2013-10-11 19:25:14 +08:00
|
|
|
def test_cache_key_no_i18n(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
2010-02-24 04:45:28 +08:00
|
|
|
lang = translation.get_language()
|
2017-01-24 19:22:42 +08:00
|
|
|
tz = timezone.get_current_timezone_name()
|
2010-02-24 04:45:28 +08:00
|
|
|
response = HttpResponse()
|
|
|
|
key = learn_cache_key(request, response)
|
2011-11-01 22:02:31 +08:00
|
|
|
self.assertNotIn(lang, key, "Cache keys shouldn't include the language name when i18n isn't active")
|
2011-11-18 21:01:06 +08:00
|
|
|
self.assertNotIn(tz, key, "Cache keys shouldn't include the time zone name when i18n isn't active")
|
2010-02-24 04:45:28 +08:00
|
|
|
|
2011-10-27 04:55:36 +08:00
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHE_MIDDLEWARE_KEY_PREFIX="test",
|
|
|
|
CACHE_MIDDLEWARE_SECONDS=60,
|
|
|
|
USE_I18N=True,
|
2011-10-27 04:55:36 +08:00
|
|
|
)
|
2010-02-24 04:45:28 +08:00
|
|
|
def test_middleware(self):
|
|
|
|
def set_cache(request, lang, msg):
|
2019-09-27 01:06:35 +08:00
|
|
|
def get_response(req):
|
|
|
|
return HttpResponse(msg)
|
|
|
|
|
2011-10-27 06:47:04 +08:00
|
|
|
translation.activate(lang)
|
2019-09-27 01:06:35 +08:00
|
|
|
return UpdateCacheMiddleware(get_response)(request)
|
2011-03-02 20:47:36 +08:00
|
|
|
|
|
|
|
# cache with non empty request.GET
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path, {'foo': 'bar', 'other': 'true'})
|
|
|
|
request._cache_update_cache = True
|
|
|
|
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2011-03-02 20:47:36 +08:00
|
|
|
# first access, cache must return None
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(get_cache_data)
|
2011-03-02 20:47:36 +08:00
|
|
|
content = 'Check for cache with QUERY_STRING'
|
2019-09-27 01:06:35 +08:00
|
|
|
|
|
|
|
def get_response(req):
|
|
|
|
return HttpResponse(content)
|
|
|
|
|
|
|
|
UpdateCacheMiddleware(get_response)(request)
|
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2011-03-02 20:47:36 +08:00
|
|
|
# cache must return content
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(get_cache_data)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(get_cache_data.content, content.encode())
|
2011-03-02 20:47:36 +08:00
|
|
|
# different QUERY_STRING, cache must be empty
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path, {'foo': 'bar', 'somethingelse': 'true'})
|
|
|
|
request._cache_update_cache = True
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(get_cache_data)
|
2011-03-02 20:47:36 +08:00
|
|
|
|
|
|
|
# i18n tests
|
2013-10-23 18:09:29 +08:00
|
|
|
en_message = "Hello world!"
|
|
|
|
es_message = "Hola mundo!"
|
2010-02-24 04:45:28 +08:00
|
|
|
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
|
|
|
request._cache_update_cache = True
|
2010-02-24 04:45:28 +08:00
|
|
|
set_cache(request, 'en', en_message)
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2016-10-27 15:53:39 +08:00
|
|
|
# The cache can be recovered
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(get_cache_data)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(get_cache_data.content, en_message.encode())
|
2010-02-24 04:45:28 +08:00
|
|
|
# change the session language and set content
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
|
|
|
request._cache_update_cache = True
|
2010-02-24 04:45:28 +08:00
|
|
|
set_cache(request, 'es', es_message)
|
|
|
|
# change again the language
|
2011-10-27 06:47:04 +08:00
|
|
|
translation.activate('en')
|
|
|
|
# retrieve the content from cache
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(get_cache_data.content, en_message.encode())
|
2010-02-24 04:45:28 +08:00
|
|
|
# change again the language
|
2011-10-27 06:47:04 +08:00
|
|
|
translation.activate('es')
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(get_cache_data.content, es_message.encode())
|
2011-10-27 14:17:24 +08:00
|
|
|
# reset the language
|
|
|
|
translation.deactivate()
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2012-10-20 23:40:14 +08:00
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHE_MIDDLEWARE_KEY_PREFIX="test",
|
|
|
|
CACHE_MIDDLEWARE_SECONDS=60,
|
2012-10-20 23:40:14 +08:00
|
|
|
)
|
2012-12-25 03:25:02 +08:00
|
|
|
def test_middleware_doesnt_cache_streaming_response(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2012-12-25 03:25:02 +08:00
|
|
|
self.assertIsNone(get_cache_data)
|
2012-10-20 23:40:14 +08:00
|
|
|
|
2019-09-27 01:06:35 +08:00
|
|
|
def get_stream_response(req):
|
|
|
|
return StreamingHttpResponse(['Check for cache with streaming content.'])
|
|
|
|
|
|
|
|
UpdateCacheMiddleware(get_stream_response)(request)
|
2012-10-20 23:40:14 +08:00
|
|
|
|
2019-09-27 01:06:35 +08:00
|
|
|
get_cache_data = FetchFromCacheMiddleware(empty_response).process_request(request)
|
2012-12-25 03:25:02 +08:00
|
|
|
self.assertIsNone(get_cache_data)
|
2011-10-27 04:55:36 +08:00
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
|
|
|
'KEY_PREFIX': 'cacheprefix'
|
2011-10-27 04:55:36 +08:00
|
|
|
},
|
2013-10-20 07:33:10 +08:00
|
|
|
},
|
2012-03-30 17:08:29 +08:00
|
|
|
)
|
|
|
|
class PrefixedCacheI18nTest(CacheI18nTest):
|
|
|
|
pass
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2011-02-17 11:50:55 +08:00
|
|
|
|
|
|
|
def hello_world_view(request, value):
|
|
|
|
return HttpResponse('Hello World %s' % value)
|
|
|
|
|
2011-10-27 04:55:36 +08:00
|
|
|
|
2014-04-21 04:10:32 +08:00
|
|
|
def csrf_view(request):
|
|
|
|
return HttpResponse(csrf(request)['csrf_token'])
|
|
|
|
|
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHE_MIDDLEWARE_ALIAS='other',
|
|
|
|
CACHE_MIDDLEWARE_KEY_PREFIX='middlewareprefix',
|
|
|
|
CACHE_MIDDLEWARE_SECONDS=30,
|
|
|
|
CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
|
|
|
},
|
|
|
|
'other': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
|
|
|
'LOCATION': 'other',
|
|
|
|
'TIMEOUT': '1',
|
2012-03-30 17:08:29 +08:00
|
|
|
},
|
2013-10-20 07:33:10 +08:00
|
|
|
},
|
2012-03-30 17:08:29 +08:00
|
|
|
)
|
2015-04-18 05:38:20 +08:00
|
|
|
class CacheMiddlewareTest(SimpleTestCase):
|
2018-11-27 03:01:27 +08:00
|
|
|
factory = RequestFactory()
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
def setUp(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
self.default_cache = caches['default']
|
|
|
|
self.other_cache = caches['other']
|
2011-10-27 06:47:04 +08:00
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
self.default_cache.clear()
|
|
|
|
self.other_cache.clear()
|
2017-01-21 21:13:44 +08:00
|
|
|
super().tearDown()
|
2011-02-17 11:50:55 +08:00
|
|
|
|
2011-01-24 14:36:31 +08:00
|
|
|
def test_constructor(self):
|
|
|
|
"""
|
|
|
|
Ensure the constructor is correctly distinguishing between usage of CacheMiddleware as
|
|
|
|
Middleware vs. usage of CacheMiddleware as view decorator and setting attributes
|
|
|
|
appropriately.
|
|
|
|
"""
|
2019-09-27 01:06:35 +08:00
|
|
|
# If only one argument is passed in construction, it's being used as
|
|
|
|
# middleware.
|
|
|
|
middleware = CacheMiddleware(empty_response)
|
2011-01-24 14:36:31 +08:00
|
|
|
|
|
|
|
# Now test object attributes against values defined in setUp above
|
2011-03-03 23:04:39 +08:00
|
|
|
self.assertEqual(middleware.cache_timeout, 30)
|
|
|
|
self.assertEqual(middleware.key_prefix, 'middlewareprefix')
|
|
|
|
self.assertEqual(middleware.cache_alias, 'other')
|
2020-08-28 15:44:40 +08:00
|
|
|
self.assertEqual(middleware.cache, self.other_cache)
|
2011-01-24 14:36:31 +08:00
|
|
|
|
2019-09-27 01:06:35 +08:00
|
|
|
# If more arguments are being passed in construction, it's being used
|
|
|
|
# as a decorator. First, test with "defaults":
|
|
|
|
as_view_decorator = CacheMiddleware(empty_response, cache_alias=None, key_prefix=None)
|
2011-01-24 14:36:31 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(as_view_decorator.cache_timeout, 30) # Timeout value for 'default' cache, i.e. 30
|
2011-03-03 23:04:39 +08:00
|
|
|
self.assertEqual(as_view_decorator.key_prefix, '')
|
2015-09-12 07:33:12 +08:00
|
|
|
# Value of DEFAULT_CACHE_ALIAS from django.core.cache
|
|
|
|
self.assertEqual(as_view_decorator.cache_alias, 'default')
|
2020-08-28 15:44:40 +08:00
|
|
|
self.assertEqual(as_view_decorator.cache, self.default_cache)
|
2011-01-24 14:36:31 +08:00
|
|
|
|
|
|
|
# Next, test with custom values:
|
2019-09-27 01:06:35 +08:00
|
|
|
as_view_decorator_with_custom = CacheMiddleware(
|
|
|
|
hello_world_view, cache_timeout=60, cache_alias='other', key_prefix='foo'
|
|
|
|
)
|
2011-01-24 14:36:31 +08:00
|
|
|
|
2011-03-03 23:04:39 +08:00
|
|
|
self.assertEqual(as_view_decorator_with_custom.cache_timeout, 60)
|
|
|
|
self.assertEqual(as_view_decorator_with_custom.key_prefix, 'foo')
|
|
|
|
self.assertEqual(as_view_decorator_with_custom.cache_alias, 'other')
|
2020-08-28 15:44:40 +08:00
|
|
|
self.assertEqual(as_view_decorator_with_custom.cache, self.other_cache)
|
|
|
|
|
|
|
|
def test_update_cache_middleware_constructor(self):
|
|
|
|
middleware = UpdateCacheMiddleware(empty_response)
|
|
|
|
self.assertEqual(middleware.cache_timeout, 30)
|
|
|
|
self.assertIsNone(middleware.page_timeout)
|
|
|
|
self.assertEqual(middleware.key_prefix, 'middlewareprefix')
|
|
|
|
self.assertEqual(middleware.cache_alias, 'other')
|
|
|
|
self.assertEqual(middleware.cache, self.other_cache)
|
|
|
|
|
|
|
|
def test_fetch_cache_middleware_constructor(self):
|
|
|
|
middleware = FetchFromCacheMiddleware(empty_response)
|
|
|
|
self.assertEqual(middleware.key_prefix, 'middlewareprefix')
|
|
|
|
self.assertEqual(middleware.cache_alias, 'other')
|
|
|
|
self.assertEqual(middleware.cache, self.other_cache)
|
2011-01-24 14:36:31 +08:00
|
|
|
|
2010-12-22 15:52:44 +08:00
|
|
|
def test_middleware(self):
|
2019-09-27 01:06:35 +08:00
|
|
|
middleware = CacheMiddleware(hello_world_view)
|
|
|
|
prefix_middleware = CacheMiddleware(hello_world_view, key_prefix='prefix1')
|
|
|
|
timeout_middleware = CacheMiddleware(hello_world_view, cache_timeout=1)
|
2010-12-22 15:52:44 +08:00
|
|
|
|
2011-02-17 11:50:55 +08:00
|
|
|
request = self.factory.get('/view/')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# Put the request through the request middleware
|
|
|
|
result = middleware.process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(result)
|
2010-12-22 15:52:44 +08:00
|
|
|
|
2011-02-17 11:50:55 +08:00
|
|
|
response = hello_world_view(request, '1')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# Now put the response through the response middleware
|
|
|
|
response = middleware.process_response(request, response)
|
|
|
|
|
|
|
|
# Repeating the request should result in a cache hit
|
|
|
|
result = middleware.process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(result)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(result.content, b'Hello World 1')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# The same request through a different middleware won't hit
|
|
|
|
result = prefix_middleware.process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(result)
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# The same request with a timeout _will_ hit
|
|
|
|
result = timeout_middleware.process_request(request)
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNotNone(result)
|
2012-08-16 04:47:31 +08:00
|
|
|
self.assertEqual(result.content, b'Hello World 1')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
2011-02-17 11:50:55 +08:00
|
|
|
def test_view_decorator(self):
|
2010-12-22 15:52:44 +08:00
|
|
|
# decorate the same view with different cache decorators
|
2012-12-25 06:43:34 +08:00
|
|
|
default_view = cache_page(3)(hello_world_view)
|
|
|
|
default_with_prefix_view = cache_page(3, key_prefix='prefix1')(hello_world_view)
|
2010-12-22 15:52:44 +08:00
|
|
|
|
2012-12-25 06:43:34 +08:00
|
|
|
explicit_default_view = cache_page(3, cache='default')(hello_world_view)
|
|
|
|
explicit_default_with_prefix_view = cache_page(3, cache='default', key_prefix='prefix1')(hello_world_view)
|
2010-12-22 15:52:44 +08:00
|
|
|
|
2012-12-25 06:43:34 +08:00
|
|
|
other_view = cache_page(1, cache='other')(hello_world_view)
|
|
|
|
other_with_prefix_view = cache_page(1, cache='other', key_prefix='prefix2')(hello_world_view)
|
2010-12-22 15:52:44 +08:00
|
|
|
|
2011-02-17 11:50:55 +08:00
|
|
|
request = self.factory.get('/view/')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# Request the view once
|
|
|
|
response = default_view(request, '1')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 1')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# Request again -- hit the cache
|
|
|
|
response = default_view(request, '2')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 1')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# Requesting the same view with the explicit cache should yield the same result
|
|
|
|
response = explicit_default_view(request, '3')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 1')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# Requesting with a prefix will hit a different cache key
|
|
|
|
response = explicit_default_with_prefix_view(request, '4')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 4')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# Hitting the same view again gives a cache hit
|
|
|
|
response = explicit_default_with_prefix_view(request, '5')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 4')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# And going back to the implicit cache will hit the same cache
|
|
|
|
response = default_with_prefix_view(request, '6')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 4')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# Requesting from an alternate cache won't hit cache
|
|
|
|
response = other_view(request, '7')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 7')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# But a repeated hit will hit cache
|
|
|
|
response = other_view(request, '8')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 7')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# And prefixing the alternate cache yields yet another cache entry
|
|
|
|
response = other_with_prefix_view(request, '9')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 9')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# But if we wait a couple of seconds...
|
|
|
|
time.sleep(2)
|
|
|
|
|
|
|
|
# ... the default cache will still hit
|
2013-10-19 06:49:24 +08:00
|
|
|
caches['default']
|
2011-01-24 14:36:31 +08:00
|
|
|
response = default_view(request, '11')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 1')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# ... the default cache with a prefix will still hit
|
2011-01-24 14:36:31 +08:00
|
|
|
response = default_with_prefix_view(request, '12')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 4')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# ... the explicit default cache will still hit
|
2011-01-24 14:36:31 +08:00
|
|
|
response = explicit_default_view(request, '13')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 1')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# ... the explicit default cache with a prefix will still hit
|
2011-01-24 14:36:31 +08:00
|
|
|
response = explicit_default_with_prefix_view(request, '14')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 4')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# .. but a rapidly expiring cache won't hit
|
2011-01-24 14:36:31 +08:00
|
|
|
response = other_view(request, '15')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 15')
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
# .. even if it has a prefix
|
2011-01-24 14:36:31 +08:00
|
|
|
response = other_with_prefix_view(request, '16')
|
2012-08-14 17:57:18 +08:00
|
|
|
self.assertEqual(response.content, b'Hello World 16')
|
2011-01-24 14:36:31 +08:00
|
|
|
|
2019-09-27 02:41:38 +08:00
|
|
|
def test_cache_page_timeout(self):
|
|
|
|
# Page timeout takes precedence over the "max-age" section of the
|
|
|
|
# "Cache-Control".
|
|
|
|
tests = [
|
|
|
|
(1, 3), # max_age < page_timeout.
|
|
|
|
(3, 1), # max_age > page_timeout.
|
|
|
|
]
|
|
|
|
for max_age, page_timeout in tests:
|
|
|
|
with self.subTest(max_age=max_age, page_timeout=page_timeout):
|
|
|
|
view = cache_page(timeout=page_timeout)(
|
|
|
|
cache_control(max_age=max_age)(hello_world_view)
|
|
|
|
)
|
|
|
|
request = self.factory.get('/view/')
|
|
|
|
response = view(request, '1')
|
|
|
|
self.assertEqual(response.content, b'Hello World 1')
|
|
|
|
time.sleep(1)
|
|
|
|
response = view(request, '2')
|
|
|
|
self.assertEqual(
|
|
|
|
response.content,
|
|
|
|
b'Hello World 1' if page_timeout > max_age else b'Hello World 2',
|
|
|
|
)
|
|
|
|
cache.clear()
|
|
|
|
|
2018-02-06 13:44:53 +08:00
|
|
|
def test_cached_control_private_not_cached(self):
|
|
|
|
"""Responses with 'Cache-Control: private' are not cached."""
|
|
|
|
view_with_private_cache = cache_page(3)(cache_control(private=True)(hello_world_view))
|
|
|
|
request = self.factory.get('/view/')
|
|
|
|
response = view_with_private_cache(request, '1')
|
|
|
|
self.assertEqual(response.content, b'Hello World 1')
|
|
|
|
response = view_with_private_cache(request, '2')
|
|
|
|
self.assertEqual(response.content, b'Hello World 2')
|
|
|
|
|
2014-04-21 04:10:32 +08:00
|
|
|
def test_sensitive_cookie_not_cached(self):
|
|
|
|
"""
|
|
|
|
Django must prevent caching of responses that set a user-specific (and
|
|
|
|
maybe security sensitive) cookie in response to a cookie-less request.
|
|
|
|
"""
|
|
|
|
request = self.factory.get('/view/')
|
2019-09-27 01:06:35 +08:00
|
|
|
csrf_middleware = CsrfViewMiddleware(csrf_view)
|
2014-04-21 04:10:32 +08:00
|
|
|
csrf_middleware.process_view(request, csrf_view, (), {})
|
2019-09-27 01:06:35 +08:00
|
|
|
cache_middleware = CacheMiddleware(csrf_middleware)
|
2014-04-21 04:10:32 +08:00
|
|
|
|
2019-09-27 01:06:35 +08:00
|
|
|
self.assertIsNone(cache_middleware.process_request(request))
|
|
|
|
cache_middleware(request)
|
2014-04-21 04:10:32 +08:00
|
|
|
|
|
|
|
# Inserting a CSRF cookie in a cookie-less request prevented caching.
|
|
|
|
self.assertIsNone(cache_middleware.process_request(request))
|
|
|
|
|
2016-09-12 22:19:36 +08:00
|
|
|
def test_304_response_has_http_caching_headers_but_not_cached(self):
|
|
|
|
original_view = mock.Mock(return_value=HttpResponseNotModified())
|
|
|
|
view = cache_page(2)(original_view)
|
|
|
|
request = self.factory.get('/view/')
|
|
|
|
# The view shouldn't be cached on the second call.
|
|
|
|
view(request).close()
|
|
|
|
response = view(request)
|
|
|
|
response.close()
|
|
|
|
self.assertEqual(original_view.call_count, 2)
|
|
|
|
self.assertIsInstance(response, HttpResponseNotModified)
|
|
|
|
self.assertIn('Cache-Control', response)
|
|
|
|
self.assertIn('Expires', response)
|
|
|
|
|
2021-11-01 08:54:13 +08:00
|
|
|
def test_per_thread(self):
|
|
|
|
"""The cache instance is different for each thread."""
|
|
|
|
thread_caches = []
|
|
|
|
middleware = CacheMiddleware(empty_response)
|
|
|
|
|
|
|
|
def runner():
|
|
|
|
thread_caches.append(middleware.cache)
|
|
|
|
|
|
|
|
for _ in range(2):
|
|
|
|
thread = threading.Thread(target=runner)
|
|
|
|
thread.start()
|
|
|
|
thread.join()
|
|
|
|
|
|
|
|
self.assertIsNot(thread_caches[0], thread_caches[1])
|
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
@override_settings(
|
2013-10-20 07:33:10 +08:00
|
|
|
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
|
|
|
|
CACHE_MIDDLEWARE_SECONDS=1,
|
|
|
|
CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
2011-10-27 04:55:36 +08:00
|
|
|
},
|
2013-10-20 07:33:10 +08:00
|
|
|
},
|
|
|
|
USE_I18N=False,
|
2012-03-30 17:08:29 +08:00
|
|
|
)
|
2015-04-18 05:38:20 +08:00
|
|
|
class TestWithTemplateResponse(SimpleTestCase):
|
2011-09-08 21:25:31 +08:00
|
|
|
"""
|
|
|
|
Tests various headers w/ TemplateResponse.
|
|
|
|
|
|
|
|
Most are probably redundant since they manipulate the same object
|
2016-09-09 23:00:21 +08:00
|
|
|
anyway but the ETag header is 'special' because it relies on the
|
2011-09-08 21:25:31 +08:00
|
|
|
content being complete (which is not necessarily always the case
|
|
|
|
with a TemplateResponse)
|
|
|
|
"""
|
2018-11-27 03:01:27 +08:00
|
|
|
path = '/cache/test/'
|
|
|
|
factory = RequestFactory()
|
2011-10-27 06:47:04 +08:00
|
|
|
|
|
|
|
def tearDown(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
cache.clear()
|
2011-09-08 21:25:31 +08:00
|
|
|
|
|
|
|
def test_patch_vary_headers(self):
|
|
|
|
headers = (
|
|
|
|
# Initial vary, new headers, resulting vary.
|
|
|
|
(None, ('Accept-Encoding',), 'Accept-Encoding'),
|
|
|
|
('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
|
|
|
|
('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
|
|
|
|
('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
|
|
|
|
('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
|
|
|
|
('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
|
|
|
|
(None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
|
|
|
|
('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
|
|
|
|
('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
|
|
|
|
)
|
|
|
|
for initial_vary, newheaders, resulting_vary in headers:
|
2017-03-08 05:00:43 +08:00
|
|
|
with self.subTest(initial_vary=initial_vary, newheaders=newheaders):
|
|
|
|
template = engines['django'].from_string("This is a test")
|
|
|
|
response = TemplateResponse(HttpRequest(), template)
|
|
|
|
if initial_vary is not None:
|
2020-07-14 19:32:24 +08:00
|
|
|
response.headers['Vary'] = initial_vary
|
2017-03-08 05:00:43 +08:00
|
|
|
patch_vary_headers(response, newheaders)
|
2020-07-14 19:32:24 +08:00
|
|
|
self.assertEqual(response.headers['Vary'], resulting_vary)
|
2011-09-08 21:25:31 +08:00
|
|
|
|
|
|
|
def test_get_cache_key(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path)
|
2015-01-10 05:59:00 +08:00
|
|
|
template = engines['django'].from_string("This is a test")
|
|
|
|
response = TemplateResponse(HttpRequest(), template)
|
2011-09-08 21:25:31 +08:00
|
|
|
key_prefix = 'localprefix'
|
|
|
|
# Expect None if no headers have been set yet.
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(get_cache_key(request))
|
2011-09-08 21:25:31 +08:00
|
|
|
# Set headers to an empty list.
|
|
|
|
learn_cache_key(request, response)
|
2013-12-27 12:14:08 +08:00
|
|
|
|
|
|
|
self.assertEqual(
|
|
|
|
get_cache_key(request),
|
|
|
|
'views.decorators.cache.cache_page.settingsprefix.GET.'
|
|
|
|
'58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e'
|
|
|
|
)
|
2016-10-27 15:53:39 +08:00
|
|
|
# A specified key_prefix is taken into account.
|
2011-09-08 21:25:31 +08:00
|
|
|
learn_cache_key(request, response, key_prefix=key_prefix)
|
2013-12-27 12:14:08 +08:00
|
|
|
self.assertEqual(
|
|
|
|
get_cache_key(request, key_prefix=key_prefix),
|
|
|
|
'views.decorators.cache.cache_page.localprefix.GET.'
|
|
|
|
'58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e'
|
|
|
|
)
|
2011-09-08 21:25:31 +08:00
|
|
|
|
|
|
|
def test_get_cache_key_with_query(self):
|
2013-11-21 07:54:23 +08:00
|
|
|
request = self.factory.get(self.path, {'test': 1})
|
2015-01-10 05:59:00 +08:00
|
|
|
template = engines['django'].from_string("This is a test")
|
|
|
|
response = TemplateResponse(HttpRequest(), template)
|
2011-09-08 21:25:31 +08:00
|
|
|
# Expect None if no headers have been set yet.
|
2014-05-10 01:34:53 +08:00
|
|
|
self.assertIsNone(get_cache_key(request))
|
2011-09-08 21:25:31 +08:00
|
|
|
# Set headers to an empty list.
|
|
|
|
learn_cache_key(request, response)
|
2016-10-27 15:53:39 +08:00
|
|
|
# The querystring is taken into account.
|
2013-12-27 12:14:08 +08:00
|
|
|
self.assertEqual(
|
|
|
|
get_cache_key(request),
|
|
|
|
'views.decorators.cache.cache_page.settingsprefix.GET.'
|
|
|
|
'0f1c2d56633c943073c4569d9a9502fe.d41d8cd98f00b204e9800998ecf8427e'
|
|
|
|
)
|
2011-09-08 21:25:31 +08:00
|
|
|
|
|
|
|
|
2015-04-18 05:38:20 +08:00
|
|
|
class TestMakeTemplateFragmentKey(SimpleTestCase):
|
2013-02-24 19:58:02 +08:00
|
|
|
def test_without_vary_on(self):
|
|
|
|
key = make_template_fragment_key('a.fragment')
|
|
|
|
self.assertEqual(key, 'template.cache.a.fragment.d41d8cd98f00b204e9800998ecf8427e')
|
|
|
|
|
|
|
|
def test_with_one_vary_on(self):
|
|
|
|
key = make_template_fragment_key('foo', ['abc'])
|
2019-09-12 05:12:35 +08:00
|
|
|
self.assertEqual(key, 'template.cache.foo.493e283d571a73056196f1a68efd0f66')
|
2013-02-24 19:58:02 +08:00
|
|
|
|
|
|
|
def test_with_many_vary_on(self):
|
|
|
|
key = make_template_fragment_key('bar', ['abc', 'def'])
|
2019-09-12 05:12:35 +08:00
|
|
|
self.assertEqual(key, 'template.cache.bar.17c1a507a0cb58384f4c639067a93520')
|
2013-02-24 19:58:02 +08:00
|
|
|
|
|
|
|
def test_proper_escaping(self):
|
|
|
|
key = make_template_fragment_key('spam', ['abc:def%'])
|
2019-09-12 05:12:35 +08:00
|
|
|
self.assertEqual(key, 'template.cache.spam.06c8ae8e8c430b69fb0a6443504153dc')
|
|
|
|
|
|
|
|
def test_with_ints_vary_on(self):
|
|
|
|
key = make_template_fragment_key('foo', [1, 2, 3, 4, 5])
|
|
|
|
self.assertEqual(key, 'template.cache.foo.7ae8fd2e0d25d651c683bdeebdb29461')
|
|
|
|
|
|
|
|
def test_with_unicode_vary_on(self):
|
|
|
|
key = make_template_fragment_key('foo', ['42º', '😀'])
|
|
|
|
self.assertEqual(key, 'template.cache.foo.7ced1c94e543668590ba39b3c08b0237')
|
|
|
|
|
|
|
|
def test_long_vary_on(self):
|
|
|
|
key = make_template_fragment_key('foo', ['x' * 10000])
|
|
|
|
self.assertEqual(key, 'template.cache.foo.3670b349b5124aa56bdb50678b02b23a')
|
2013-10-19 06:49:24 +08:00
|
|
|
|
2013-11-24 00:26:11 +08:00
|
|
|
|
2015-04-18 05:38:20 +08:00
|
|
|
class CacheHandlerTest(SimpleTestCase):
|
2013-10-19 06:49:24 +08:00
|
|
|
def test_same_instance(self):
|
|
|
|
"""
|
|
|
|
Attempting to retrieve the same alias should yield the same instance.
|
|
|
|
"""
|
|
|
|
cache1 = caches['default']
|
|
|
|
cache2 = caches['default']
|
|
|
|
|
2014-10-28 18:02:56 +08:00
|
|
|
self.assertIs(cache1, cache2)
|
2013-10-19 06:49:24 +08:00
|
|
|
|
|
|
|
def test_per_thread(self):
|
|
|
|
"""
|
|
|
|
Requesting the same alias from separate threads should yield separate
|
|
|
|
instances.
|
|
|
|
"""
|
|
|
|
c = []
|
2013-11-24 00:26:11 +08:00
|
|
|
|
2013-10-19 06:49:24 +08:00
|
|
|
def runner():
|
|
|
|
c.append(caches['default'])
|
|
|
|
|
|
|
|
for x in range(2):
|
|
|
|
t = threading.Thread(target=runner)
|
|
|
|
t.start()
|
|
|
|
t.join()
|
|
|
|
|
2014-10-28 18:02:56 +08:00
|
|
|
self.assertIsNot(c[0], c[1])
|
2020-12-08 14:05:49 +08:00
|
|
|
|
|
|
|
def test_nonexistent_alias(self):
|
2017-10-22 23:30:42 +08:00
|
|
|
msg = "The connection 'nonexistent' doesn't exist."
|
2020-12-08 14:05:49 +08:00
|
|
|
with self.assertRaisesMessage(InvalidCacheBackendError, msg):
|
|
|
|
caches['nonexistent']
|
2020-12-08 14:28:59 +08:00
|
|
|
|
|
|
|
def test_nonexistent_backend(self):
|
2017-10-22 23:30:42 +08:00
|
|
|
test_caches = CacheHandler({
|
|
|
|
'invalid_backend': {
|
|
|
|
'BACKEND': 'django.nonexistent.NonexistentBackend',
|
|
|
|
},
|
|
|
|
})
|
2020-12-08 14:28:59 +08:00
|
|
|
msg = (
|
|
|
|
"Could not find backend 'django.nonexistent.NonexistentBackend': "
|
|
|
|
"No module named 'django.nonexistent'"
|
|
|
|
)
|
2017-10-22 23:30:42 +08:00
|
|
|
with self.assertRaisesMessage(InvalidCacheBackendError, msg):
|
|
|
|
test_caches['invalid_backend']
|
2021-05-14 17:53:17 +08:00
|
|
|
|
|
|
|
def test_all(self):
|
|
|
|
test_caches = CacheHandler({
|
|
|
|
'cache_1': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
|
|
|
|
},
|
|
|
|
'cache_2': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
|
|
|
|
},
|
|
|
|
})
|
|
|
|
self.assertEqual(test_caches.all(initialized_only=True), [])
|
|
|
|
cache_1 = test_caches['cache_1']
|
|
|
|
self.assertEqual(test_caches.all(initialized_only=True), [cache_1])
|
|
|
|
self.assertEqual(len(test_caches.all()), 2)
|
|
|
|
# .all() initializes all caches.
|
|
|
|
self.assertEqual(len(test_caches.all(initialized_only=True)), 2)
|
|
|
|
self.assertEqual(test_caches.all(), test_caches.all(initialized_only=True))
|