PageRenderTime 75ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/cache/tests.py

https://code.google.com/p/mango-py/
Python | 1462 lines | 1239 code | 136 blank | 87 comment | 12 complexity | 2345451cc3c4a3510d7cac5f4263a224 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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 re
  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, DEFAULT_CACHE_ALIAS
  12. from django.core.cache.backends.base import CacheKeyWarning
  13. from django.http import HttpResponse, HttpRequest, QueryDict
  14. from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware, CacheMiddleware
  15. from django.test import RequestFactory
  16. from django.test.utils import get_warnings_state, restore_warnings_state
  17. from django.utils import translation
  18. from django.utils import unittest
  19. from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key, patch_cache_control
  20. from django.utils.hashcompat import md5_constructor
  21. from django.views.decorators.cache import cache_page
  22. from regressiontests.cache.models import Poll, expensive_calculation
  23. # functions/classes for complex data type tests
  24. def f():
  25. return 42
  26. class C:
  27. def m(n):
  28. return 24
  29. class DummyCacheTests(unittest.TestCase):
  30. # The Dummy cache backend doesn't really behave like a test backend,
  31. # so it has different test requirements.
  32. def setUp(self):
  33. self.cache = get_cache('django.core.cache.backends.dummy.DummyCache')
  34. def test_simple(self):
  35. "Dummy cache backend ignores cache set calls"
  36. self.cache.set("key", "value")
  37. self.assertEqual(self.cache.get("key"), None)
  38. def test_add(self):
  39. "Add doesn't do anything in dummy cache backend"
  40. self.cache.add("addkey1", "value")
  41. result = self.cache.add("addkey1", "newvalue")
  42. self.assertEqual(result, True)
  43. self.assertEqual(self.cache.get("addkey1"), None)
  44. def test_non_existent(self):
  45. "Non-existent keys aren't found in the dummy cache backend"
  46. self.assertEqual(self.cache.get("does_not_exist"), None)
  47. self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  48. def test_get_many(self):
  49. "get_many returns nothing for the dummy cache backend"
  50. self.cache.set('a', 'a')
  51. self.cache.set('b', 'b')
  52. self.cache.set('c', 'c')
  53. self.cache.set('d', 'd')
  54. self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {})
  55. self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {})
  56. def test_delete(self):
  57. "Cache deletion is transparently ignored on the dummy cache backend"
  58. self.cache.set("key1", "spam")
  59. self.cache.set("key2", "eggs")
  60. self.assertEqual(self.cache.get("key1"), None)
  61. self.cache.delete("key1")
  62. self.assertEqual(self.cache.get("key1"), None)
  63. self.assertEqual(self.cache.get("key2"), None)
  64. def test_has_key(self):
  65. "The has_key method doesn't ever return True for the dummy cache backend"
  66. self.cache.set("hello1", "goodbye1")
  67. self.assertEqual(self.cache.has_key("hello1"), False)
  68. self.assertEqual(self.cache.has_key("goodbye1"), False)
  69. def test_in(self):
  70. "The in operator doesn't ever return True for the dummy cache backend"
  71. self.cache.set("hello2", "goodbye2")
  72. self.assertEqual("hello2" in self.cache, False)
  73. self.assertEqual("goodbye2" in self.cache, False)
  74. def test_incr(self):
  75. "Dummy cache values can't be incremented"
  76. self.cache.set('answer', 42)
  77. self.assertRaises(ValueError, self.cache.incr, 'answer')
  78. self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
  79. def test_decr(self):
  80. "Dummy cache values can't be decremented"
  81. self.cache.set('answer', 42)
  82. self.assertRaises(ValueError, self.cache.decr, 'answer')
  83. self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
  84. def test_data_types(self):
  85. "All data types are ignored equally by the dummy cache"
  86. stuff = {
  87. 'string' : 'this is a string',
  88. 'int' : 42,
  89. 'list' : [1, 2, 3, 4],
  90. 'tuple' : (1, 2, 3, 4),
  91. 'dict' : {'A': 1, 'B' : 2},
  92. 'function' : f,
  93. 'class' : C,
  94. }
  95. self.cache.set("stuff", stuff)
  96. self.assertEqual(self.cache.get("stuff"), None)
  97. def test_expiration(self):
  98. "Expiration has no effect on the dummy cache"
  99. self.cache.set('expire1', 'very quickly', 1)
  100. self.cache.set('expire2', 'very quickly', 1)
  101. self.cache.set('expire3', 'very quickly', 1)
  102. time.sleep(2)
  103. self.assertEqual(self.cache.get("expire1"), None)
  104. self.cache.add("expire2", "newvalue")
  105. self.assertEqual(self.cache.get("expire2"), None)
  106. self.assertEqual(self.cache.has_key("expire3"), False)
  107. def test_unicode(self):
  108. "Unicode values are ignored by the dummy cache"
  109. stuff = {
  110. u'ascii': u'ascii_value',
  111. u'unicode_ascii': u'Ińtërnâtiônŕlizćtiřn1',
  112. u'Ińtërnâtiônŕlizćtiřn': u'Ińtërnâtiônŕlizćtiřn2',
  113. u'ascii': {u'x' : 1 }
  114. }
  115. for (key, value) in stuff.items():
  116. self.cache.set(key, value)
  117. self.assertEqual(self.cache.get(key), None)
  118. def test_set_many(self):
  119. "set_many does nothing for the dummy cache backend"
  120. self.cache.set_many({'a': 1, 'b': 2})
  121. def test_delete_many(self):
  122. "delete_many does nothing for the dummy cache backend"
  123. self.cache.delete_many(['a', 'b'])
  124. def test_clear(self):
  125. "clear does nothing for the dummy cache backend"
  126. self.cache.clear()
  127. def test_incr_version(self):
  128. "Dummy cache versions can't be incremented"
  129. self.cache.set('answer', 42)
  130. self.assertRaises(ValueError, self.cache.incr_version, 'answer')
  131. self.assertRaises(ValueError, self.cache.incr_version, 'does_not_exist')
  132. def test_decr_version(self):
  133. "Dummy cache versions can't be decremented"
  134. self.cache.set('answer', 42)
  135. self.assertRaises(ValueError, self.cache.decr_version, 'answer')
  136. self.assertRaises(ValueError, self.cache.decr_version, 'does_not_exist')
  137. class BaseCacheTests(object):
  138. # A common set of tests to apply to all cache backends
  139. def test_simple(self):
  140. # Simple cache set/get works
  141. self.cache.set("key", "value")
  142. self.assertEqual(self.cache.get("key"), "value")
  143. def test_add(self):
  144. # A key can be added to a cache
  145. self.cache.add("addkey1", "value")
  146. result = self.cache.add("addkey1", "newvalue")
  147. self.assertEqual(result, False)
  148. self.assertEqual(self.cache.get("addkey1"), "value")
  149. def test_prefix(self):
  150. # Test for same cache key conflicts between shared backend
  151. self.cache.set('somekey', 'value')
  152. # should not be set in the prefixed cache
  153. self.assertFalse(self.prefix_cache.has_key('somekey'))
  154. self.prefix_cache.set('somekey', 'value2')
  155. self.assertEqual(self.cache.get('somekey'), 'value')
  156. self.assertEqual(self.prefix_cache.get('somekey'), 'value2')
  157. def test_non_existent(self):
  158. # Non-existent cache keys return as None/default
  159. # get with non-existent keys
  160. self.assertEqual(self.cache.get("does_not_exist"), None)
  161. self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  162. def test_get_many(self):
  163. # Multiple cache keys can be returned using get_many
  164. self.cache.set('a', 'a')
  165. self.cache.set('b', 'b')
  166. self.cache.set('c', 'c')
  167. self.cache.set('d', 'd')
  168. self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {'a' : 'a', 'c' : 'c', 'd' : 'd'})
  169. self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'})
  170. def test_delete(self):
  171. # Cache keys can be deleted
  172. self.cache.set("key1", "spam")
  173. self.cache.set("key2", "eggs")
  174. self.assertEqual(self.cache.get("key1"), "spam")
  175. self.cache.delete("key1")
  176. self.assertEqual(self.cache.get("key1"), None)
  177. self.assertEqual(self.cache.get("key2"), "eggs")
  178. def test_has_key(self):
  179. # The cache can be inspected for cache keys
  180. self.cache.set("hello1", "goodbye1")
  181. self.assertEqual(self.cache.has_key("hello1"), True)
  182. self.assertEqual(self.cache.has_key("goodbye1"), False)
  183. def test_in(self):
  184. # The in operator can be used to inspet cache contents
  185. self.cache.set("hello2", "goodbye2")
  186. self.assertEqual("hello2" in self.cache, True)
  187. self.assertEqual("goodbye2" in self.cache, False)
  188. def test_incr(self):
  189. # Cache values can be incremented
  190. self.cache.set('answer', 41)
  191. self.assertEqual(self.cache.incr('answer'), 42)
  192. self.assertEqual(self.cache.get('answer'), 42)
  193. self.assertEqual(self.cache.incr('answer', 10), 52)
  194. self.assertEqual(self.cache.get('answer'), 52)
  195. self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
  196. def test_decr(self):
  197. # Cache values can be decremented
  198. self.cache.set('answer', 43)
  199. self.assertEqual(self.cache.decr('answer'), 42)
  200. self.assertEqual(self.cache.get('answer'), 42)
  201. self.assertEqual(self.cache.decr('answer', 10), 32)
  202. self.assertEqual(self.cache.get('answer'), 32)
  203. self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
  204. def test_data_types(self):
  205. # Many different data types can be cached
  206. stuff = {
  207. 'string' : 'this is a string',
  208. 'int' : 42,
  209. 'list' : [1, 2, 3, 4],
  210. 'tuple' : (1, 2, 3, 4),
  211. 'dict' : {'A': 1, 'B' : 2},
  212. 'function' : f,
  213. 'class' : C,
  214. }
  215. self.cache.set("stuff", stuff)
  216. self.assertEqual(self.cache.get("stuff"), stuff)
  217. def test_cache_read_for_model_instance(self):
  218. # Don't want fields with callable as default to be called on cache read
  219. expensive_calculation.num_runs = 0
  220. Poll.objects.all().delete()
  221. my_poll = Poll.objects.create(question="Well?")
  222. self.assertEqual(Poll.objects.count(), 1)
  223. pub_date = my_poll.pub_date
  224. self.cache.set('question', my_poll)
  225. cached_poll = self.cache.get('question')
  226. self.assertEqual(cached_poll.pub_date, pub_date)
  227. # We only want the default expensive calculation run once
  228. self.assertEqual(expensive_calculation.num_runs, 1)
  229. def test_cache_write_for_model_instance_with_deferred(self):
  230. # Don't want fields with callable as default to be called on cache write
  231. expensive_calculation.num_runs = 0
  232. Poll.objects.all().delete()
  233. my_poll = Poll.objects.create(question="What?")
  234. self.assertEqual(expensive_calculation.num_runs, 1)
  235. defer_qs = Poll.objects.all().defer('question')
  236. self.assertEqual(defer_qs.count(), 1)
  237. self.assertEqual(expensive_calculation.num_runs, 1)
  238. self.cache.set('deferred_queryset', defer_qs)
  239. # cache set should not re-evaluate default functions
  240. self.assertEqual(expensive_calculation.num_runs, 1)
  241. def test_cache_read_for_model_instance_with_deferred(self):
  242. # Don't want fields with callable as default to be called on cache read
  243. expensive_calculation.num_runs = 0
  244. Poll.objects.all().delete()
  245. my_poll = Poll.objects.create(question="What?")
  246. self.assertEqual(expensive_calculation.num_runs, 1)
  247. defer_qs = Poll.objects.all().defer('question')
  248. self.assertEqual(defer_qs.count(), 1)
  249. self.cache.set('deferred_queryset', defer_qs)
  250. self.assertEqual(expensive_calculation.num_runs, 1)
  251. runs_before_cache_read = expensive_calculation.num_runs
  252. cached_polls = self.cache.get('deferred_queryset')
  253. # We only want the default expensive calculation run on creation and set
  254. self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read)
  255. def test_expiration(self):
  256. # Cache values can be set to expire
  257. self.cache.set('expire1', 'very quickly', 1)
  258. self.cache.set('expire2', 'very quickly', 1)
  259. self.cache.set('expire3', 'very quickly', 1)
  260. time.sleep(2)
  261. self.assertEqual(self.cache.get("expire1"), None)
  262. self.cache.add("expire2", "newvalue")
  263. self.assertEqual(self.cache.get("expire2"), "newvalue")
  264. self.assertEqual(self.cache.has_key("expire3"), False)
  265. def test_unicode(self):
  266. # Unicode values can be cached
  267. stuff = {
  268. u'ascii': u'ascii_value',
  269. u'unicode_ascii': u'Ińtërnâtiônŕlizćtiřn1',
  270. u'Ińtërnâtiônŕlizćtiřn': u'Ińtërnâtiônŕlizćtiřn2',
  271. u'ascii': {u'x' : 1 }
  272. }
  273. # Test `set`
  274. for (key, value) in stuff.items():
  275. self.cache.set(key, value)
  276. self.assertEqual(self.cache.get(key), value)
  277. # Test `add`
  278. for (key, value) in stuff.items():
  279. self.cache.delete(key)
  280. self.cache.add(key, value)
  281. self.assertEqual(self.cache.get(key), value)
  282. # Test `set_many`
  283. for (key, value) in stuff.items():
  284. self.cache.delete(key)
  285. self.cache.set_many(stuff)
  286. for (key, value) in stuff.items():
  287. self.assertEqual(self.cache.get(key), value)
  288. def test_binary_string(self):
  289. # Binary strings should be cachable
  290. from zlib import compress, decompress
  291. value = 'value_to_be_compressed'
  292. compressed_value = compress(value)
  293. # Test set
  294. self.cache.set('binary1', compressed_value)
  295. compressed_result = self.cache.get('binary1')
  296. self.assertEqual(compressed_value, compressed_result)
  297. self.assertEqual(value, decompress(compressed_result))
  298. # Test add
  299. self.cache.add('binary1-add', compressed_value)
  300. compressed_result = self.cache.get('binary1-add')
  301. self.assertEqual(compressed_value, compressed_result)
  302. self.assertEqual(value, decompress(compressed_result))
  303. # Test set_many
  304. self.cache.set_many({'binary1-set_many': compressed_value})
  305. compressed_result = self.cache.get('binary1-set_many')
  306. self.assertEqual(compressed_value, compressed_result)
  307. self.assertEqual(value, decompress(compressed_result))
  308. def test_set_many(self):
  309. # Multiple keys can be set using set_many
  310. self.cache.set_many({"key1": "spam", "key2": "eggs"})
  311. self.assertEqual(self.cache.get("key1"), "spam")
  312. self.assertEqual(self.cache.get("key2"), "eggs")
  313. def test_set_many_expiration(self):
  314. # set_many takes a second ``timeout`` parameter
  315. self.cache.set_many({"key1": "spam", "key2": "eggs"}, 1)
  316. time.sleep(2)
  317. self.assertEqual(self.cache.get("key1"), None)
  318. self.assertEqual(self.cache.get("key2"), None)
  319. def test_delete_many(self):
  320. # Multiple keys can be deleted using delete_many
  321. self.cache.set("key1", "spam")
  322. self.cache.set("key2", "eggs")
  323. self.cache.set("key3", "ham")
  324. self.cache.delete_many(["key1", "key2"])
  325. self.assertEqual(self.cache.get("key1"), None)
  326. self.assertEqual(self.cache.get("key2"), None)
  327. self.assertEqual(self.cache.get("key3"), "ham")
  328. def test_clear(self):
  329. # The cache can be emptied using clear
  330. self.cache.set("key1", "spam")
  331. self.cache.set("key2", "eggs")
  332. self.cache.clear()
  333. self.assertEqual(self.cache.get("key1"), None)
  334. self.assertEqual(self.cache.get("key2"), None)
  335. def test_long_timeout(self):
  336. '''
  337. Using a timeout greater than 30 days makes memcached think
  338. it is an absolute expiration timestamp instead of a relative
  339. offset. Test that we honour this convention. Refs #12399.
  340. '''
  341. self.cache.set('key1', 'eggs', 60*60*24*30 + 1) #30 days + 1 second
  342. self.assertEqual(self.cache.get('key1'), 'eggs')
  343. self.cache.add('key2', 'ham', 60*60*24*30 + 1)
  344. self.assertEqual(self.cache.get('key2'), 'ham')
  345. self.cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, 60*60*24*30 + 1)
  346. self.assertEqual(self.cache.get('key3'), 'sausage')
  347. self.assertEqual(self.cache.get('key4'), 'lobster bisque')
  348. def perform_cull_test(self, initial_count, final_count):
  349. """This is implemented as a utility method, because only some of the backends
  350. implement culling. The culling algorithm also varies slightly, so the final
  351. number of entries will vary between backends"""
  352. # Create initial cache key entries. This will overflow the cache, causing a cull
  353. for i in range(1, initial_count):
  354. self.cache.set('cull%d' % i, 'value', 1000)
  355. count = 0
  356. # Count how many keys are left in the cache.
  357. for i in range(1, initial_count):
  358. if self.cache.has_key('cull%d' % i):
  359. count = count + 1
  360. self.assertEqual(count, final_count)
  361. def test_invalid_keys(self):
  362. """
  363. All the builtin backends (except memcached, see below) should warn on
  364. keys that would be refused by memcached. This encourages portable
  365. caching code without making it too difficult to use production backends
  366. with more liberal key rules. Refs #6447.
  367. """
  368. # mimic custom ``make_key`` method being defined since the default will
  369. # never show the below warnings
  370. def func(key, *args):
  371. return key
  372. old_func = self.cache.key_func
  373. self.cache.key_func = func
  374. # On Python 2.6+ we could use the catch_warnings context
  375. # manager to test this warning nicely. Since we can't do that
  376. # yet, the cleanest option is to temporarily ask for
  377. # CacheKeyWarning to be raised as an exception.
  378. _warnings_state = get_warnings_state()
  379. warnings.simplefilter("error", CacheKeyWarning)
  380. try:
  381. # memcached does not allow whitespace or control characters in keys
  382. self.assertRaises(CacheKeyWarning, self.cache.set, 'key with spaces', 'value')
  383. # memcached limits key length to 250
  384. self.assertRaises(CacheKeyWarning, self.cache.set, 'a' * 251, 'value')
  385. finally:
  386. restore_warnings_state(_warnings_state)
  387. self.cache.key_func = old_func
  388. def test_cache_versioning_get_set(self):
  389. # set, using default version = 1
  390. self.cache.set('answer1', 42)
  391. self.assertEqual(self.cache.get('answer1'), 42)
  392. self.assertEqual(self.cache.get('answer1', version=1), 42)
  393. self.assertEqual(self.cache.get('answer1', version=2), None)
  394. self.assertEqual(self.v2_cache.get('answer1'), None)
  395. self.assertEqual(self.v2_cache.get('answer1', version=1), 42)
  396. self.assertEqual(self.v2_cache.get('answer1', version=2), None)
  397. # set, default version = 1, but manually override version = 2
  398. self.cache.set('answer2', 42, version=2)
  399. self.assertEqual(self.cache.get('answer2'), None)
  400. self.assertEqual(self.cache.get('answer2', version=1), None)
  401. self.assertEqual(self.cache.get('answer2', version=2), 42)
  402. self.assertEqual(self.v2_cache.get('answer2'), 42)
  403. self.assertEqual(self.v2_cache.get('answer2', version=1), None)
  404. self.assertEqual(self.v2_cache.get('answer2', version=2), 42)
  405. # v2 set, using default version = 2
  406. self.v2_cache.set('answer3', 42)
  407. self.assertEqual(self.cache.get('answer3'), None)
  408. self.assertEqual(self.cache.get('answer3', version=1), None)
  409. self.assertEqual(self.cache.get('answer3', version=2), 42)
  410. self.assertEqual(self.v2_cache.get('answer3'), 42)
  411. self.assertEqual(self.v2_cache.get('answer3', version=1), None)
  412. self.assertEqual(self.v2_cache.get('answer3', version=2), 42)
  413. # v2 set, default version = 2, but manually override version = 1
  414. self.v2_cache.set('answer4', 42, version=1)
  415. self.assertEqual(self.cache.get('answer4'), 42)
  416. self.assertEqual(self.cache.get('answer4', version=1), 42)
  417. self.assertEqual(self.cache.get('answer4', version=2), None)
  418. self.assertEqual(self.v2_cache.get('answer4'), None)
  419. self.assertEqual(self.v2_cache.get('answer4', version=1), 42)
  420. self.assertEqual(self.v2_cache.get('answer4', version=2), None)
  421. def test_cache_versioning_add(self):
  422. # add, default version = 1, but manually override version = 2
  423. self.cache.add('answer1', 42, version=2)
  424. self.assertEqual(self.cache.get('answer1', version=1), None)
  425. self.assertEqual(self.cache.get('answer1', version=2), 42)
  426. self.cache.add('answer1', 37, version=2)
  427. self.assertEqual(self.cache.get('answer1', version=1), None)
  428. self.assertEqual(self.cache.get('answer1', version=2), 42)
  429. self.cache.add('answer1', 37, version=1)
  430. self.assertEqual(self.cache.get('answer1', version=1), 37)
  431. self.assertEqual(self.cache.get('answer1', version=2), 42)
  432. # v2 add, using default version = 2
  433. self.v2_cache.add('answer2', 42)
  434. self.assertEqual(self.cache.get('answer2', version=1), None)
  435. self.assertEqual(self.cache.get('answer2', version=2), 42)
  436. self.v2_cache.add('answer2', 37)
  437. self.assertEqual(self.cache.get('answer2', version=1), None)
  438. self.assertEqual(self.cache.get('answer2', version=2), 42)
  439. self.v2_cache.add('answer2', 37, version=1)
  440. self.assertEqual(self.cache.get('answer2', version=1), 37)
  441. self.assertEqual(self.cache.get('answer2', version=2), 42)
  442. # v2 add, default version = 2, but manually override version = 1
  443. self.v2_cache.add('answer3', 42, version=1)
  444. self.assertEqual(self.cache.get('answer3', version=1), 42)
  445. self.assertEqual(self.cache.get('answer3', version=2), None)
  446. self.v2_cache.add('answer3', 37, version=1)
  447. self.assertEqual(self.cache.get('answer3', version=1), 42)
  448. self.assertEqual(self.cache.get('answer3', version=2), None)
  449. self.v2_cache.add('answer3', 37)
  450. self.assertEqual(self.cache.get('answer3', version=1), 42)
  451. self.assertEqual(self.cache.get('answer3', version=2), 37)
  452. def test_cache_versioning_has_key(self):
  453. self.cache.set('answer1', 42)
  454. # has_key
  455. self.assertTrue(self.cache.has_key('answer1'))
  456. self.assertTrue(self.cache.has_key('answer1', version=1))
  457. self.assertFalse(self.cache.has_key('answer1', version=2))
  458. self.assertFalse(self.v2_cache.has_key('answer1'))
  459. self.assertTrue(self.v2_cache.has_key('answer1', version=1))
  460. self.assertFalse(self.v2_cache.has_key('answer1', version=2))
  461. def test_cache_versioning_delete(self):
  462. self.cache.set('answer1', 37, version=1)
  463. self.cache.set('answer1', 42, version=2)
  464. self.cache.delete('answer1')
  465. self.assertEqual(self.cache.get('answer1', version=1), None)
  466. self.assertEqual(self.cache.get('answer1', version=2), 42)
  467. self.cache.set('answer2', 37, version=1)
  468. self.cache.set('answer2', 42, version=2)
  469. self.cache.delete('answer2', version=2)
  470. self.assertEqual(self.cache.get('answer2', version=1), 37)
  471. self.assertEqual(self.cache.get('answer2', version=2), None)
  472. self.cache.set('answer3', 37, version=1)
  473. self.cache.set('answer3', 42, version=2)
  474. self.v2_cache.delete('answer3')
  475. self.assertEqual(self.cache.get('answer3', version=1), 37)
  476. self.assertEqual(self.cache.get('answer3', version=2), None)
  477. self.cache.set('answer4', 37, version=1)
  478. self.cache.set('answer4', 42, version=2)
  479. self.v2_cache.delete('answer4', version=1)
  480. self.assertEqual(self.cache.get('answer4', version=1), None)
  481. self.assertEqual(self.cache.get('answer4', version=2), 42)
  482. def test_cache_versioning_incr_decr(self):
  483. self.cache.set('answer1', 37, version=1)
  484. self.cache.set('answer1', 42, version=2)
  485. self.cache.incr('answer1')
  486. self.assertEqual(self.cache.get('answer1', version=1), 38)
  487. self.assertEqual(self.cache.get('answer1', version=2), 42)
  488. self.cache.decr('answer1')
  489. self.assertEqual(self.cache.get('answer1', version=1), 37)
  490. self.assertEqual(self.cache.get('answer1', version=2), 42)
  491. self.cache.set('answer2', 37, version=1)
  492. self.cache.set('answer2', 42, version=2)
  493. self.cache.incr('answer2', version=2)
  494. self.assertEqual(self.cache.get('answer2', version=1), 37)
  495. self.assertEqual(self.cache.get('answer2', version=2), 43)
  496. self.cache.decr('answer2', version=2)
  497. self.assertEqual(self.cache.get('answer2', version=1), 37)
  498. self.assertEqual(self.cache.get('answer2', version=2), 42)
  499. self.cache.set('answer3', 37, version=1)
  500. self.cache.set('answer3', 42, version=2)
  501. self.v2_cache.incr('answer3')
  502. self.assertEqual(self.cache.get('answer3', version=1), 37)
  503. self.assertEqual(self.cache.get('answer3', version=2), 43)
  504. self.v2_cache.decr('answer3')
  505. self.assertEqual(self.cache.get('answer3', version=1), 37)
  506. self.assertEqual(self.cache.get('answer3', version=2), 42)
  507. self.cache.set('answer4', 37, version=1)
  508. self.cache.set('answer4', 42, version=2)
  509. self.v2_cache.incr('answer4', version=1)
  510. self.assertEqual(self.cache.get('answer4', version=1), 38)
  511. self.assertEqual(self.cache.get('answer4', version=2), 42)
  512. self.v2_cache.decr('answer4', version=1)
  513. self.assertEqual(self.cache.get('answer4', version=1), 37)
  514. self.assertEqual(self.cache.get('answer4', version=2), 42)
  515. def test_cache_versioning_get_set_many(self):
  516. # set, using default version = 1
  517. self.cache.set_many({'ford1': 37, 'arthur1': 42})
  518. self.assertEqual(self.cache.get_many(['ford1','arthur1']),
  519. {'ford1': 37, 'arthur1': 42})
  520. self.assertEqual(self.cache.get_many(['ford1','arthur1'], version=1),
  521. {'ford1': 37, 'arthur1': 42})
  522. self.assertEqual(self.cache.get_many(['ford1','arthur1'], version=2), {})
  523. self.assertEqual(self.v2_cache.get_many(['ford1','arthur1']), {})
  524. self.assertEqual(self.v2_cache.get_many(['ford1','arthur1'], version=1),
  525. {'ford1': 37, 'arthur1': 42})
  526. self.assertEqual(self.v2_cache.get_many(['ford1','arthur1'], version=2), {})
  527. # set, default version = 1, but manually override version = 2
  528. self.cache.set_many({'ford2': 37, 'arthur2': 42}, version=2)
  529. self.assertEqual(self.cache.get_many(['ford2','arthur2']), {})
  530. self.assertEqual(self.cache.get_many(['ford2','arthur2'], version=1), {})
  531. self.assertEqual(self.cache.get_many(['ford2','arthur2'], version=2),
  532. {'ford2': 37, 'arthur2': 42})
  533. self.assertEqual(self.v2_cache.get_many(['ford2','arthur2']),
  534. {'ford2': 37, 'arthur2': 42})
  535. self.assertEqual(self.v2_cache.get_many(['ford2','arthur2'], version=1), {})
  536. self.assertEqual(self.v2_cache.get_many(['ford2','arthur2'], version=2),
  537. {'ford2': 37, 'arthur2': 42})
  538. # v2 set, using default version = 2
  539. self.v2_cache.set_many({'ford3': 37, 'arthur3': 42})
  540. self.assertEqual(self.cache.get_many(['ford3','arthur3']), {})
  541. self.assertEqual(self.cache.get_many(['ford3','arthur3'], version=1), {})
  542. self.assertEqual(self.cache.get_many(['ford3','arthur3'], version=2),
  543. {'ford3': 37, 'arthur3': 42})
  544. self.assertEqual(self.v2_cache.get_many(['ford3','arthur3']),
  545. {'ford3': 37, 'arthur3': 42})
  546. self.assertEqual(self.v2_cache.get_many(['ford3','arthur3'], version=1), {})
  547. self.assertEqual(self.v2_cache.get_many(['ford3','arthur3'], version=2),
  548. {'ford3': 37, 'arthur3': 42})
  549. # v2 set, default version = 2, but manually override version = 1
  550. self.v2_cache.set_many({'ford4': 37, 'arthur4': 42}, version=1)
  551. self.assertEqual(self.cache.get_many(['ford4','arthur4']),
  552. {'ford4': 37, 'arthur4': 42})
  553. self.assertEqual(self.cache.get_many(['ford4','arthur4'], version=1),
  554. {'ford4': 37, 'arthur4': 42})
  555. self.assertEqual(self.cache.get_many(['ford4','arthur4'], version=2), {})
  556. self.assertEqual(self.v2_cache.get_many(['ford4','arthur4']), {})
  557. self.assertEqual(self.v2_cache.get_many(['ford4','arthur4'], version=1),
  558. {'ford4': 37, 'arthur4': 42})
  559. self.assertEqual(self.v2_cache.get_many(['ford4','arthur4'], version=2), {})
  560. def test_incr_version(self):
  561. self.cache.set('answer', 42, version=2)
  562. self.assertEqual(self.cache.get('answer'), None)
  563. self.assertEqual(self.cache.get('answer', version=1), None)
  564. self.assertEqual(self.cache.get('answer', version=2), 42)
  565. self.assertEqual(self.cache.get('answer', version=3), None)
  566. self.assertEqual(self.cache.incr_version('answer', version=2), 3)
  567. self.assertEqual(self.cache.get('answer'), None)
  568. self.assertEqual(self.cache.get('answer', version=1), None)
  569. self.assertEqual(self.cache.get('answer', version=2), None)
  570. self.assertEqual(self.cache.get('answer', version=3), 42)
  571. self.v2_cache.set('answer2', 42)
  572. self.assertEqual(self.v2_cache.get('answer2'), 42)
  573. self.assertEqual(self.v2_cache.get('answer2', version=1), None)
  574. self.assertEqual(self.v2_cache.get('answer2', version=2), 42)
  575. self.assertEqual(self.v2_cache.get('answer2', version=3), None)
  576. self.assertEqual(self.v2_cache.incr_version('answer2'), 3)
  577. self.assertEqual(self.v2_cache.get('answer2'), None)
  578. self.assertEqual(self.v2_cache.get('answer2', version=1), None)
  579. self.assertEqual(self.v2_cache.get('answer2', version=2), None)
  580. self.assertEqual(self.v2_cache.get('answer2', version=3), 42)
  581. self.assertRaises(ValueError, self.cache.incr_version, 'does_not_exist')
  582. def test_decr_version(self):
  583. self.cache.set('answer', 42, version=2)
  584. self.assertEqual(self.cache.get('answer'), None)
  585. self.assertEqual(self.cache.get('answer', version=1), None)
  586. self.assertEqual(self.cache.get('answer', version=2), 42)
  587. self.assertEqual(self.cache.decr_version('answer', version=2), 1)
  588. self.assertEqual(self.cache.get('answer'), 42)
  589. self.assertEqual(self.cache.get('answer', version=1), 42)
  590. self.assertEqual(self.cache.get('answer', version=2), None)
  591. self.v2_cache.set('answer2', 42)
  592. self.assertEqual(self.v2_cache.get('answer2'), 42)
  593. self.assertEqual(self.v2_cache.get('answer2', version=1), None)
  594. self.assertEqual(self.v2_cache.get('answer2', version=2), 42)
  595. self.assertEqual(self.v2_cache.decr_version('answer2'), 1)
  596. self.assertEqual(self.v2_cache.get('answer2'), None)
  597. self.assertEqual(self.v2_cache.get('answer2', version=1), 42)
  598. self.assertEqual(self.v2_cache.get('answer2', version=2), None)
  599. self.assertRaises(ValueError, self.cache.decr_version, 'does_not_exist', version=2)
  600. def test_custom_key_func(self):
  601. # Two caches with different key functions aren't visible to each other
  602. self.cache.set('answer1', 42)
  603. self.assertEqual(self.cache.get('answer1'), 42)
  604. self.assertEqual(self.custom_key_cache.get('answer1'), None)
  605. self.assertEqual(self.custom_key_cache2.get('answer1'), None)
  606. self.custom_key_cache.set('answer2', 42)
  607. self.assertEqual(self.cache.get('answer2'), None)
  608. self.assertEqual(self.custom_key_cache.get('answer2'), 42)
  609. self.assertEqual(self.custom_key_cache2.get('answer2'), 42)
  610. def custom_key_func(key, key_prefix, version):
  611. "A customized cache key function"
  612. return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
  613. class DBCacheTests(unittest.TestCase, BaseCacheTests):
  614. def setUp(self):
  615. # Spaces are used in the table name to ensure quoting/escaping is working
  616. self._table_name = 'test cache table'
  617. management.call_command('createcachetable', self._table_name, verbosity=0, interactive=False)
  618. self.cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, OPTIONS={'MAX_ENTRIES': 30})
  619. self.prefix_cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, KEY_PREFIX='cacheprefix')
  620. self.v2_cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, VERSION=2)
  621. self.custom_key_cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, KEY_FUNCTION=custom_key_func)
  622. self.custom_key_cache2 = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func')
  623. def tearDown(self):
  624. from django.db import connection
  625. cursor = connection.cursor()
  626. cursor.execute('DROP TABLE %s' % connection.ops.quote_name(self._table_name))
  627. def test_cull(self):
  628. self.perform_cull_test(50, 29)
  629. def test_zero_cull(self):
  630. self.cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, OPTIONS={'MAX_ENTRIES': 30, 'CULL_FREQUENCY': 0})
  631. self.perform_cull_test(50, 18)
  632. def test_old_initialization(self):
  633. self.cache = get_cache('db://%s?max_entries=30&cull_frequency=0' % self._table_name)
  634. self.perform_cull_test(50, 18)
  635. class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
  636. def setUp(self):
  637. self.cache = get_cache('django.core.cache.backends.locmem.LocMemCache', OPTIONS={'MAX_ENTRIES': 30})
  638. self.prefix_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', KEY_PREFIX='cacheprefix')
  639. self.v2_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', VERSION=2)
  640. self.custom_key_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', OPTIONS={'MAX_ENTRIES': 30}, KEY_FUNCTION=custom_key_func)
  641. self.custom_key_cache2 = get_cache('django.core.cache.backends.locmem.LocMemCache', OPTIONS={'MAX_ENTRIES': 30}, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func')
  642. # LocMem requires a hack to make the other caches
  643. # share a data store with the 'normal' cache.
  644. self.prefix_cache._cache = self.cache._cache
  645. self.prefix_cache._expire_info = self.cache._expire_info
  646. self.v2_cache._cache = self.cache._cache
  647. self.v2_cache._expire_info = self.cache._expire_info
  648. self.custom_key_cache._cache = self.cache._cache
  649. self.custom_key_cache._expire_info = self.cache._expire_info
  650. self.custom_key_cache2._cache = self.cache._cache
  651. self.custom_key_cache2._expire_info = self.cache._expire_info
  652. def tearDown(self):
  653. self.cache.clear()
  654. def test_cull(self):
  655. self.perform_cull_test(50, 29)
  656. def test_zero_cull(self):
  657. self.cache = get_cache('django.core.cache.backends.locmem.LocMemCache', OPTIONS={'MAX_ENTRIES': 30, 'CULL_FREQUENCY': 0})
  658. self.perform_cull_test(50, 19)
  659. def test_old_initialization(self):
  660. self.cache = get_cache('locmem://?max_entries=30&cull_frequency=0')
  661. self.perform_cull_test(50, 19)
  662. def test_multiple_caches(self):
  663. "Check that multiple locmem caches are isolated"
  664. mirror_cache = get_cache('django.core.cache.backends.locmem.LocMemCache')
  665. other_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', LOCATION='other')
  666. self.cache.set('value1', 42)
  667. self.assertEqual(mirror_cache.get('value1'), 42)
  668. self.assertEqual(other_cache.get('value1'), None)
  669. # memcached backend isn't guaranteed to be available.
  670. # To check the memcached backend, the test settings file will
  671. # need to contain a cache backend setting that points at
  672. # your memcache server.
  673. class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
  674. def setUp(self):
  675. name = settings.CACHES[DEFAULT_CACHE_ALIAS]['LOCATION']
  676. self.cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name)
  677. self.prefix_cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name, KEY_PREFIX='cacheprefix')
  678. self.v2_cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name, VERSION=2)
  679. self.custom_key_cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name, KEY_FUNCTION=custom_key_func)
  680. self.custom_key_cache2 = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func')
  681. def tearDown(self):
  682. self.cache.clear()
  683. def test_invalid_keys(self):
  684. """
  685. On memcached, we don't introduce a duplicate key validation
  686. step (for speed reasons), we just let the memcached API
  687. library raise its own exception on bad keys. Refs #6447.
  688. In order to be memcached-API-library agnostic, we only assert
  689. that a generic exception of some kind is raised.
  690. """
  691. # memcached does not allow whitespace or control characters in keys
  692. self.assertRaises(Exception, self.cache.set, 'key with spaces', 'value')
  693. # memcached limits key length to 250
  694. self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value')
  695. MemcachedCacheTests = unittest.skipUnless(settings.CACHES[DEFAULT_CACHE_ALIAS]['BACKEND'].startswith('django.core.cache.backends.memcached.'), "memcached not available")(MemcachedCacheTests)
  696. class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
  697. """
  698. Specific test cases for the file-based cache.
  699. """
  700. def setUp(self):
  701. self.dirname = tempfile.mkdtemp()
  702. self.cache = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, OPTIONS={'MAX_ENTRIES': 30})
  703. self.prefix_cache = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, KEY_PREFIX='cacheprefix')
  704. self.v2_cache = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, VERSION=2)
  705. self.custom_key_cache = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, KEY_FUNCTION=custom_key_func)
  706. self.custom_key_cache2 = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func')
  707. def tearDown(self):
  708. self.cache.clear()
  709. def test_hashing(self):
  710. """Test that keys are hashed into subdirectories correctly"""
  711. self.cache.set("foo", "bar")
  712. key = self.cache.make_key("foo")
  713. keyhash = md5_constructor(key).hexdigest()
  714. keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
  715. self.assertTrue(os.path.exists(keypath))
  716. def test_subdirectory_removal(self):
  717. """
  718. Make sure that the created subdirectories are correctly removed when empty.
  719. """
  720. self.cache.set("foo", "bar")
  721. key = self.cache.make_key("foo")
  722. keyhash = md5_constructor(key).hexdigest()
  723. keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
  724. self.assertTrue(os.path.exists(keypath))
  725. self.cache.delete("foo")
  726. self.assertTrue(not os.path.exists(keypath))
  727. self.assertTrue(not os.path.exists(os.path.dirname(keypath)))
  728. self.assertTrue(not os.path.exists(os.path.dirname(os.path.dirname(keypath))))
  729. def test_cull(self):
  730. self.perform_cull_test(50, 29)
  731. def test_old_initialization(self):
  732. self.cache = get_cache('file://%s?max_entries=30' % self.dirname)
  733. self.perform_cull_test(50, 29)
  734. class CustomCacheKeyValidationTests(unittest.TestCase):
  735. """
  736. Tests for the ability to mixin a custom ``validate_key`` method to
  737. a custom cache backend that otherwise inherits from a builtin
  738. backend, and override the default key validation. Refs #6447.
  739. """
  740. def test_custom_key_validation(self):
  741. cache = get_cache('regressiontests.cache.liberal_backend://')
  742. # this key is both longer than 250 characters, and has spaces
  743. key = 'some key with spaces' * 15
  744. val = 'a value'
  745. cache.set(key, val)
  746. self.assertEqual(cache.get(key), val)
  747. class CacheUtils(unittest.TestCase):
  748. """TestCase for django.utils.cache functions."""
  749. def setUp(self):
  750. self.path = '/cache/test/'
  751. self.old_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  752. self.old_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
  753. self.orig_use_i18n = settings.USE_I18N
  754. settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
  755. settings.CACHE_MIDDLEWARE_SECONDS = 1
  756. settings.USE_I18N = False
  757. def tearDown(self):
  758. settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.old_cache_middleware_key_prefix
  759. settings.CACHE_MIDDLEWARE_SECONDS = self.old_cache_middleware_seconds
  760. settings.USE_I18N = self.orig_use_i18n
  761. def _get_request(self, path, method='GET'):
  762. request = HttpRequest()
  763. request.META = {
  764. 'SERVER_NAME': 'testserver',
  765. 'SERVER_PORT': 80,
  766. }
  767. request.method = method
  768. request.path = request.path_info = "/cache/%s" % path
  769. return request
  770. def test_patch_vary_headers(self):
  771. headers = (
  772. # Initial vary, new headers, resulting vary.
  773. (None, ('Accept-Encoding',), 'Accept-Encoding'),
  774. ('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
  775. ('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
  776. ('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  777. ('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  778. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  779. (None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
  780. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  781. ('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  782. )
  783. for initial_vary, newheaders, resulting_vary in headers:
  784. response = HttpResponse()
  785. if initial_vary is not None:
  786. response['Vary'] = initial_vary
  787. patch_vary_headers(response, newheaders)
  788. self.assertEqual(response['Vary'], resulting_vary)
  789. def test_get_cache_key(self):
  790. request = self._get_request(self.path)
  791. response = HttpResponse()
  792. key_prefix = 'localprefix'
  793. # Expect None if no headers have been set yet.
  794. self.assertEqual(get_cache_key(request), None)
  795. # Set headers to an empty list.
  796. learn_cache_key(request, response)
  797. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  798. # Verify that a specified key_prefix is taken into account.
  799. learn_cache_key(request, response, key_prefix=key_prefix)
  800. self.assertEqual(get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  801. def test_get_cache_key_with_query(self):
  802. request = self._get_request(self.path + '?test=1')
  803. response = HttpResponse()
  804. # Expect None if no headers have been set yet.
  805. self.assertEqual(get_cache_key(request), None)
  806. # Set headers to an empty list.
  807. learn_cache_key(request, response)
  808. # Verify that the querystring is taken into account.
  809. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.bd889c5a59603af44333ed21504db3cd.d41d8cd98f00b204e9800998ecf8427e')
  810. def test_learn_cache_key(self):
  811. request = self._get_request(self.path, 'HEAD')
  812. response = HttpResponse()
  813. response['Vary'] = 'Pony'
  814. # Make sure that the Vary header is added to the key hash
  815. learn_cache_key(request, response)
  816. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.HEAD.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  817. def test_patch_cache_control(self):
  818. tests = (
  819. # Initial Cache-Control, kwargs to patch_cache_control, expected Cache-Control parts
  820. (None, {'private' : True}, set(['private'])),
  821. # Test whether private/public attributes are mutually exclusive
  822. ('private', {'private' : True}, set(['private'])),
  823. ('private', {'public' : True}, set(['public'])),
  824. ('public', {'public' : True}, set(['public'])),
  825. ('public', {'private' : True}, set(['private'])),
  826. ('must-revalidate,max-age=60,private', {'public' : True}, set(['must-revalidate', 'max-age=60', 'public'])),
  827. ('must-revalidate,max-age=60,public', {'private' : True}, set(['must-revalidate', 'max-age=60', 'private'])),
  828. ('must-revalidate,max-age=60', {'public' : True}, set(['must-revalidate', 'max-age=60', 'public'])),
  829. )
  830. cc_delim_re = re.compile(r'\s*,\s*')
  831. for initial_cc, newheaders, expected_cc in tests:
  832. response = HttpResponse()
  833. if initial_cc is not None:
  834. response['Cache-Control'] = initial_cc
  835. patch_cache_control(response, **newheaders)
  836. parts = set(cc_delim_re.split(response['Cache-Control']))
  837. self.assertEqual(parts, expected_cc)
  838. class PrefixedCacheUtils(CacheUtils):
  839. def setUp(self):
  840. super(PrefixedCacheUtils, self).setUp()
  841. self.old_cache_key_prefix = settings.CACHES['default'].get('KEY_PREFIX', None)
  842. settings.CACHES['default']['KEY_PREFIX'] = 'cacheprefix'
  843. def tearDown(self):
  844. super(PrefixedCacheUtils, self).tearDown()
  845. if self.old_cache_key_prefix is None:
  846. del settings.CACHES['default']['KEY_PREFIX']
  847. else:
  848. settings.CACHES['default']['KEY_PREFIX'] = self.old_cache_key_prefix
  849. class CacheHEADTest(unittest.TestCase):
  850. def setUp(self):
  851. self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
  852. self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  853. self.orig_caches = settings.CACHES
  854. settings.CACHE_MIDDLEWARE_SECONDS = 60
  855. settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'test'
  856. settings.CACHES = {
  857. 'default': {
  858. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
  859. }
  860. }
  861. self.path = '/cache/test/'
  862. def tearDown(self):
  863. settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds
  864. settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix
  865. settings.CACHES = self.orig_caches
  866. def _get_request(self, method):
  867. request = HttpRequest()
  868. request.META = {
  869. 'SERVER_NAME': 'testserver',
  870. 'SERVER_PORT': 80,
  871. }
  872. request.method = method
  873. request.path = request.path_info = self.path
  874. return request
  875. def _get_request_cache(self, method):
  876. request = self._get_request(method)
  877. request._cache_update_cache = True
  878. return request
  879. def _set_cache(self, request, msg):
  880. response = HttpResponse()
  881. response.content = msg
  882. return UpdateCacheMiddleware().process_response(request, response)
  883. def test_head_caches_correctly(self):
  884. test_content = 'test content'
  885. request = self._get_request_cache('HEAD')
  886. self._set_cache(request, test_content)
  887. request = self._get_request('HEAD')
  888. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  889. self.assertNotEqual(get_cache_data, None)
  890. self.assertEqual(test_content, get_cache_data.content)
  891. def test_head_with_cached_get(self):
  892. test_content = 'test content'
  893. request = self._get_request_cache('GET')
  894. self._set_cache(request, test_content)
  895. request = self._get_request('HEAD')
  896. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  897. self.assertNotEqual(get_cache_data, None)
  898. self.assertEqual(test_content, get_cache_data.content)
  899. class CacheI18nTest(unittest.TestCase):
  900. def setUp(self):
  901. self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
  902. self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  903. self.orig_caches = settings.CACHES
  904. self.orig_use_i18n = settings.USE_I18N
  905. self.orig_languages = settings.LANGUAGES
  906. settings.LANGUAGES = (
  907. ('en', 'English'),
  908. ('es', 'Spanish'),
  909. )
  910. settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
  911. self.path = '/cache/test/'
  912. def tearDown(self):
  913. settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds
  914. settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix
  915. settings.CACHES = self.orig_caches

Large files files are truncated, but you can click here to view the full file