tests.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. # -*- coding: utf-8 -*-
  2. # Unit tests for cache framework
  3. # Uses whatever cache backend is set in the test settings file.
  4. import os
  5. import shutil
  6. import tempfile
  7. import time
  8. import warnings
  9. from django.conf import settings
  10. from django.core import management
  11. from django.core.cache import get_cache
  12. from django.core.cache.backends.base import InvalidCacheBackendError, CacheKeyWarning
  13. from django.http import HttpResponse, HttpRequest
  14. from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware
  15. from django.utils import translation
  16. from django.utils import unittest
  17. from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key
  18. from django.utils.hashcompat import md5_constructor
  19. from regressiontests.cache.models import Poll, expensive_calculation
  20. # functions/classes for complex data type tests
  21. def f():
  22. return 42
  23. class C:
  24. def m(n):
  25. return 24
  26. class DummyCacheTests(unittest.TestCase):
  27. # The Dummy cache backend doesn't really behave like a test backend,
  28. # so it has different test requirements.
  29. def setUp(self):
  30. self.cache = get_cache('dummy://')
  31. def test_simple(self):
  32. "Dummy cache backend ignores cache set calls"
  33. self.cache.set("key", "value")
  34. self.assertEqual(self.cache.get("key"), None)
  35. def test_add(self):
  36. "Add doesn't do anything in dummy cache backend"
  37. self.cache.add("addkey1", "value")
  38. result = self.cache.add("addkey1", "newvalue")
  39. self.assertEqual(result, True)
  40. self.assertEqual(self.cache.get("addkey1"), None)
  41. def test_non_existent(self):
  42. "Non-existent keys aren't found in the dummy cache backend"
  43. self.assertEqual(self.cache.get("does_not_exist"), None)
  44. self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  45. def test_get_many(self):
  46. "get_many returns nothing for the dummy cache backend"
  47. self.cache.set('a', 'a')
  48. self.cache.set('b', 'b')
  49. self.cache.set('c', 'c')
  50. self.cache.set('d', 'd')
  51. self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {})
  52. self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {})
  53. def test_delete(self):
  54. "Cache deletion is transparently ignored on the dummy cache backend"
  55. self.cache.set("key1", "spam")
  56. self.cache.set("key2", "eggs")
  57. self.assertEqual(self.cache.get("key1"), None)
  58. self.cache.delete("key1")
  59. self.assertEqual(self.cache.get("key1"), None)
  60. self.assertEqual(self.cache.get("key2"), None)
  61. def test_has_key(self):
  62. "The has_key method doesn't ever return True for the dummy cache backend"
  63. self.cache.set("hello1", "goodbye1")
  64. self.assertEqual(self.cache.has_key("hello1"), False)
  65. self.assertEqual(self.cache.has_key("goodbye1"), False)
  66. def test_in(self):
  67. "The in operator doesn't ever return True for the dummy cache backend"
  68. self.cache.set("hello2", "goodbye2")
  69. self.assertEqual("hello2" in self.cache, False)
  70. self.assertEqual("goodbye2" in self.cache, False)
  71. def test_incr(self):
  72. "Dummy cache values can't be incremented"
  73. self.cache.set('answer', 42)
  74. self.assertRaises(ValueError, self.cache.incr, 'answer')
  75. self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
  76. def test_decr(self):
  77. "Dummy cache values can't be decremented"
  78. self.cache.set('answer', 42)
  79. self.assertRaises(ValueError, self.cache.decr, 'answer')
  80. self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
  81. def test_data_types(self):
  82. "All data types are ignored equally by the dummy cache"
  83. stuff = {
  84. 'string' : 'this is a string',
  85. 'int' : 42,
  86. 'list' : [1, 2, 3, 4],
  87. 'tuple' : (1, 2, 3, 4),
  88. 'dict' : {'A': 1, 'B' : 2},
  89. 'function' : f,
  90. 'class' : C,
  91. }
  92. self.cache.set("stuff", stuff)
  93. self.assertEqual(self.cache.get("stuff"), None)
  94. def test_expiration(self):
  95. "Expiration has no effect on the dummy cache"
  96. self.cache.set('expire1', 'very quickly', 1)
  97. self.cache.set('expire2', 'very quickly', 1)
  98. self.cache.set('expire3', 'very quickly', 1)
  99. time.sleep(2)
  100. self.assertEqual(self.cache.get("expire1"), None)
  101. self.cache.add("expire2", "newvalue")
  102. self.assertEqual(self.cache.get("expire2"), None)
  103. self.assertEqual(self.cache.has_key("expire3"), False)
  104. def test_unicode(self):
  105. "Unicode values are ignored by the dummy cache"
  106. stuff = {
  107. u'ascii': u'ascii_value',
  108. u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1',
  109. u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2',
  110. u'ascii': {u'x' : 1 }
  111. }
  112. for (key, value) in stuff.items():
  113. self.cache.set(key, value)
  114. self.assertEqual(self.cache.get(key), None)
  115. def test_set_many(self):
  116. "set_many does nothing for the dummy cache backend"
  117. self.cache.set_many({'a': 1, 'b': 2})
  118. def test_delete_many(self):
  119. "delete_many does nothing for the dummy cache backend"
  120. self.cache.delete_many(['a', 'b'])
  121. def test_clear(self):
  122. "clear does nothing for the dummy cache backend"
  123. self.cache.clear()
  124. class BaseCacheTests(object):
  125. # A common set of tests to apply to all cache backends
  126. def tearDown(self):
  127. self.cache.clear()
  128. def test_simple(self):
  129. # Simple cache set/get works
  130. self.cache.set("key", "value")
  131. self.assertEqual(self.cache.get("key"), "value")
  132. def test_add(self):
  133. # A key can be added to a cache
  134. self.cache.add("addkey1", "value")
  135. result = self.cache.add("addkey1", "newvalue")
  136. self.assertEqual(result, False)
  137. self.assertEqual(self.cache.get("addkey1"), "value")
  138. def test_non_existent(self):
  139. # Non-existent cache keys return as None/default
  140. # get with non-existent keys
  141. self.assertEqual(self.cache.get("does_not_exist"), None)
  142. self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  143. def test_get_many(self):
  144. # Multiple cache keys can be returned using get_many
  145. self.cache.set('a', 'a')
  146. self.cache.set('b', 'b')
  147. self.cache.set('c', 'c')
  148. self.cache.set('d', 'd')
  149. self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {'a' : 'a', 'c' : 'c', 'd' : 'd'})
  150. self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'})
  151. def test_delete(self):
  152. # Cache keys can be deleted
  153. self.cache.set("key1", "spam")
  154. self.cache.set("key2", "eggs")
  155. self.assertEqual(self.cache.get("key1"), "spam")
  156. self.cache.delete("key1")
  157. self.assertEqual(self.cache.get("key1"), None)
  158. self.assertEqual(self.cache.get("key2"), "eggs")
  159. def test_has_key(self):
  160. # The cache can be inspected for cache keys
  161. self.cache.set("hello1", "goodbye1")
  162. self.assertEqual(self.cache.has_key("hello1"), True)
  163. self.assertEqual(self.cache.has_key("goodbye1"), False)
  164. def test_in(self):
  165. # The in operator can be used to inspet cache contents
  166. self.cache.set("hello2", "goodbye2")
  167. self.assertEqual("hello2" in self.cache, True)
  168. self.assertEqual("goodbye2" in self.cache, False)
  169. def test_incr(self):
  170. # Cache values can be incremented
  171. self.cache.set('answer', 41)
  172. self.assertEqual(self.cache.incr('answer'), 42)
  173. self.assertEqual(self.cache.get('answer'), 42)
  174. self.assertEqual(self.cache.incr('answer', 10), 52)
  175. self.assertEqual(self.cache.get('answer'), 52)
  176. self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
  177. def test_decr(self):
  178. # Cache values can be decremented
  179. self.cache.set('answer', 43)
  180. self.assertEqual(self.cache.decr('answer'), 42)
  181. self.assertEqual(self.cache.get('answer'), 42)
  182. self.assertEqual(self.cache.decr('answer', 10), 32)
  183. self.assertEqual(self.cache.get('answer'), 32)
  184. self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
  185. def test_data_types(self):
  186. # Many different data types can be cached
  187. stuff = {
  188. 'string' : 'this is a string',
  189. 'int' : 42,
  190. 'list' : [1, 2, 3, 4],
  191. 'tuple' : (1, 2, 3, 4),
  192. 'dict' : {'A': 1, 'B' : 2},
  193. 'function' : f,
  194. 'class' : C,
  195. }
  196. self.cache.set("stuff", stuff)
  197. self.assertEqual(self.cache.get("stuff"), stuff)
  198. def test_cache_read_for_model_instance(self):
  199. # Don't want fields with callable as default to be called on cache read
  200. expensive_calculation.num_runs = 0
  201. Poll.objects.all().delete()
  202. my_poll = Poll.objects.create(question="Well?")
  203. self.assertEqual(Poll.objects.count(), 1)
  204. pub_date = my_poll.pub_date
  205. self.cache.set('question', my_poll)
  206. cached_poll = self.cache.get('question')
  207. self.assertEqual(cached_poll.pub_date, pub_date)
  208. # We only want the default expensive calculation run once
  209. self.assertEqual(expensive_calculation.num_runs, 1)
  210. def test_cache_write_for_model_instance_with_deferred(self):
  211. # Don't want fields with callable as default to be called on cache write
  212. expensive_calculation.num_runs = 0
  213. Poll.objects.all().delete()
  214. my_poll = Poll.objects.create(question="What?")
  215. self.assertEqual(expensive_calculation.num_runs, 1)
  216. defer_qs = Poll.objects.all().defer('question')
  217. self.assertEqual(defer_qs.count(), 1)
  218. self.assertEqual(expensive_calculation.num_runs, 1)
  219. self.cache.set('deferred_queryset', defer_qs)
  220. # cache set should not re-evaluate default functions
  221. self.assertEqual(expensive_calculation.num_runs, 1)
  222. def test_cache_read_for_model_instance_with_deferred(self):
  223. # Don't want fields with callable as default to be called on cache read
  224. expensive_calculation.num_runs = 0
  225. Poll.objects.all().delete()
  226. my_poll = Poll.objects.create(question="What?")
  227. self.assertEqual(expensive_calculation.num_runs, 1)
  228. defer_qs = Poll.objects.all().defer('question')
  229. self.assertEqual(defer_qs.count(), 1)
  230. self.cache.set('deferred_queryset', defer_qs)
  231. self.assertEqual(expensive_calculation.num_runs, 1)
  232. runs_before_cache_read = expensive_calculation.num_runs
  233. cached_polls = self.cache.get('deferred_queryset')
  234. # We only want the default expensive calculation run on creation and set
  235. self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read)
  236. def test_expiration(self):
  237. # Cache values can be set to expire
  238. self.cache.set('expire1', 'very quickly', 1)
  239. self.cache.set('expire2', 'very quickly', 1)
  240. self.cache.set('expire3', 'very quickly', 1)
  241. time.sleep(2)
  242. self.assertEqual(self.cache.get("expire1"), None)
  243. self.cache.add("expire2", "newvalue")
  244. self.assertEqual(self.cache.get("expire2"), "newvalue")
  245. self.assertEqual(self.cache.has_key("expire3"), False)
  246. def test_unicode(self):
  247. # Unicode values can be cached
  248. stuff = {
  249. u'ascii': u'ascii_value',
  250. u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1',
  251. u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2',
  252. u'ascii': {u'x' : 1 }
  253. }
  254. for (key, value) in stuff.items():
  255. self.cache.set(key, value)
  256. self.assertEqual(self.cache.get(key), value)
  257. def test_binary_string(self):
  258. # Binary strings should be cachable
  259. from zlib import compress, decompress
  260. value = 'value_to_be_compressed'
  261. compressed_value = compress(value)
  262. self.cache.set('binary1', compressed_value)
  263. compressed_result = self.cache.get('binary1')
  264. self.assertEqual(compressed_value, compressed_result)
  265. self.assertEqual(value, decompress(compressed_result))
  266. def test_set_many(self):
  267. # Multiple keys can be set using set_many
  268. self.cache.set_many({"key1": "spam", "key2": "eggs"})
  269. self.assertEqual(self.cache.get("key1"), "spam")
  270. self.assertEqual(self.cache.get("key2"), "eggs")
  271. def test_set_many_expiration(self):
  272. # set_many takes a second ``timeout`` parameter
  273. self.cache.set_many({"key1": "spam", "key2": "eggs"}, 1)
  274. time.sleep(2)
  275. self.assertEqual(self.cache.get("key1"), None)
  276. self.assertEqual(self.cache.get("key2"), None)
  277. def test_delete_many(self):
  278. # Multiple keys can be deleted using delete_many
  279. self.cache.set("key1", "spam")
  280. self.cache.set("key2", "eggs")
  281. self.cache.set("key3", "ham")
  282. self.cache.delete_many(["key1", "key2"])
  283. self.assertEqual(self.cache.get("key1"), None)
  284. self.assertEqual(self.cache.get("key2"), None)
  285. self.assertEqual(self.cache.get("key3"), "ham")
  286. def test_clear(self):
  287. # The cache can be emptied using clear
  288. self.cache.set("key1", "spam")
  289. self.cache.set("key2", "eggs")
  290. self.cache.clear()
  291. self.assertEqual(self.cache.get("key1"), None)
  292. self.assertEqual(self.cache.get("key2"), None)
  293. def test_long_timeout(self):
  294. '''
  295. Using a timeout greater than 30 days makes memcached think
  296. it is an absolute expiration timestamp instead of a relative
  297. offset. Test that we honour this convention. Refs #12399.
  298. '''
  299. self.cache.set('key1', 'eggs', 60*60*24*30 + 1) #30 days + 1 second
  300. self.assertEqual(self.cache.get('key1'), 'eggs')
  301. self.cache.add('key2', 'ham', 60*60*24*30 + 1)
  302. self.assertEqual(self.cache.get('key2'), 'ham')
  303. self.cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, 60*60*24*30 + 1)
  304. self.assertEqual(self.cache.get('key3'), 'sausage')
  305. self.assertEqual(self.cache.get('key4'), 'lobster bisque')
  306. def perform_cull_test(self, initial_count, final_count):
  307. """This is implemented as a utility method, because only some of the backends
  308. implement culling. The culling algorithm also varies slightly, so the final
  309. number of entries will vary between backends"""
  310. # Create initial cache key entries. This will overflow the cache, causing a cull
  311. for i in range(1, initial_count):
  312. self.cache.set('cull%d' % i, 'value', 1000)
  313. count = 0
  314. # Count how many keys are left in the cache.
  315. for i in range(1, initial_count):
  316. if self.cache.has_key('cull%d' % i):
  317. count = count + 1
  318. self.assertEqual(count, final_count)
  319. def test_invalid_keys(self):
  320. """
  321. All the builtin backends (except memcached, see below) should warn on
  322. keys that would be refused by memcached. This encourages portable
  323. caching code without making it too difficult to use production backends
  324. with more liberal key rules. Refs #6447.
  325. """
  326. # On Python 2.6+ we could use the catch_warnings context
  327. # manager to test this warning nicely. Since we can't do that
  328. # yet, the cleanest option is to temporarily ask for
  329. # CacheKeyWarning to be raised as an exception.
  330. warnings.simplefilter("error", CacheKeyWarning)
  331. # memcached does not allow whitespace or control characters in keys
  332. self.assertRaises(CacheKeyWarning, self.cache.set, 'key with spaces', 'value')
  333. # memcached limits key length to 250
  334. self.assertRaises(CacheKeyWarning, self.cache.set, 'a' * 251, 'value')
  335. # The warnings module has no public API for getting the
  336. # current list of warning filters, so we can't save that off
  337. # and reset to the previous value, we have to globally reset
  338. # it. The effect will be the same, as long as the Django test
  339. # runner doesn't add any global warning filters (it currently
  340. # does not).
  341. warnings.resetwarnings()
  342. warnings.simplefilter("ignore", PendingDeprecationWarning)
  343. class DBCacheTests(unittest.TestCase, BaseCacheTests):
  344. def setUp(self):
  345. # Spaces are used in the table name to ensure quoting/escaping is working
  346. self._table_name = 'test cache table'
  347. management.call_command('createcachetable', self._table_name, verbosity=0, interactive=False)
  348. self.cache = get_cache('db://%s?max_entries=30' % self._table_name)
  349. def tearDown(self):
  350. from django.db import connection
  351. cursor = connection.cursor()
  352. cursor.execute('DROP TABLE %s' % connection.ops.quote_name(self._table_name))
  353. def test_cull(self):
  354. self.perform_cull_test(50, 29)
  355. class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
  356. def setUp(self):
  357. self.cache = get_cache('locmem://?max_entries=30')
  358. def test_cull(self):
  359. self.perform_cull_test(50, 29)
  360. # memcached backend isn't guaranteed to be available.
  361. # To check the memcached backend, the test settings file will
  362. # need to contain a CACHE_BACKEND setting that points at
  363. # your memcache server.
  364. if settings.CACHE_BACKEND.startswith('memcached://'):
  365. class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
  366. def setUp(self):
  367. self.cache = get_cache(settings.CACHE_BACKEND)
  368. def test_invalid_keys(self):
  369. """
  370. On memcached, we don't introduce a duplicate key validation
  371. step (for speed reasons), we just let the memcached API
  372. library raise its own exception on bad keys. Refs #6447.
  373. In order to be memcached-API-library agnostic, we only assert
  374. that a generic exception of some kind is raised.
  375. """
  376. # memcached does not allow whitespace or control characters in keys
  377. self.assertRaises(Exception, self.cache.set, 'key with spaces', 'value')
  378. # memcached limits key length to 250
  379. self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value')
  380. class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
  381. """
  382. Specific test cases for the file-based cache.
  383. """
  384. def setUp(self):
  385. self.dirname = tempfile.mkdtemp()
  386. self.cache = get_cache('file://%s?max_entries=30' % self.dirname)
  387. def test_hashing(self):
  388. """Test that keys are hashed into subdirectories correctly"""
  389. self.cache.set("foo", "bar")
  390. keyhash = md5_constructor("foo").hexdigest()
  391. keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
  392. self.assert_(os.path.exists(keypath))
  393. def test_subdirectory_removal(self):
  394. """
  395. Make sure that the created subdirectories are correctly removed when empty.
  396. """
  397. self.cache.set("foo", "bar")
  398. keyhash = md5_constructor("foo").hexdigest()
  399. keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
  400. self.assert_(os.path.exists(keypath))
  401. self.cache.delete("foo")
  402. self.assert_(not os.path.exists(keypath))
  403. self.assert_(not os.path.exists(os.path.dirname(keypath)))
  404. self.assert_(not os.path.exists(os.path.dirname(os.path.dirname(keypath))))
  405. def test_cull(self):
  406. self.perform_cull_test(50, 28)
  407. class CustomCacheKeyValidationTests(unittest.TestCase):
  408. """
  409. Tests for the ability to mixin a custom ``validate_key`` method to
  410. a custom cache backend that otherwise inherits from a builtin
  411. backend, and override the default key validation. Refs #6447.
  412. """
  413. def test_custom_key_validation(self):
  414. cache = get_cache('regressiontests.cache.liberal_backend://')
  415. # this key is both longer than 250 characters, and has spaces
  416. key = 'some key with spaces' * 15
  417. val = 'a value'
  418. cache.set(key, val)
  419. self.assertEqual(cache.get(key), val)
  420. class CacheUtils(unittest.TestCase):
  421. """TestCase for django.utils.cache functions."""
  422. def setUp(self):
  423. self.path = '/cache/test/'
  424. self.old_settings_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  425. self.old_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
  426. self.orig_use_i18n = settings.USE_I18N
  427. settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
  428. settings.CACHE_MIDDLEWARE_SECONDS = 1
  429. settings.USE_I18N = False
  430. def tearDown(self):
  431. settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.old_settings_key_prefix
  432. settings.CACHE_MIDDLEWARE_SECONDS = self.old_middleware_seconds
  433. settings.USE_I18N = self.orig_use_i18n
  434. def _get_request(self, path):
  435. request = HttpRequest()
  436. request.META = {
  437. 'SERVER_NAME': 'testserver',
  438. 'SERVER_PORT': 80,
  439. }
  440. request.path = request.path_info = "/cache/%s" % path
  441. return request
  442. def test_patch_vary_headers(self):
  443. headers = (
  444. # Initial vary, new headers, resulting vary.
  445. (None, ('Accept-Encoding',), 'Accept-Encoding'),
  446. ('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
  447. ('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
  448. ('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  449. ('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  450. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  451. (None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
  452. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  453. ('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  454. )
  455. for initial_vary, newheaders, resulting_vary in headers:
  456. response = HttpResponse()
  457. if initial_vary is not None:
  458. response['Vary'] = initial_vary
  459. patch_vary_headers(response, newheaders)
  460. self.assertEqual(response['Vary'], resulting_vary)
  461. def test_get_cache_key(self):
  462. request = self._get_request(self.path)
  463. response = HttpResponse()
  464. key_prefix = 'localprefix'
  465. # Expect None if no headers have been set yet.
  466. self.assertEqual(get_cache_key(request), None)
  467. # Set headers to an empty list.
  468. learn_cache_key(request, response)
  469. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  470. # Verify that a specified key_prefix is taken in to account.
  471. learn_cache_key(request, response, key_prefix=key_prefix)
  472. self.assertEqual(get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  473. def test_learn_cache_key(self):
  474. request = self._get_request(self.path)
  475. response = HttpResponse()
  476. response['Vary'] = 'Pony'
  477. # Make sure that the Vary header is added to the key hash
  478. learn_cache_key(request, response)
  479. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  480. class CacheI18nTest(unittest.TestCase):
  481. def setUp(self):
  482. self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
  483. self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  484. self.orig_cache_backend = settings.CACHE_BACKEND
  485. self.orig_use_i18n = settings.USE_I18N
  486. self.orig_languages = settings.LANGUAGES
  487. settings.LANGUAGES = (
  488. ('en', 'English'),
  489. ('es', 'Spanish'),
  490. )
  491. settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
  492. self.path = '/cache/test/'
  493. def tearDown(self):
  494. settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds
  495. settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix
  496. settings.CACHE_BACKEND = self.orig_cache_backend
  497. settings.USE_I18N = self.orig_use_i18n
  498. settings.LANGUAGES = self.orig_languages
  499. translation.deactivate()
  500. def _get_request(self):
  501. request = HttpRequest()
  502. request.META = {
  503. 'SERVER_NAME': 'testserver',
  504. 'SERVER_PORT': 80,
  505. }
  506. request.path = request.path_info = self.path
  507. return request
  508. def _get_request_cache(self):
  509. request = HttpRequest()
  510. request.META = {
  511. 'SERVER_NAME': 'testserver',
  512. 'SERVER_PORT': 80,
  513. }
  514. request.path = request.path_info = self.path
  515. request._cache_update_cache = True
  516. request.method = 'GET'
  517. request.session = {}
  518. return request
  519. def test_cache_key_i18n(self):
  520. settings.USE_I18N = True
  521. request = self._get_request()
  522. lang = translation.get_language()
  523. response = HttpResponse()
  524. key = learn_cache_key(request, response)
  525. self.assertTrue(key.endswith(lang), "Cache keys should include the language name when i18n is active")
  526. key2 = get_cache_key(request)
  527. self.assertEqual(key, key2)
  528. def test_cache_key_no_i18n (self):
  529. settings.USE_I18N = False
  530. request = self._get_request()
  531. lang = translation.get_language()
  532. response = HttpResponse()
  533. key = learn_cache_key(request, response)
  534. self.assertFalse(key.endswith(lang), "Cache keys shouldn't include the language name when i18n is inactive")
  535. def test_middleware(self):
  536. def set_cache(request, lang, msg):
  537. translation.activate(lang)
  538. response = HttpResponse()
  539. response.content= msg
  540. return UpdateCacheMiddleware().process_response(request, response)
  541. settings.CACHE_MIDDLEWARE_SECONDS = 60
  542. settings.CACHE_MIDDLEWARE_KEY_PREFIX="test"
  543. settings.CACHE_BACKEND='locmem:///'
  544. settings.USE_I18N = True
  545. en_message ="Hello world!"
  546. es_message ="Hola mundo!"
  547. request = self._get_request_cache()
  548. set_cache(request, 'en', en_message)
  549. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  550. # Check that we can recover the cache
  551. self.assertNotEqual(get_cache_data.content, None)
  552. self.assertEqual(en_message, get_cache_data.content)
  553. # change the session language and set content
  554. request = self._get_request_cache()
  555. set_cache(request, 'es', es_message)
  556. # change again the language
  557. translation.activate('en')
  558. # retrieve the content from cache
  559. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  560. self.assertEqual(get_cache_data.content, en_message)
  561. # change again the language
  562. translation.activate('es')
  563. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  564. self.assertEqual(get_cache_data.content, es_message)
  565. if __name__ == '__main__':
  566. unittest.main()