tests.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812
  1. # -*- coding: utf-8 -*-
  2. # Unit tests for cache framework
  3. # Uses whatever cache backend is set in the test settings file.
  4. from __future__ import absolute_import, unicode_literals
  5. import hashlib
  6. import os
  7. import random
  8. import re
  9. import string
  10. import tempfile
  11. import time
  12. import warnings
  13. from django.conf import settings
  14. from django.core import management
  15. from django.core.cache import get_cache
  16. from django.core.cache.backends.base import (CacheKeyWarning,
  17. InvalidCacheBackendError)
  18. from django.db import router
  19. from django.http import (HttpResponse, HttpRequest, StreamingHttpResponse,
  20. QueryDict)
  21. from django.middleware.cache import (FetchFromCacheMiddleware,
  22. UpdateCacheMiddleware, CacheMiddleware)
  23. from django.template import Template
  24. from django.template.response import TemplateResponse
  25. from django.test import TestCase, TransactionTestCase, RequestFactory
  26. from django.test.utils import override_settings, six
  27. from django.utils import timezone, translation, unittest
  28. from django.utils.cache import (patch_vary_headers, get_cache_key,
  29. learn_cache_key, patch_cache_control, patch_response_headers)
  30. from django.utils.encoding import force_text
  31. from django.views.decorators.cache import cache_page
  32. from .models import Poll, expensive_calculation
  33. # functions/classes for complex data type tests
  34. def f():
  35. return 42
  36. class C:
  37. def m(n):
  38. return 24
  39. class DummyCacheTests(unittest.TestCase):
  40. # The Dummy cache backend doesn't really behave like a test backend,
  41. # so it has different test requirements.
  42. backend_name = 'django.core.cache.backends.dummy.DummyCache'
  43. def setUp(self):
  44. self.cache = get_cache(self.backend_name)
  45. def test_simple(self):
  46. "Dummy cache backend ignores cache set calls"
  47. self.cache.set("key", "value")
  48. self.assertEqual(self.cache.get("key"), None)
  49. def test_add(self):
  50. "Add doesn't do anything in dummy cache backend"
  51. self.cache.add("addkey1", "value")
  52. result = self.cache.add("addkey1", "newvalue")
  53. self.assertEqual(result, True)
  54. self.assertEqual(self.cache.get("addkey1"), None)
  55. def test_non_existent(self):
  56. "Non-existent keys aren't found in the dummy cache backend"
  57. self.assertEqual(self.cache.get("does_not_exist"), None)
  58. self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  59. def test_get_many(self):
  60. "get_many returns nothing for the dummy cache backend"
  61. self.cache.set('a', 'a')
  62. self.cache.set('b', 'b')
  63. self.cache.set('c', 'c')
  64. self.cache.set('d', 'd')
  65. self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {})
  66. self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {})
  67. def test_delete(self):
  68. "Cache deletion is transparently ignored on the dummy cache backend"
  69. self.cache.set("key1", "spam")
  70. self.cache.set("key2", "eggs")
  71. self.assertEqual(self.cache.get("key1"), None)
  72. self.cache.delete("key1")
  73. self.assertEqual(self.cache.get("key1"), None)
  74. self.assertEqual(self.cache.get("key2"), None)
  75. def test_has_key(self):
  76. "The has_key method doesn't ever return True for the dummy cache backend"
  77. self.cache.set("hello1", "goodbye1")
  78. self.assertEqual(self.cache.has_key("hello1"), False)
  79. self.assertEqual(self.cache.has_key("goodbye1"), False)
  80. def test_in(self):
  81. "The in operator doesn't ever return True for the dummy cache backend"
  82. self.cache.set("hello2", "goodbye2")
  83. self.assertEqual("hello2" in self.cache, False)
  84. self.assertEqual("goodbye2" in self.cache, False)
  85. def test_incr(self):
  86. "Dummy cache values can't be incremented"
  87. self.cache.set('answer', 42)
  88. self.assertRaises(ValueError, self.cache.incr, 'answer')
  89. self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
  90. def test_decr(self):
  91. "Dummy cache values can't be decremented"
  92. self.cache.set('answer', 42)
  93. self.assertRaises(ValueError, self.cache.decr, 'answer')
  94. self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
  95. def test_data_types(self):
  96. "All data types are ignored equally by the dummy cache"
  97. stuff = {
  98. 'string' : 'this is a string',
  99. 'int' : 42,
  100. 'list' : [1, 2, 3, 4],
  101. 'tuple' : (1, 2, 3, 4),
  102. 'dict' : {'A': 1, 'B' : 2},
  103. 'function' : f,
  104. 'class' : C,
  105. }
  106. self.cache.set("stuff", stuff)
  107. self.assertEqual(self.cache.get("stuff"), None)
  108. def test_expiration(self):
  109. "Expiration has no effect on the dummy cache"
  110. self.cache.set('expire1', 'very quickly', 1)
  111. self.cache.set('expire2', 'very quickly', 1)
  112. self.cache.set('expire3', 'very quickly', 1)
  113. time.sleep(2)
  114. self.assertEqual(self.cache.get("expire1"), None)
  115. self.cache.add("expire2", "newvalue")
  116. self.assertEqual(self.cache.get("expire2"), None)
  117. self.assertEqual(self.cache.has_key("expire3"), False)
  118. def test_unicode(self):
  119. "Unicode values are ignored by the dummy cache"
  120. stuff = {
  121. 'ascii': 'ascii_value',
  122. 'unicode_ascii': 'Iñtërnâtiônàlizætiøn1',
  123. 'Iñtërnâtiônàlizætiøn': 'Iñtërnâtiônàlizætiøn2',
  124. 'ascii2': {'x' : 1 }
  125. }
  126. for (key, value) in stuff.items():
  127. self.cache.set(key, value)
  128. self.assertEqual(self.cache.get(key), None)
  129. def test_set_many(self):
  130. "set_many does nothing for the dummy cache backend"
  131. self.cache.set_many({'a': 1, 'b': 2})
  132. self.cache.set_many({'a': 1, 'b': 2}, timeout=2, version='1')
  133. def test_delete_many(self):
  134. "delete_many does nothing for the dummy cache backend"
  135. self.cache.delete_many(['a', 'b'])
  136. def test_clear(self):
  137. "clear does nothing for the dummy cache backend"
  138. self.cache.clear()
  139. def test_incr_version(self):
  140. "Dummy cache versions can't be incremented"
  141. self.cache.set('answer', 42)
  142. self.assertRaises(ValueError, self.cache.incr_version, 'answer')
  143. self.assertRaises(ValueError, self.cache.incr_version, 'does_not_exist')
  144. def test_decr_version(self):
  145. "Dummy cache versions can't be decremented"
  146. self.cache.set('answer', 42)
  147. self.assertRaises(ValueError, self.cache.decr_version, 'answer')
  148. self.assertRaises(ValueError, self.cache.decr_version, 'does_not_exist')
  149. class BaseCacheTests(object):
  150. # A common set of tests to apply to all cache backends
  151. def _get_request_cache(self, path):
  152. request = HttpRequest()
  153. request.META = {
  154. 'SERVER_NAME': 'testserver',
  155. 'SERVER_PORT': 80,
  156. }
  157. request.path = request.path_info = path
  158. request._cache_update_cache = True
  159. request.method = 'GET'
  160. return request
  161. def test_simple(self):
  162. # Simple cache set/get works
  163. self.cache.set("key", "value")
  164. self.assertEqual(self.cache.get("key"), "value")
  165. def test_add(self):
  166. # A key can be added to a cache
  167. self.cache.add("addkey1", "value")
  168. result = self.cache.add("addkey1", "newvalue")
  169. self.assertEqual(result, False)
  170. self.assertEqual(self.cache.get("addkey1"), "value")
  171. def test_prefix(self):
  172. # Test for same cache key conflicts between shared backend
  173. self.cache.set('somekey', 'value')
  174. # should not be set in the prefixed cache
  175. self.assertFalse(self.prefix_cache.has_key('somekey'))
  176. self.prefix_cache.set('somekey', 'value2')
  177. self.assertEqual(self.cache.get('somekey'), 'value')
  178. self.assertEqual(self.prefix_cache.get('somekey'), 'value2')
  179. def test_non_existent(self):
  180. # Non-existent cache keys return as None/default
  181. # get with non-existent keys
  182. self.assertEqual(self.cache.get("does_not_exist"), None)
  183. self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  184. def test_get_many(self):
  185. # Multiple cache keys can be returned using get_many
  186. self.cache.set('a', 'a')
  187. self.cache.set('b', 'b')
  188. self.cache.set('c', 'c')
  189. self.cache.set('d', 'd')
  190. self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {'a' : 'a', 'c' : 'c', 'd' : 'd'})
  191. self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'})
  192. def test_delete(self):
  193. # Cache keys can be deleted
  194. self.cache.set("key1", "spam")
  195. self.cache.set("key2", "eggs")
  196. self.assertEqual(self.cache.get("key1"), "spam")
  197. self.cache.delete("key1")
  198. self.assertEqual(self.cache.get("key1"), None)
  199. self.assertEqual(self.cache.get("key2"), "eggs")
  200. def test_has_key(self):
  201. # The cache can be inspected for cache keys
  202. self.cache.set("hello1", "goodbye1")
  203. self.assertEqual(self.cache.has_key("hello1"), True)
  204. self.assertEqual(self.cache.has_key("goodbye1"), False)
  205. def test_in(self):
  206. # The in operator can be used to inspect cache contents
  207. self.cache.set("hello2", "goodbye2")
  208. self.assertEqual("hello2" in self.cache, True)
  209. self.assertEqual("goodbye2" in self.cache, False)
  210. def test_incr(self):
  211. # Cache values can be incremented
  212. self.cache.set('answer', 41)
  213. self.assertEqual(self.cache.incr('answer'), 42)
  214. self.assertEqual(self.cache.get('answer'), 42)
  215. self.assertEqual(self.cache.incr('answer', 10), 52)
  216. self.assertEqual(self.cache.get('answer'), 52)
  217. self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
  218. def test_decr(self):
  219. # Cache values can be decremented
  220. self.cache.set('answer', 43)
  221. self.assertEqual(self.cache.decr('answer'), 42)
  222. self.assertEqual(self.cache.get('answer'), 42)
  223. self.assertEqual(self.cache.decr('answer', 10), 32)
  224. self.assertEqual(self.cache.get('answer'), 32)
  225. self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
  226. def test_data_types(self):
  227. # Many different data types can be cached
  228. stuff = {
  229. 'string' : 'this is a string',
  230. 'int' : 42,
  231. 'list' : [1, 2, 3, 4],
  232. 'tuple' : (1, 2, 3, 4),
  233. 'dict' : {'A': 1, 'B' : 2},
  234. 'function' : f,
  235. 'class' : C,
  236. }
  237. self.cache.set("stuff", stuff)
  238. self.assertEqual(self.cache.get("stuff"), stuff)
  239. def test_cache_read_for_model_instance(self):
  240. # Don't want fields with callable as default to be called on cache read
  241. expensive_calculation.num_runs = 0
  242. Poll.objects.all().delete()
  243. my_poll = Poll.objects.create(question="Well?")
  244. self.assertEqual(Poll.objects.count(), 1)
  245. pub_date = my_poll.pub_date
  246. self.cache.set('question', my_poll)
  247. cached_poll = self.cache.get('question')
  248. self.assertEqual(cached_poll.pub_date, pub_date)
  249. # We only want the default expensive calculation run once
  250. self.assertEqual(expensive_calculation.num_runs, 1)
  251. def test_cache_write_for_model_instance_with_deferred(self):
  252. # Don't want fields with callable as default to be called on cache write
  253. expensive_calculation.num_runs = 0
  254. Poll.objects.all().delete()
  255. my_poll = Poll.objects.create(question="What?")
  256. self.assertEqual(expensive_calculation.num_runs, 1)
  257. defer_qs = Poll.objects.all().defer('question')
  258. self.assertEqual(defer_qs.count(), 1)
  259. self.assertEqual(expensive_calculation.num_runs, 1)
  260. self.cache.set('deferred_queryset', defer_qs)
  261. # cache set should not re-evaluate default functions
  262. self.assertEqual(expensive_calculation.num_runs, 1)
  263. def test_cache_read_for_model_instance_with_deferred(self):
  264. # Don't want fields with callable as default to be called on cache read
  265. expensive_calculation.num_runs = 0
  266. Poll.objects.all().delete()
  267. my_poll = Poll.objects.create(question="What?")
  268. self.assertEqual(expensive_calculation.num_runs, 1)
  269. defer_qs = Poll.objects.all().defer('question')
  270. self.assertEqual(defer_qs.count(), 1)
  271. self.cache.set('deferred_queryset', defer_qs)
  272. self.assertEqual(expensive_calculation.num_runs, 1)
  273. runs_before_cache_read = expensive_calculation.num_runs
  274. cached_polls = self.cache.get('deferred_queryset')
  275. # We only want the default expensive calculation run on creation and set
  276. self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read)
  277. def test_expiration(self):
  278. # Cache values can be set to expire
  279. self.cache.set('expire1', 'very quickly', 1)
  280. self.cache.set('expire2', 'very quickly', 1)
  281. self.cache.set('expire3', 'very quickly', 1)
  282. time.sleep(2)
  283. self.assertEqual(self.cache.get("expire1"), None)
  284. self.cache.add("expire2", "newvalue")
  285. self.assertEqual(self.cache.get("expire2"), "newvalue")
  286. self.assertEqual(self.cache.has_key("expire3"), False)
  287. def test_unicode(self):
  288. # Unicode values can be cached
  289. stuff = {
  290. 'ascii': 'ascii_value',
  291. 'unicode_ascii': 'Iñtërnâtiônàlizætiøn1',
  292. 'Iñtërnâtiônàlizætiøn': 'Iñtërnâtiônàlizætiøn2',
  293. 'ascii2': {'x' : 1 }
  294. }
  295. # Test `set`
  296. for (key, value) in stuff.items():
  297. self.cache.set(key, value)
  298. self.assertEqual(self.cache.get(key), value)
  299. # Test `add`
  300. for (key, value) in stuff.items():
  301. self.cache.delete(key)
  302. self.cache.add(key, value)
  303. self.assertEqual(self.cache.get(key), value)
  304. # Test `set_many`
  305. for (key, value) in stuff.items():
  306. self.cache.delete(key)
  307. self.cache.set_many(stuff)
  308. for (key, value) in stuff.items():
  309. self.assertEqual(self.cache.get(key), value)
  310. def test_binary_string(self):
  311. # Binary strings should be cacheable
  312. from zlib import compress, decompress
  313. value = 'value_to_be_compressed'
  314. compressed_value = compress(value.encode())
  315. # Test set
  316. self.cache.set('binary1', compressed_value)
  317. compressed_result = self.cache.get('binary1')
  318. self.assertEqual(compressed_value, compressed_result)
  319. self.assertEqual(value, decompress(compressed_result).decode())
  320. # Test add
  321. self.cache.add('binary1-add', compressed_value)
  322. compressed_result = self.cache.get('binary1-add')
  323. self.assertEqual(compressed_value, compressed_result)
  324. self.assertEqual(value, decompress(compressed_result).decode())
  325. # Test set_many
  326. self.cache.set_many({'binary1-set_many': compressed_value})
  327. compressed_result = self.cache.get('binary1-set_many')
  328. self.assertEqual(compressed_value, compressed_result)
  329. self.assertEqual(value, decompress(compressed_result).decode())
  330. def test_set_many(self):
  331. # Multiple keys can be set using set_many
  332. self.cache.set_many({"key1": "spam", "key2": "eggs"})
  333. self.assertEqual(self.cache.get("key1"), "spam")
  334. self.assertEqual(self.cache.get("key2"), "eggs")
  335. def test_set_many_expiration(self):
  336. # set_many takes a second ``timeout`` parameter
  337. self.cache.set_many({"key1": "spam", "key2": "eggs"}, 1)
  338. time.sleep(2)
  339. self.assertEqual(self.cache.get("key1"), None)
  340. self.assertEqual(self.cache.get("key2"), None)
  341. def test_delete_many(self):
  342. # Multiple keys can be deleted using delete_many
  343. self.cache.set("key1", "spam")
  344. self.cache.set("key2", "eggs")
  345. self.cache.set("key3", "ham")
  346. self.cache.delete_many(["key1", "key2"])
  347. self.assertEqual(self.cache.get("key1"), None)
  348. self.assertEqual(self.cache.get("key2"), None)
  349. self.assertEqual(self.cache.get("key3"), "ham")
  350. def test_clear(self):
  351. # The cache can be emptied using clear
  352. self.cache.set("key1", "spam")
  353. self.cache.set("key2", "eggs")
  354. self.cache.clear()
  355. self.assertEqual(self.cache.get("key1"), None)
  356. self.assertEqual(self.cache.get("key2"), None)
  357. def test_long_timeout(self):
  358. '''
  359. Using a timeout greater than 30 days makes memcached think
  360. it is an absolute expiration timestamp instead of a relative
  361. offset. Test that we honour this convention. Refs #12399.
  362. '''
  363. self.cache.set('key1', 'eggs', 60*60*24*30 + 1) #30 days + 1 second
  364. self.assertEqual(self.cache.get('key1'), 'eggs')
  365. self.cache.add('key2', 'ham', 60*60*24*30 + 1)
  366. self.assertEqual(self.cache.get('key2'), 'ham')
  367. self.cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, 60*60*24*30 + 1)
  368. self.assertEqual(self.cache.get('key3'), 'sausage')
  369. self.assertEqual(self.cache.get('key4'), 'lobster bisque')
  370. def test_float_timeout(self):
  371. # Make sure a timeout given as a float doesn't crash anything.
  372. self.cache.set("key1", "spam", 100.2)
  373. self.assertEqual(self.cache.get("key1"), "spam")
  374. def perform_cull_test(self, initial_count, final_count):
  375. """This is implemented as a utility method, because only some of the backends
  376. implement culling. The culling algorithm also varies slightly, so the final
  377. number of entries will vary between backends"""
  378. # Create initial cache key entries. This will overflow the cache, causing a cull
  379. for i in range(1, initial_count):
  380. self.cache.set('cull%d' % i, 'value', 1000)
  381. count = 0
  382. # Count how many keys are left in the cache.
  383. for i in range(1, initial_count):
  384. if self.cache.has_key('cull%d' % i):
  385. count = count + 1
  386. self.assertEqual(count, final_count)
  387. def test_invalid_keys(self):
  388. """
  389. All the builtin backends (except memcached, see below) should warn on
  390. keys that would be refused by memcached. This encourages portable
  391. caching code without making it too difficult to use production backends
  392. with more liberal key rules. Refs #6447.
  393. """
  394. # mimic custom ``make_key`` method being defined since the default will
  395. # never show the below warnings
  396. def func(key, *args):
  397. return key
  398. old_func = self.cache.key_func
  399. self.cache.key_func = func
  400. try:
  401. with warnings.catch_warnings(record=True) as w:
  402. warnings.simplefilter("always")
  403. # memcached does not allow whitespace or control characters in keys
  404. self.cache.set('key with spaces', 'value')
  405. self.assertEqual(len(w), 2)
  406. self.assertTrue(isinstance(w[0].message, CacheKeyWarning))
  407. with warnings.catch_warnings(record=True) as w:
  408. warnings.simplefilter("always")
  409. # memcached limits key length to 250
  410. self.cache.set('a' * 251, 'value')
  411. self.assertEqual(len(w), 1)
  412. self.assertTrue(isinstance(w[0].message, CacheKeyWarning))
  413. finally:
  414. self.cache.key_func = old_func
  415. def test_cache_versioning_get_set(self):
  416. # set, using default version = 1
  417. self.cache.set('answer1', 42)
  418. self.assertEqual(self.cache.get('answer1'), 42)
  419. self.assertEqual(self.cache.get('answer1', version=1), 42)
  420. self.assertEqual(self.cache.get('answer1', version=2), None)
  421. self.assertEqual(self.v2_cache.get('answer1'), None)
  422. self.assertEqual(self.v2_cache.get('answer1', version=1), 42)
  423. self.assertEqual(self.v2_cache.get('answer1', version=2), None)
  424. # set, default version = 1, but manually override version = 2
  425. self.cache.set('answer2', 42, version=2)
  426. self.assertEqual(self.cache.get('answer2'), None)
  427. self.assertEqual(self.cache.get('answer2', version=1), None)
  428. self.assertEqual(self.cache.get('answer2', version=2), 42)
  429. self.assertEqual(self.v2_cache.get('answer2'), 42)
  430. self.assertEqual(self.v2_cache.get('answer2', version=1), None)
  431. self.assertEqual(self.v2_cache.get('answer2', version=2), 42)
  432. # v2 set, using default version = 2
  433. self.v2_cache.set('answer3', 42)
  434. self.assertEqual(self.cache.get('answer3'), None)
  435. self.assertEqual(self.cache.get('answer3', version=1), None)
  436. self.assertEqual(self.cache.get('answer3', version=2), 42)
  437. self.assertEqual(self.v2_cache.get('answer3'), 42)
  438. self.assertEqual(self.v2_cache.get('answer3', version=1), None)
  439. self.assertEqual(self.v2_cache.get('answer3', version=2), 42)
  440. # v2 set, default version = 2, but manually override version = 1
  441. self.v2_cache.set('answer4', 42, version=1)
  442. self.assertEqual(self.cache.get('answer4'), 42)
  443. self.assertEqual(self.cache.get('answer4', version=1), 42)
  444. self.assertEqual(self.cache.get('answer4', version=2), None)
  445. self.assertEqual(self.v2_cache.get('answer4'), None)
  446. self.assertEqual(self.v2_cache.get('answer4', version=1), 42)
  447. self.assertEqual(self.v2_cache.get('answer4', version=2), None)
  448. def test_cache_versioning_add(self):
  449. # add, default version = 1, but manually override version = 2
  450. self.cache.add('answer1', 42, version=2)
  451. self.assertEqual(self.cache.get('answer1', version=1), None)
  452. self.assertEqual(self.cache.get('answer1', version=2), 42)
  453. self.cache.add('answer1', 37, version=2)
  454. self.assertEqual(self.cache.get('answer1', version=1), None)
  455. self.assertEqual(self.cache.get('answer1', version=2), 42)
  456. self.cache.add('answer1', 37, version=1)
  457. self.assertEqual(self.cache.get('answer1', version=1), 37)
  458. self.assertEqual(self.cache.get('answer1', version=2), 42)
  459. # v2 add, using default version = 2
  460. self.v2_cache.add('answer2', 42)
  461. self.assertEqual(self.cache.get('answer2', version=1), None)
  462. self.assertEqual(self.cache.get('answer2', version=2), 42)
  463. self.v2_cache.add('answer2', 37)
  464. self.assertEqual(self.cache.get('answer2', version=1), None)
  465. self.assertEqual(self.cache.get('answer2', version=2), 42)
  466. self.v2_cache.add('answer2', 37, version=1)
  467. self.assertEqual(self.cache.get('answer2', version=1), 37)
  468. self.assertEqual(self.cache.get('answer2', version=2), 42)
  469. # v2 add, default version = 2, but manually override version = 1
  470. self.v2_cache.add('answer3', 42, version=1)
  471. self.assertEqual(self.cache.get('answer3', version=1), 42)
  472. self.assertEqual(self.cache.get('answer3', version=2), None)
  473. self.v2_cache.add('answer3', 37, version=1)
  474. self.assertEqual(self.cache.get('answer3', version=1), 42)
  475. self.assertEqual(self.cache.get('answer3', version=2), None)
  476. self.v2_cache.add('answer3', 37)
  477. self.assertEqual(self.cache.get('answer3', version=1), 42)
  478. self.assertEqual(self.cache.get('answer3', version=2), 37)
  479. def test_cache_versioning_has_key(self):
  480. self.cache.set('answer1', 42)
  481. # has_key
  482. self.assertTrue(self.cache.has_key('answer1'))
  483. self.assertTrue(self.cache.has_key('answer1', version=1))
  484. self.assertFalse(self.cache.has_key('answer1', version=2))
  485. self.assertFalse(self.v2_cache.has_key('answer1'))
  486. self.assertTrue(self.v2_cache.has_key('answer1', version=1))
  487. self.assertFalse(self.v2_cache.has_key('answer1', version=2))
  488. def test_cache_versioning_delete(self):
  489. self.cache.set('answer1', 37, version=1)
  490. self.cache.set('answer1', 42, version=2)
  491. self.cache.delete('answer1')
  492. self.assertEqual(self.cache.get('answer1', version=1), None)
  493. self.assertEqual(self.cache.get('answer1', version=2), 42)
  494. self.cache.set('answer2', 37, version=1)
  495. self.cache.set('answer2', 42, version=2)
  496. self.cache.delete('answer2', version=2)
  497. self.assertEqual(self.cache.get('answer2', version=1), 37)
  498. self.assertEqual(self.cache.get('answer2', version=2), None)
  499. self.cache.set('answer3', 37, version=1)
  500. self.cache.set('answer3', 42, version=2)
  501. self.v2_cache.delete('answer3')
  502. self.assertEqual(self.cache.get('answer3', version=1), 37)
  503. self.assertEqual(self.cache.get('answer3', version=2), None)
  504. self.cache.set('answer4', 37, version=1)
  505. self.cache.set('answer4', 42, version=2)
  506. self.v2_cache.delete('answer4', version=1)
  507. self.assertEqual(self.cache.get('answer4', version=1), None)
  508. self.assertEqual(self.cache.get('answer4', version=2), 42)
  509. def test_cache_versioning_incr_decr(self):
  510. self.cache.set('answer1', 37, version=1)
  511. self.cache.set('answer1', 42, version=2)
  512. self.cache.incr('answer1')
  513. self.assertEqual(self.cache.get('answer1', version=1), 38)
  514. self.assertEqual(self.cache.get('answer1', version=2), 42)
  515. self.cache.decr('answer1')
  516. self.assertEqual(self.cache.get('answer1', version=1), 37)
  517. self.assertEqual(self.cache.get('answer1', version=2), 42)
  518. self.cache.set('answer2', 37, version=1)
  519. self.cache.set('answer2', 42, version=2)
  520. self.cache.incr('answer2', version=2)
  521. self.assertEqual(self.cache.get('answer2', version=1), 37)
  522. self.assertEqual(self.cache.get('answer2', version=2), 43)
  523. self.cache.decr('answer2', version=2)
  524. self.assertEqual(self.cache.get('answer2', version=1), 37)
  525. self.assertEqual(self.cache.get('answer2', version=2), 42)
  526. self.cache.set('answer3', 37, version=1)
  527. self.cache.set('answer3', 42, version=2)
  528. self.v2_cache.incr('answer3')
  529. self.assertEqual(self.cache.get('answer3', version=1), 37)
  530. self.assertEqual(self.cache.get('answer3', version=2), 43)
  531. self.v2_cache.decr('answer3')
  532. self.assertEqual(self.cache.get('answer3', version=1), 37)
  533. self.assertEqual(self.cache.get('answer3', version=2), 42)
  534. self.cache.set('answer4', 37, version=1)
  535. self.cache.set('answer4', 42, version=2)
  536. self.v2_cache.incr('answer4', version=1)
  537. self.assertEqual(self.cache.get('answer4', version=1), 38)
  538. self.assertEqual(self.cache.get('answer4', version=2), 42)
  539. self.v2_cache.decr('answer4', version=1)
  540. self.assertEqual(self.cache.get('answer4', version=1), 37)
  541. self.assertEqual(self.cache.get('answer4', version=2), 42)
  542. def test_cache_versioning_get_set_many(self):
  543. # set, using default version = 1
  544. self.cache.set_many({'ford1': 37, 'arthur1': 42})
  545. self.assertEqual(self.cache.get_many(['ford1','arthur1']),
  546. {'ford1': 37, 'arthur1': 42})
  547. self.assertEqual(self.cache.get_many(['ford1','arthur1'], version=1),
  548. {'ford1': 37, 'arthur1': 42})
  549. self.assertEqual(self.cache.get_many(['ford1','arthur1'], version=2), {})
  550. self.assertEqual(self.v2_cache.get_many(['ford1','arthur1']), {})
  551. self.assertEqual(self.v2_cache.get_many(['ford1','arthur1'], version=1),
  552. {'ford1': 37, 'arthur1': 42})
  553. self.assertEqual(self.v2_cache.get_many(['ford1','arthur1'], version=2), {})
  554. # set, default version = 1, but manually override version = 2
  555. self.cache.set_many({'ford2': 37, 'arthur2': 42}, version=2)
  556. self.assertEqual(self.cache.get_many(['ford2','arthur2']), {})
  557. self.assertEqual(self.cache.get_many(['ford2','arthur2'], version=1), {})
  558. self.assertEqual(self.cache.get_many(['ford2','arthur2'], version=2),
  559. {'ford2': 37, 'arthur2': 42})
  560. self.assertEqual(self.v2_cache.get_many(['ford2','arthur2']),
  561. {'ford2': 37, 'arthur2': 42})
  562. self.assertEqual(self.v2_cache.get_many(['ford2','arthur2'], version=1), {})
  563. self.assertEqual(self.v2_cache.get_many(['ford2','arthur2'], version=2),
  564. {'ford2': 37, 'arthur2': 42})
  565. # v2 set, using default version = 2
  566. self.v2_cache.set_many({'ford3': 37, 'arthur3': 42})
  567. self.assertEqual(self.cache.get_many(['ford3','arthur3']), {})
  568. self.assertEqual(self.cache.get_many(['ford3','arthur3'], version=1), {})
  569. self.assertEqual(self.cache.get_many(['ford3','arthur3'], version=2),
  570. {'ford3': 37, 'arthur3': 42})
  571. self.assertEqual(self.v2_cache.get_many(['ford3','arthur3']),
  572. {'ford3': 37, 'arthur3': 42})
  573. self.assertEqual(self.v2_cache.get_many(['ford3','arthur3'], version=1), {})
  574. self.assertEqual(self.v2_cache.get_many(['ford3','arthur3'], version=2),
  575. {'ford3': 37, 'arthur3': 42})
  576. # v2 set, default version = 2, but manually override version = 1
  577. self.v2_cache.set_many({'ford4': 37, 'arthur4': 42}, version=1)
  578. self.assertEqual(self.cache.get_many(['ford4','arthur4']),
  579. {'ford4': 37, 'arthur4': 42})
  580. self.assertEqual(self.cache.get_many(['ford4','arthur4'], version=1),
  581. {'ford4': 37, 'arthur4': 42})
  582. self.assertEqual(self.cache.get_many(['ford4','arthur4'], version=2), {})
  583. self.assertEqual(self.v2_cache.get_many(['ford4','arthur4']), {})
  584. self.assertEqual(self.v2_cache.get_many(['ford4','arthur4'], version=1),
  585. {'ford4': 37, 'arthur4': 42})
  586. self.assertEqual(self.v2_cache.get_many(['ford4','arthur4'], version=2), {})
  587. def test_incr_version(self):
  588. self.cache.set('answer', 42, version=2)
  589. self.assertEqual(self.cache.get('answer'), None)
  590. self.assertEqual(self.cache.get('answer', version=1), None)
  591. self.assertEqual(self.cache.get('answer', version=2), 42)
  592. self.assertEqual(self.cache.get('answer', version=3), None)
  593. self.assertEqual(self.cache.incr_version('answer', version=2), 3)
  594. self.assertEqual(self.cache.get('answer'), None)
  595. self.assertEqual(self.cache.get('answer', version=1), None)
  596. self.assertEqual(self.cache.get('answer', version=2), None)
  597. self.assertEqual(self.cache.get('answer', version=3), 42)
  598. self.v2_cache.set('answer2', 42)
  599. self.assertEqual(self.v2_cache.get('answer2'), 42)
  600. self.assertEqual(self.v2_cache.get('answer2', version=1), None)
  601. self.assertEqual(self.v2_cache.get('answer2', version=2), 42)
  602. self.assertEqual(self.v2_cache.get('answer2', version=3), None)
  603. self.assertEqual(self.v2_cache.incr_version('answer2'), 3)
  604. self.assertEqual(self.v2_cache.get('answer2'), None)
  605. self.assertEqual(self.v2_cache.get('answer2', version=1), None)
  606. self.assertEqual(self.v2_cache.get('answer2', version=2), None)
  607. self.assertEqual(self.v2_cache.get('answer2', version=3), 42)
  608. self.assertRaises(ValueError, self.cache.incr_version, 'does_not_exist')
  609. def test_decr_version(self):
  610. self.cache.set('answer', 42, version=2)
  611. self.assertEqual(self.cache.get('answer'), None)
  612. self.assertEqual(self.cache.get('answer', version=1), None)
  613. self.assertEqual(self.cache.get('answer', version=2), 42)
  614. self.assertEqual(self.cache.decr_version('answer', version=2), 1)
  615. self.assertEqual(self.cache.get('answer'), 42)
  616. self.assertEqual(self.cache.get('answer', version=1), 42)
  617. self.assertEqual(self.cache.get('answer', version=2), None)
  618. self.v2_cache.set('answer2', 42)
  619. self.assertEqual(self.v2_cache.get('answer2'), 42)
  620. self.assertEqual(self.v2_cache.get('answer2', version=1), None)
  621. self.assertEqual(self.v2_cache.get('answer2', version=2), 42)
  622. self.assertEqual(self.v2_cache.decr_version('answer2'), 1)
  623. self.assertEqual(self.v2_cache.get('answer2'), None)
  624. self.assertEqual(self.v2_cache.get('answer2', version=1), 42)
  625. self.assertEqual(self.v2_cache.get('answer2', version=2), None)
  626. self.assertRaises(ValueError, self.cache.decr_version, 'does_not_exist', version=2)
  627. def test_custom_key_func(self):
  628. # Two caches with different key functions aren't visible to each other
  629. self.cache.set('answer1', 42)
  630. self.assertEqual(self.cache.get('answer1'), 42)
  631. self.assertEqual(self.custom_key_cache.get('answer1'), None)
  632. self.assertEqual(self.custom_key_cache2.get('answer1'), None)
  633. self.custom_key_cache.set('answer2', 42)
  634. self.assertEqual(self.cache.get('answer2'), None)
  635. self.assertEqual(self.custom_key_cache.get('answer2'), 42)
  636. self.assertEqual(self.custom_key_cache2.get('answer2'), 42)
  637. def test_cache_write_unpickable_object(self):
  638. update_middleware = UpdateCacheMiddleware()
  639. update_middleware.cache = self.cache
  640. fetch_middleware = FetchFromCacheMiddleware()
  641. fetch_middleware.cache = self.cache
  642. request = self._get_request_cache('/cache/test')
  643. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  644. self.assertEqual(get_cache_data, None)
  645. response = HttpResponse()
  646. content = 'Testing cookie serialization.'
  647. response.content = content
  648. response.set_cookie('foo', 'bar')
  649. update_middleware.process_response(request, response)
  650. get_cache_data = fetch_middleware.process_request(request)
  651. self.assertNotEqual(get_cache_data, None)
  652. self.assertEqual(get_cache_data.content, content.encode('utf-8'))
  653. self.assertEqual(get_cache_data.cookies, response.cookies)
  654. update_middleware.process_response(request, get_cache_data)
  655. get_cache_data = fetch_middleware.process_request(request)
  656. self.assertNotEqual(get_cache_data, None)
  657. self.assertEqual(get_cache_data.content, content.encode('utf-8'))
  658. self.assertEqual(get_cache_data.cookies, response.cookies)
  659. def custom_key_func(key, key_prefix, version):
  660. "A customized cache key function"
  661. return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
  662. class DBCacheTests(BaseCacheTests, TransactionTestCase):
  663. backend_name = 'django.core.cache.backends.db.DatabaseCache'
  664. def setUp(self):
  665. # Spaces are used in the table name to ensure quoting/escaping is working
  666. self._table_name = 'test cache table'
  667. management.call_command('createcachetable', self._table_name, verbosity=0, interactive=False)
  668. self.cache = get_cache(self.backend_name, LOCATION=self._table_name, OPTIONS={'MAX_ENTRIES': 30})
  669. self.prefix_cache = get_cache(self.backend_name, LOCATION=self._table_name, KEY_PREFIX='cacheprefix')
  670. self.v2_cache = get_cache(self.backend_name, LOCATION=self._table_name, VERSION=2)
  671. self.custom_key_cache = get_cache(self.backend_name, LOCATION=self._table_name, KEY_FUNCTION=custom_key_func)
  672. self.custom_key_cache2 = get_cache(self.backend_name, LOCATION=self._table_name, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func')
  673. def tearDown(self):
  674. from django.db import connection
  675. cursor = connection.cursor()
  676. cursor.execute('DROP TABLE %s' % connection.ops.quote_name(self._table_name))
  677. connection.commit()
  678. def test_cull(self):
  679. self.perform_cull_test(50, 29)
  680. def test_zero_cull(self):
  681. self.cache = get_cache(self.backend_name, LOCATION=self._table_name, OPTIONS={'MAX_ENTRIES': 30, 'CULL_FREQUENCY': 0})
  682. self.perform_cull_test(50, 18)
  683. def test_old_initialization(self):
  684. self.cache = get_cache('db://%s?max_entries=30&cull_frequency=0' % self._table_name)
  685. self.perform_cull_test(50, 18)
  686. def test_second_call_doesnt_crash(self):
  687. with six.assertRaisesRegex(self, management.CommandError,
  688. "Cache table 'test cache table' could not be created"):
  689. management.call_command(
  690. 'createcachetable',
  691. self._table_name,
  692. verbosity=0,
  693. interactive=False
  694. )
  695. @override_settings(USE_TZ=True)
  696. class DBCacheWithTimeZoneTests(DBCacheTests):
  697. pass
  698. class DBCacheRouter(object):
  699. """A router that puts the cache table on the 'other' database."""
  700. def db_for_read(self, model, **hints):
  701. if model._meta.app_label == 'django_cache':
  702. return 'other'
  703. def db_for_write(self, model, **hints):
  704. if model._meta.app_label == 'django_cache':
  705. return 'other'
  706. def allow_syncdb(self, db, model):
  707. if model._meta.app_label == 'django_cache':
  708. return db == 'other'
  709. class CreateCacheTableForDBCacheTests(TestCase):
  710. multi_db = True
  711. def test_createcachetable_observes_database_router(self):
  712. old_routers = router.routers
  713. try:
  714. router.routers = [DBCacheRouter()]
  715. # cache table should not be created on 'default'
  716. with self.assertNumQueries(0, using='default'):
  717. management.call_command('createcachetable', 'cache_table',
  718. database='default',
  719. verbosity=0, interactive=False)
  720. # cache table should be created on 'other'
  721. # one query is used to create the table and another one the index
  722. with self.assertNumQueries(2, using='other'):
  723. management.call_command('createcachetable', 'cache_table',
  724. database='other',
  725. verbosity=0, interactive=False)
  726. finally:
  727. router.routers = old_routers
  728. class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
  729. backend_name = 'django.core.cache.backends.locmem.LocMemCache'
  730. def setUp(self):
  731. self.cache = get_cache(self.backend_name, OPTIONS={'MAX_ENTRIES': 30})
  732. self.prefix_cache = get_cache(self.backend_name, KEY_PREFIX='cacheprefix')
  733. self.v2_cache = get_cache(self.backend_name, VERSION=2)
  734. self.custom_key_cache = get_cache(self.backend_name, OPTIONS={'MAX_ENTRIES': 30}, KEY_FUNCTION=custom_key_func)
  735. self.custom_key_cache2 = get_cache(self.backend_name, OPTIONS={'MAX_ENTRIES': 30}, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func')
  736. # LocMem requires a hack to make the other caches
  737. # share a data store with the 'normal' cache.
  738. self.prefix_cache._cache = self.cache._cache
  739. self.prefix_cache._expire_info = self.cache._expire_info
  740. self.v2_cache._cache = self.cache._cache
  741. self.v2_cache._expire_info = self.cache._expire_info
  742. self.custom_key_cache._cache = self.cache._cache
  743. self.custom_key_cache._expire_info = self.cache._expire_info
  744. self.custom_key_cache2._cache = self.cache._cache
  745. self.custom_key_cache2._expire_info = self.cache._expire_info
  746. def tearDown(self):
  747. self.cache.clear()
  748. def test_cull(self):
  749. self.perform_cull_test(50, 29)
  750. def test_zero_cull(self):
  751. self.cache = get_cache(self.backend_name, OPTIONS={'MAX_ENTRIES': 30, 'CULL_FREQUENCY': 0})
  752. self.perform_cull_test(50, 19)
  753. def test_old_initialization(self):
  754. self.cache = get_cache('locmem://?max_entries=30&cull_frequency=0')
  755. self.perform_cull_test(50, 19)
  756. def test_multiple_caches(self):
  757. "Check that multiple locmem caches are isolated"
  758. mirror_cache = get_cache(self.backend_name)
  759. other_cache = get_cache(self.backend_name, LOCATION='other')
  760. self.cache.set('value1', 42)
  761. self.assertEqual(mirror_cache.get('value1'), 42)
  762. self.assertEqual(other_cache.get('value1'), None)
  763. def test_incr_decr_timeout(self):
  764. """incr/decr does not modify expiry time (matches memcached behavior)"""
  765. key = 'value'
  766. _key = self.cache.make_key(key)
  767. self.cache.set(key, 1, timeout=self.cache.default_timeout*10)
  768. expire = self.cache._expire_info[_key]
  769. self.cache.incr(key)
  770. self.assertEqual(expire, self.cache._expire_info[_key])
  771. self.cache.decr(key)
  772. self.assertEqual(expire, self.cache._expire_info[_key])
  773. # memcached backend isn't guaranteed to be available.
  774. # To check the memcached backend, the test settings file will
  775. # need to contain at least one cache backend setting that points at
  776. # your memcache server.
  777. @unittest.skipUnless(
  778. any(cache['BACKEND'].startswith('django.core.cache.backends.memcached.')
  779. for cache in settings.CACHES.values()),
  780. "memcached not available")
  781. class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
  782. def setUp(self):
  783. for cache_key, cache in settings.CACHES.items():
  784. if cache['BACKEND'].startswith('django.core.cache.backends.memcached.'):
  785. break
  786. random_prefix = ''.join(random.choice(string.ascii_letters) for x in range(10))
  787. self.cache = get_cache(cache_key)
  788. self.prefix_cache = get_cache(cache_key, KEY_PREFIX=random_prefix)
  789. self.v2_cache = get_cache(cache_key, VERSION=2)
  790. self.custom_key_cache = get_cache(cache_key, KEY_FUNCTION=custom_key_func)
  791. self.custom_key_cache2 = get_cache(cache_key, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func')
  792. def tearDown(self):
  793. self.cache.clear()
  794. def test_invalid_keys(self):
  795. """
  796. On memcached, we don't introduce a duplicate key validation
  797. step (for speed reasons), we just let the memcached API
  798. library raise its own exception on bad keys. Refs #6447.
  799. In order to be memcached-API-library agnostic, we only assert
  800. that a generic exception of some kind is raised.
  801. """
  802. # memcached does not allow whitespace or control characters in keys
  803. self.assertRaises(Exception, self.cache.set, 'key with spaces', 'value')
  804. # memcached limits key length to 250
  805. self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value')
  806. class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
  807. """
  808. Specific test cases for the file-based cache.
  809. """
  810. backend_name = 'django.core.cache.backends.filebased.FileBasedCache'
  811. def setUp(self):
  812. self.dirname = tempfile.mkdtemp()
  813. self.cache = get_cache(self.backend_name, LOCATION=self.dirname, OPTIONS={'MAX_ENTRIES': 30})
  814. self.prefix_cache = get_cache(self.backend_name, LOCATION=self.dirname, KEY_PREFIX='cacheprefix')
  815. self.v2_cache = get_cache(self.backend_name, LOCATION=self.dirname, VERSION=2)
  816. self.custom_key_cache = get_cache(self.backend_name, LOCATION=self.dirname, KEY_FUNCTION=custom_key_func)
  817. self.custom_key_cache2 = get_cache(self.backend_name, LOCATION=self.dirname, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func')
  818. def tearDown(self):
  819. self.cache.clear()
  820. def test_hashing(self):
  821. """Test that keys are hashed into subdirectories correctly"""
  822. self.cache.set("foo", "bar")
  823. key = self.cache.make_key("foo")
  824. keyhash = hashlib.md5(key.encode()).hexdigest()
  825. keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
  826. self.assertTrue(os.path.exists(keypath))
  827. def test_subdirectory_removal(self):
  828. """
  829. Make sure that the created subdirectories are correctly removed when empty.
  830. """
  831. self.cache.set("foo", "bar")
  832. key = self.cache.make_key("foo")
  833. keyhash = hashlib.md5(key.encode()).hexdigest()
  834. keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
  835. self.assertTrue(os.path.exists(keypath))
  836. self.cache.delete("foo")
  837. self.assertTrue(not os.path.exists(keypath))
  838. self.assertTrue(not os.path.exists(os.path.dirname(keypath)))
  839. self.assertTrue(not os.path.exists(os.path.dirname(os.path.dirname(keypath))))
  840. def test_cull(self):
  841. self.perform_cull_test(50, 29)
  842. def test_old_initialization(self):
  843. self.cache = get_cache('file://%s?max_entries=30' % self.dirname)
  844. self.perform_cull_test(50, 29)
  845. class CustomCacheKeyValidationTests(unittest.TestCase):
  846. """
  847. Tests for the ability to mixin a custom ``validate_key`` method to
  848. a custom cache backend that otherwise inherits from a builtin
  849. backend, and override the default key validation. Refs #6447.
  850. """
  851. def test_custom_key_validation(self):
  852. cache = get_cache('regressiontests.cache.liberal_backend://')
  853. # this key is both longer than 250 characters, and has spaces
  854. key = 'some key with spaces' * 15
  855. val = 'a value'
  856. cache.set(key, val)
  857. self.assertEqual(cache.get(key), val)
  858. class GetCacheTests(unittest.TestCase):
  859. def test_simple(self):
  860. cache = get_cache('locmem://')
  861. from django.core.cache.backends.locmem import LocMemCache
  862. self.assertTrue(isinstance(cache, LocMemCache))
  863. from django.core.cache import cache
  864. self.assertTrue(isinstance(cache, get_cache('default').__class__))
  865. cache = get_cache(
  866. 'django.core.cache.backends.dummy.DummyCache', **{'TIMEOUT': 120})
  867. self.assertEqual(cache.default_timeout, 120)
  868. self.assertRaises(InvalidCacheBackendError, get_cache, 'does_not_exist')
  869. def test_close(self):
  870. from django.core import signals
  871. cache = get_cache('regressiontests.cache.closeable_cache.CacheClass')
  872. self.assertFalse(cache.closed)
  873. signals.request_finished.send(self.__class__)
  874. self.assertTrue(cache.closed)
  875. @override_settings(
  876. CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
  877. CACHE_MIDDLEWARE_SECONDS=1,
  878. CACHES={
  879. 'default': {
  880. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  881. },
  882. },
  883. USE_I18N=False,
  884. )
  885. class CacheUtils(TestCase):
  886. """TestCase for django.utils.cache functions."""
  887. def setUp(self):
  888. self.path = '/cache/test/'
  889. self.cache = get_cache('default')
  890. def tearDown(self):
  891. self.cache.clear()
  892. def _get_request(self, path, method='GET'):
  893. request = HttpRequest()
  894. request.META = {
  895. 'SERVER_NAME': 'testserver',
  896. 'SERVER_PORT': 80,
  897. }
  898. request.method = method
  899. request.path = request.path_info = "/cache/%s" % path
  900. return request
  901. def test_patch_vary_headers(self):
  902. headers = (
  903. # Initial vary, new headers, resulting vary.
  904. (None, ('Accept-Encoding',), 'Accept-Encoding'),
  905. ('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
  906. ('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
  907. ('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  908. ('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  909. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  910. (None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
  911. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  912. ('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  913. )
  914. for initial_vary, newheaders, resulting_vary in headers:
  915. response = HttpResponse()
  916. if initial_vary is not None:
  917. response['Vary'] = initial_vary
  918. patch_vary_headers(response, newheaders)
  919. self.assertEqual(response['Vary'], resulting_vary)
  920. def test_get_cache_key(self):
  921. request = self._get_request(self.path)
  922. response = HttpResponse()
  923. key_prefix = 'localprefix'
  924. # Expect None if no headers have been set yet.
  925. self.assertEqual(get_cache_key(request), None)
  926. # Set headers to an empty list.
  927. learn_cache_key(request, response)
  928. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  929. # Verify that a specified key_prefix is taken into account.
  930. learn_cache_key(request, response, key_prefix=key_prefix)
  931. self.assertEqual(get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  932. def test_get_cache_key_with_query(self):
  933. request = self._get_request(self.path + '?test=1')
  934. response = HttpResponse()
  935. # Expect None if no headers have been set yet.
  936. self.assertEqual(get_cache_key(request), None)
  937. # Set headers to an empty list.
  938. learn_cache_key(request, response)
  939. # Verify that the querystring is taken into account.
  940. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.bd889c5a59603af44333ed21504db3cd.d41d8cd98f00b204e9800998ecf8427e')
  941. def test_learn_cache_key(self):
  942. request = self._get_request(self.path, 'HEAD')
  943. response = HttpResponse()
  944. response['Vary'] = 'Pony'
  945. # Make sure that the Vary header is added to the key hash
  946. learn_cache_key(request, response)
  947. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  948. def test_patch_cache_control(self):
  949. tests = (
  950. # Initial Cache-Control, kwargs to patch_cache_control, expected Cache-Control parts
  951. (None, {'private' : True}, set(['private'])),
  952. # Test whether private/public attributes are mutually exclusive
  953. ('private', {'private' : True}, set(['private'])),
  954. ('private', {'public' : True}, set(['public'])),
  955. ('public', {'public' : True}, set(['public'])),
  956. ('public', {'private' : True}, set(['private'])),
  957. ('must-revalidate,max-age=60,private', {'public' : True}, set(['must-revalidate', 'max-age=60', 'public'])),
  958. ('must-revalidate,max-age=60,public', {'private' : True}, set(['must-revalidate', 'max-age=60', 'private'])),
  959. ('must-revalidate,max-age=60', {'public' : True}, set(['must-revalidate', 'max-age=60', 'public'])),
  960. )
  961. cc_delim_re = re.compile(r'\s*,\s*')
  962. for initial_cc, newheaders, expected_cc in tests:
  963. response = HttpResponse()
  964. if initial_cc is not None:
  965. response['Cache-Control'] = initial_cc
  966. patch_cache_control(response, **newheaders)
  967. parts = set(cc_delim_re.split(response['Cache-Control']))
  968. self.assertEqual(parts, expected_cc)
  969. @override_settings(
  970. CACHES={
  971. 'default': {
  972. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  973. 'KEY_PREFIX': 'cacheprefix',
  974. },
  975. },
  976. )
  977. class PrefixedCacheUtils(CacheUtils):
  978. pass
  979. @override_settings(
  980. CACHE_MIDDLEWARE_SECONDS=60,
  981. CACHE_MIDDLEWARE_KEY_PREFIX='test',
  982. CACHES={
  983. 'default': {
  984. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  985. },
  986. },
  987. )
  988. class CacheHEADTest(TestCase):
  989. def setUp(self):
  990. self.path = '/cache/test/'
  991. self.cache = get_cache('default')
  992. def tearDown(self):
  993. self.cache.clear()
  994. def _get_request(self, method):
  995. request = HttpRequest()
  996. request.META = {
  997. 'SERVER_NAME': 'testserver',
  998. 'SERVER_PORT': 80,
  999. }
  1000. request.method = method
  1001. request.path = request.path_info = self.path
  1002. return request
  1003. def _get_request_cache(self, method):
  1004. request = self._get_request(method)
  1005. request._cache_update_cache = True
  1006. return request
  1007. def _set_cache(self, request, msg):
  1008. response = HttpResponse()
  1009. response.content = msg
  1010. return UpdateCacheMiddleware().process_response(request, response)
  1011. def test_head_caches_correctly(self):
  1012. test_content = 'test content'
  1013. request = self._get_request_cache('HEAD')
  1014. self._set_cache(request, test_content)
  1015. request = self._get_request('HEAD')
  1016. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1017. self.assertNotEqual(get_cache_data, None)
  1018. self.assertEqual(test_content.encode(), get_cache_data.content)
  1019. def test_head_with_cached_get(self):
  1020. test_content = 'test content'
  1021. request = self._get_request_cache('GET')
  1022. self._set_cache(request, test_content)
  1023. request = self._get_request('HEAD')
  1024. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1025. self.assertNotEqual(get_cache_data, None)
  1026. self.assertEqual(test_content.encode(), get_cache_data.content)
  1027. @override_settings(
  1028. CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
  1029. CACHES={
  1030. 'default': {
  1031. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  1032. },
  1033. },
  1034. LANGUAGES=(
  1035. ('en', 'English'),
  1036. ('es', 'Spanish'),
  1037. ),
  1038. )
  1039. class CacheI18nTest(TestCase):
  1040. def setUp(self):
  1041. self.path = '/cache/test/'
  1042. self.cache = get_cache('default')
  1043. def tearDown(self):
  1044. self.cache.clear()
  1045. def _get_request(self, method='GET'):
  1046. request = HttpRequest()
  1047. request.META = {
  1048. 'SERVER_NAME': 'testserver',
  1049. 'SERVER_PORT': 80,
  1050. }
  1051. request.method = method
  1052. request.path = request.path_info = self.path
  1053. return request
  1054. def _get_request_cache(self, query_string=None):
  1055. request = HttpRequest()
  1056. request.META = {
  1057. 'SERVER_NAME': 'testserver',
  1058. 'SERVER_PORT': 80,
  1059. }
  1060. if query_string:
  1061. request.META['QUERY_STRING'] = query_string
  1062. request.GET = QueryDict(query_string)
  1063. request.path = request.path_info = self.path
  1064. request._cache_update_cache = True
  1065. request.method = 'GET'
  1066. request.session = {}
  1067. return request
  1068. @override_settings(USE_I18N=True, USE_L10N=False, USE_TZ=False)
  1069. def test_cache_key_i18n_translation(self):
  1070. request = self._get_request()
  1071. lang = translation.get_language()
  1072. response = HttpResponse()
  1073. key = learn_cache_key(request, response)
  1074. self.assertIn(lang, key, "Cache keys should include the language name when translation is active")
  1075. key2 = get_cache_key(request)
  1076. self.assertEqual(key, key2)
  1077. @override_settings(USE_I18N=False, USE_L10N=True, USE_TZ=False)
  1078. def test_cache_key_i18n_formatting(self):
  1079. request = self._get_request()
  1080. lang = translation.get_language()
  1081. response = HttpResponse()
  1082. key = learn_cache_key(request, response)
  1083. self.assertIn(lang, key, "Cache keys should include the language name when formatting is active")
  1084. key2 = get_cache_key(request)
  1085. self.assertEqual(key, key2)
  1086. @override_settings(USE_I18N=False, USE_L10N=False, USE_TZ=True)
  1087. def test_cache_key_i18n_timezone(self):
  1088. request = self._get_request()
  1089. # This is tightly coupled to the implementation,
  1090. # but it's the most straightforward way to test the key.
  1091. tz = force_text(timezone.get_current_timezone_name(), errors='ignore')
  1092. tz = tz.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
  1093. response = HttpResponse()
  1094. key = learn_cache_key(request, response)
  1095. self.assertIn(tz, key, "Cache keys should include the time zone name when time zones are active")
  1096. key2 = get_cache_key(request)
  1097. self.assertEqual(key, key2)
  1098. @override_settings(USE_I18N=False, USE_L10N=False)
  1099. def test_cache_key_no_i18n (self):
  1100. request = self._get_request()
  1101. lang = translation.get_language()
  1102. tz = force_text(timezone.get_current_timezone_name(), errors='ignore')
  1103. tz = tz.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
  1104. response = HttpResponse()
  1105. key = learn_cache_key(request, response)
  1106. self.assertNotIn(lang, key, "Cache keys shouldn't include the language name when i18n isn't active")
  1107. self.assertNotIn(tz, key, "Cache keys shouldn't include the time zone name when i18n isn't active")
  1108. @override_settings(USE_I18N=False, USE_L10N=False, USE_TZ=True)
  1109. def test_cache_key_with_non_ascii_tzname(self):
  1110. # Regression test for #17476
  1111. class CustomTzName(timezone.UTC):
  1112. name = ''
  1113. def tzname(self, dt):
  1114. return self.name
  1115. request = self._get_request()
  1116. response = HttpResponse()
  1117. with timezone.override(CustomTzName()):
  1118. CustomTzName.name = 'Hora estándar de Argentina'.encode('UTF-8') # UTF-8 string
  1119. sanitized_name = 'Hora_estndar_de_Argentina'
  1120. self.assertIn(sanitized_name, learn_cache_key(request, response),
  1121. "Cache keys should include the time zone name when time zones are active")
  1122. CustomTzName.name = 'Hora estándar de Argentina' # unicode
  1123. sanitized_name = 'Hora_estndar_de_Argentina'
  1124. self.assertIn(sanitized_name, learn_cache_key(request, response),
  1125. "Cache keys should include the time zone name when time zones are active")
  1126. @override_settings(
  1127. CACHE_MIDDLEWARE_KEY_PREFIX="test",
  1128. CACHE_MIDDLEWARE_SECONDS=60,
  1129. USE_ETAGS=True,
  1130. USE_I18N=True,
  1131. )
  1132. def test_middleware(self):
  1133. def set_cache(request, lang, msg):
  1134. translation.activate(lang)
  1135. response = HttpResponse()
  1136. response.content = msg
  1137. return UpdateCacheMiddleware().process_response(request, response)
  1138. # cache with non empty request.GET
  1139. request = self._get_request_cache(query_string='foo=bar&other=true')
  1140. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1141. # first access, cache must return None
  1142. self.assertEqual(get_cache_data, None)
  1143. response = HttpResponse()
  1144. content = 'Check for cache with QUERY_STRING'
  1145. response.content = content
  1146. UpdateCacheMiddleware().process_response(request, response)
  1147. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1148. # cache must return content
  1149. self.assertNotEqual(get_cache_data, None)
  1150. self.assertEqual(get_cache_data.content, content.encode())
  1151. # different QUERY_STRING, cache must be empty
  1152. request = self._get_request_cache(query_string='foo=bar&somethingelse=true')
  1153. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1154. self.assertEqual(get_cache_data, None)
  1155. # i18n tests
  1156. en_message ="Hello world!"
  1157. es_message ="Hola mundo!"
  1158. request = self._get_request_cache()
  1159. set_cache(request, 'en', en_message)
  1160. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1161. # Check that we can recover the cache
  1162. self.assertNotEqual(get_cache_data, None)
  1163. self.assertEqual(get_cache_data.content, en_message.encode())
  1164. # Check that we use etags
  1165. self.assertTrue(get_cache_data.has_header('ETag'))
  1166. # Check that we can disable etags
  1167. with self.settings(USE_ETAGS=False):
  1168. request._cache_update_cache = True
  1169. set_cache(request, 'en', en_message)
  1170. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1171. self.assertFalse(get_cache_data.has_header('ETag'))
  1172. # change the session language and set content
  1173. request = self._get_request_cache()
  1174. set_cache(request, 'es', es_message)
  1175. # change again the language
  1176. translation.activate('en')
  1177. # retrieve the content from cache
  1178. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1179. self.assertEqual(get_cache_data.content, en_message.encode())
  1180. # change again the language
  1181. translation.activate('es')
  1182. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1183. self.assertEqual(get_cache_data.content, es_message.encode())
  1184. # reset the language
  1185. translation.deactivate()
  1186. @override_settings(
  1187. CACHE_MIDDLEWARE_KEY_PREFIX="test",
  1188. CACHE_MIDDLEWARE_SECONDS=60,
  1189. USE_ETAGS=True,
  1190. )
  1191. def test_middleware_with_streaming_response(self):
  1192. # cache with non empty request.GET
  1193. request = self._get_request_cache(query_string='foo=baz&other=true')
  1194. # first access, cache must return None
  1195. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1196. self.assertEqual(get_cache_data, None)
  1197. # pass streaming response through UpdateCacheMiddleware.
  1198. content = 'Check for cache with QUERY_STRING and streaming content'
  1199. response = StreamingHttpResponse(content)
  1200. UpdateCacheMiddleware().process_response(request, response)
  1201. # second access, cache must still return None, because we can't cache
  1202. # streaming response.
  1203. get_cache_data = FetchFromCacheMiddleware().process_request(request)
  1204. self.assertEqual(get_cache_data, None)
  1205. @override_settings(
  1206. CACHES={
  1207. 'default': {
  1208. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  1209. 'KEY_PREFIX': 'cacheprefix'
  1210. },
  1211. },
  1212. )
  1213. class PrefixedCacheI18nTest(CacheI18nTest):
  1214. pass
  1215. def hello_world_view(request, value):
  1216. return HttpResponse('Hello World %s' % value)
  1217. @override_settings(
  1218. CACHE_MIDDLEWARE_ALIAS='other',
  1219. CACHE_MIDDLEWARE_KEY_PREFIX='middlewareprefix',
  1220. CACHE_MIDDLEWARE_SECONDS=30,
  1221. CACHE_MIDDLEWARE_ANONYMOUS_ONLY=False,
  1222. CACHES={
  1223. 'default': {
  1224. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  1225. },
  1226. 'other': {
  1227. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  1228. 'LOCATION': 'other',
  1229. 'TIMEOUT': '1',
  1230. },
  1231. },
  1232. )
  1233. class CacheMiddlewareTest(TestCase):
  1234. # The following tests will need to be modified in Django 1.6 to not use
  1235. # deprecated ways of using the cache_page decorator that will be removed in
  1236. # such version
  1237. def setUp(self):
  1238. self.factory = RequestFactory()
  1239. self.default_cache = get_cache('default')
  1240. self.other_cache = get_cache('other')
  1241. self.save_warnings_state()
  1242. warnings.filterwarnings('ignore', category=DeprecationWarning,
  1243. module='django.views.decorators.cache')
  1244. def tearDown(self):
  1245. self.restore_warnings_state()
  1246. self.default_cache.clear()
  1247. self.other_cache.clear()
  1248. def test_constructor(self):
  1249. """
  1250. Ensure the constructor is correctly distinguishing between usage of CacheMiddleware as
  1251. Middleware vs. usage of CacheMiddleware as view decorator and setting attributes
  1252. appropriately.
  1253. """
  1254. # If no arguments are passed in construction, it's being used as middleware.
  1255. middleware = CacheMiddleware()
  1256. # Now test object attributes against values defined in setUp above
  1257. self.assertEqual(middleware.cache_timeout, 30)
  1258. self.assertEqual(middleware.key_prefix, 'middlewareprefix')
  1259. self.assertEqual(middleware.cache_alias, 'other')
  1260. self.assertEqual(middleware.cache_anonymous_only, False)
  1261. # If arguments are being passed in construction, it's being used as a decorator.
  1262. # First, test with "defaults":
  1263. as_view_decorator = CacheMiddleware(cache_alias=None, key_prefix=None)
  1264. self.assertEqual(as_view_decorator.cache_timeout, 300) # Timeout value for 'default' cache, i.e. 300
  1265. self.assertEqual(as_view_decorator.key_prefix, '')
  1266. self.assertEqual(as_view_decorator.cache_alias, 'default') # Value of DEFAULT_CACHE_ALIAS from django.core.cache
  1267. self.assertEqual(as_view_decorator.cache_anonymous_only, False)
  1268. # Next, test with custom values:
  1269. as_view_decorator_with_custom = CacheMiddleware(cache_anonymous_only=True, cache_timeout=60, cache_alias='other', key_prefix='foo')
  1270. self.assertEqual(as_view_decorator_with_custom.cache_timeout, 60)
  1271. self.assertEqual(as_view_decorator_with_custom.key_prefix, 'foo')
  1272. self.assertEqual(as_view_decorator_with_custom.cache_alias, 'other')
  1273. self.assertEqual(as_view_decorator_with_custom.cache_anonymous_only, True)
  1274. def test_middleware(self):
  1275. middleware = CacheMiddleware()
  1276. prefix_middleware = CacheMiddleware(key_prefix='prefix1')
  1277. timeout_middleware = CacheMiddleware(cache_timeout=1)
  1278. request = self.factory.get('/view/')
  1279. # Put the request through the request middleware
  1280. result = middleware.process_request(request)
  1281. self.assertEqual(result, None)
  1282. response = hello_world_view(request, '1')
  1283. # Now put the response through the response middleware
  1284. response = middleware.process_response(request, response)
  1285. # Repeating the request should result in a cache hit
  1286. result = middleware.process_request(request)
  1287. self.assertNotEqual(result, None)
  1288. self.assertEqual(result.content, b'Hello World 1')
  1289. # The same request through a different middleware won't hit
  1290. result = prefix_middleware.process_request(request)
  1291. self.assertEqual(result, None)
  1292. # The same request with a timeout _will_ hit
  1293. result = timeout_middleware.process_request(request)
  1294. self.assertNotEqual(result, None)
  1295. self.assertEqual(result.content, b'Hello World 1')
  1296. @override_settings(CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True)
  1297. def test_cache_middleware_anonymous_only_wont_cause_session_access(self):
  1298. """ The cache middleware shouldn't cause a session access due to
  1299. CACHE_MIDDLEWARE_ANONYMOUS_ONLY if nothing else has accessed the
  1300. session. Refs 13283 """
  1301. from django.contrib.sessions.middleware import SessionMiddleware
  1302. from django.contrib.auth.middleware import AuthenticationMiddleware
  1303. middleware = CacheMiddleware()
  1304. session_middleware = SessionMiddleware()
  1305. auth_middleware = AuthenticationMiddleware()
  1306. request = self.factory.get('/view_anon/')
  1307. # Put the request through the request middleware
  1308. session_middleware.process_request(request)
  1309. auth_middleware.process_request(request)
  1310. result = middleware.process_request(request)
  1311. self.assertEqual(result, None)
  1312. response = hello_world_view(request, '1')
  1313. # Now put the response through the response middleware
  1314. session_middleware.process_response(request, response)
  1315. response = middleware.process_response(request, response)
  1316. self.assertEqual(request.session.accessed, False)
  1317. @override_settings(CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True)
  1318. def test_cache_middleware_anonymous_only_with_cache_page(self):
  1319. """CACHE_MIDDLEWARE_ANONYMOUS_ONLY should still be effective when used
  1320. with the cache_page decorator: the response to a request from an
  1321. authenticated user should not be cached."""
  1322. request = self.factory.get('/view_anon/')
  1323. class MockAuthenticatedUser(object):
  1324. def is_authenticated(self):
  1325. return True
  1326. class MockAccessedSession(object):
  1327. accessed = True
  1328. request.user = MockAuthenticatedUser()
  1329. request.session = MockAccessedSession()
  1330. response = cache_page(hello_world_view)(request, '1')
  1331. self.assertFalse("Cache-Control" in response)
  1332. def test_view_decorator(self):
  1333. # decorate the same view with different cache decorators
  1334. default_view = cache_page(hello_world_view)
  1335. default_with_prefix_view = cache_page(key_prefix='prefix1')(hello_world_view)
  1336. explicit_default_view = cache_page(cache='default')(hello_world_view)
  1337. explicit_default_with_prefix_view = cache_page(cache='default', key_prefix='prefix1')(hello_world_view)
  1338. other_view = cache_page(cache='other')(hello_world_view)
  1339. other_with_prefix_view = cache_page(cache='other', key_prefix='prefix2')(hello_world_view)
  1340. other_with_timeout_view = cache_page(3, cache='other', key_prefix='prefix3')(hello_world_view)
  1341. request = self.factory.get('/view/')
  1342. # Request the view once
  1343. response = default_view(request, '1')
  1344. self.assertEqual(response.content, b'Hello World 1')
  1345. # Request again -- hit the cache
  1346. response = default_view(request, '2')
  1347. self.assertEqual(response.content, b'Hello World 1')
  1348. # Requesting the same view with the explicit cache should yield the same result
  1349. response = explicit_default_view(request, '3')
  1350. self.assertEqual(response.content, b'Hello World 1')
  1351. # Requesting with a prefix will hit a different cache key
  1352. response = explicit_default_with_prefix_view(request, '4')
  1353. self.assertEqual(response.content, b'Hello World 4')
  1354. # Hitting the same view again gives a cache hit
  1355. response = explicit_default_with_prefix_view(request, '5')
  1356. self.assertEqual(response.content, b'Hello World 4')
  1357. # And going back to the implicit cache will hit the same cache
  1358. response = default_with_prefix_view(request, '6')
  1359. self.assertEqual(response.content, b'Hello World 4')
  1360. # Requesting from an alternate cache won't hit cache
  1361. response = other_view(request, '7')
  1362. self.assertEqual(response.content, b'Hello World 7')
  1363. # But a repeated hit will hit cache
  1364. response = other_view(request, '8')
  1365. self.assertEqual(response.content, b'Hello World 7')
  1366. # And prefixing the alternate cache yields yet another cache entry
  1367. response = other_with_prefix_view(request, '9')
  1368. self.assertEqual(response.content, b'Hello World 9')
  1369. # Request from the alternate cache with a new prefix and a custom timeout
  1370. response = other_with_timeout_view(request, '10')
  1371. self.assertEqual(response.content, b'Hello World 10')
  1372. # But if we wait a couple of seconds...
  1373. time.sleep(2)
  1374. # ... the default cache will still hit
  1375. cache = get_cache('default')
  1376. response = default_view(request, '11')
  1377. self.assertEqual(response.content, b'Hello World 1')
  1378. # ... the default cache with a prefix will still hit
  1379. response = default_with_prefix_view(request, '12')
  1380. self.assertEqual(response.content, b'Hello World 4')
  1381. # ... the explicit default cache will still hit
  1382. response = explicit_default_view(request, '13')
  1383. self.assertEqual(response.content, b'Hello World 1')
  1384. # ... the explicit default cache with a prefix will still hit
  1385. response = explicit_default_with_prefix_view(request, '14')
  1386. self.assertEqual(response.content, b'Hello World 4')
  1387. # .. but a rapidly expiring cache won't hit
  1388. response = other_view(request, '15')
  1389. self.assertEqual(response.content, b'Hello World 15')
  1390. # .. even if it has a prefix
  1391. response = other_with_prefix_view(request, '16')
  1392. self.assertEqual(response.content, b'Hello World 16')
  1393. # ... but a view with a custom timeout will still hit
  1394. response = other_with_timeout_view(request, '17')
  1395. self.assertEqual(response.content, b'Hello World 10')
  1396. # And if we wait a few more seconds
  1397. time.sleep(2)
  1398. # the custom timeout cache will miss
  1399. response = other_with_timeout_view(request, '18')
  1400. self.assertEqual(response.content, b'Hello World 18')
  1401. @override_settings(
  1402. CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
  1403. CACHE_MIDDLEWARE_SECONDS=1,
  1404. CACHES={
  1405. 'default': {
  1406. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  1407. },
  1408. },
  1409. USE_I18N=False,
  1410. )
  1411. class TestWithTemplateResponse(TestCase):
  1412. """
  1413. Tests various headers w/ TemplateResponse.
  1414. Most are probably redundant since they manipulate the same object
  1415. anyway but the Etag header is 'special' because it relies on the
  1416. content being complete (which is not necessarily always the case
  1417. with a TemplateResponse)
  1418. """
  1419. def setUp(self):
  1420. self.path = '/cache/test/'
  1421. self.cache = get_cache('default')
  1422. def tearDown(self):
  1423. self.cache.clear()
  1424. def _get_request(self, path, method='GET'):
  1425. request = HttpRequest()
  1426. request.META = {
  1427. 'SERVER_NAME': 'testserver',
  1428. 'SERVER_PORT': 80,
  1429. }
  1430. request.method = method
  1431. request.path = request.path_info = "/cache/%s" % path
  1432. return request
  1433. def test_patch_vary_headers(self):
  1434. headers = (
  1435. # Initial vary, new headers, resulting vary.
  1436. (None, ('Accept-Encoding',), 'Accept-Encoding'),
  1437. ('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
  1438. ('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
  1439. ('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  1440. ('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  1441. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  1442. (None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
  1443. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  1444. ('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  1445. )
  1446. for initial_vary, newheaders, resulting_vary in headers:
  1447. response = TemplateResponse(HttpResponse(), Template("This is a test"))
  1448. if initial_vary is not None:
  1449. response['Vary'] = initial_vary
  1450. patch_vary_headers(response, newheaders)
  1451. self.assertEqual(response['Vary'], resulting_vary)
  1452. def test_get_cache_key(self):
  1453. request = self._get_request(self.path)
  1454. response = TemplateResponse(HttpResponse(), Template("This is a test"))
  1455. key_prefix = 'localprefix'
  1456. # Expect None if no headers have been set yet.
  1457. self.assertEqual(get_cache_key(request), None)
  1458. # Set headers to an empty list.
  1459. learn_cache_key(request, response)
  1460. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  1461. # Verify that a specified key_prefix is taken into account.
  1462. learn_cache_key(request, response, key_prefix=key_prefix)
  1463. self.assertEqual(get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  1464. def test_get_cache_key_with_query(self):
  1465. request = self._get_request(self.path + '?test=1')
  1466. response = TemplateResponse(HttpResponse(), Template("This is a test"))
  1467. # Expect None if no headers have been set yet.
  1468. self.assertEqual(get_cache_key(request), None)
  1469. # Set headers to an empty list.
  1470. learn_cache_key(request, response)
  1471. # Verify that the querystring is taken into account.
  1472. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.bd889c5a59603af44333ed21504db3cd.d41d8cd98f00b204e9800998ecf8427e')
  1473. @override_settings(USE_ETAGS=False)
  1474. def test_without_etag(self):
  1475. response = TemplateResponse(HttpResponse(), Template("This is a test"))
  1476. self.assertFalse(response.has_header('ETag'))
  1477. patch_response_headers(response)
  1478. self.assertFalse(response.has_header('ETag'))
  1479. response = response.render()
  1480. self.assertFalse(response.has_header('ETag'))
  1481. @override_settings(USE_ETAGS=True)
  1482. def test_with_etag(self):
  1483. response = TemplateResponse(HttpResponse(), Template("This is a test"))
  1484. self.assertFalse(response.has_header('ETag'))
  1485. patch_response_headers(response)
  1486. self.assertFalse(response.has_header('ETag'))
  1487. response = response.render()
  1488. self.assertTrue(response.has_header('ETag'))
  1489. class TestEtagWithAdmin(TestCase):
  1490. # See https://code.djangoproject.com/ticket/16003
  1491. urls = "regressiontests.admin_views.urls"
  1492. def test_admin(self):
  1493. with self.settings(USE_ETAGS=False):
  1494. response = self.client.get('/test_admin/admin/')
  1495. self.assertEqual(response.status_code, 200)
  1496. self.assertFalse(response.has_header('ETag'))
  1497. with self.settings(USE_ETAGS=True):
  1498. response = self.client.get('/test_admin/admin/')
  1499. self.assertEqual(response.status_code, 200)
  1500. self.assertTrue(response.has_header('ETag'))