2
0

tests.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. # -*- coding: utf-8 -*-
  2. # Unit tests for cache framework
  3. # Uses whatever cache backend is set in the test settings file.
  4. import os
  5. import shutil
  6. import tempfile
  7. import time
  8. import unittest
  9. from django.conf import settings
  10. from django.core import management
  11. from django.core.cache import get_cache
  12. from django.core.cache.backends.base import InvalidCacheBackendError
  13. from django.http import HttpResponse, HttpRequest
  14. from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key
  15. from django.utils.hashcompat import md5_constructor
  16. from regressiontests.cache.models import Poll, expensive_calculation
  17. # functions/classes for complex data type tests
  18. def f():
  19. return 42
  20. class C:
  21. def m(n):
  22. return 24
  23. class DummyCacheTests(unittest.TestCase):
  24. # The Dummy cache backend doesn't really behave like a test backend,
  25. # so it has different test requirements.
  26. def setUp(self):
  27. self.cache = get_cache('dummy://')
  28. def test_simple(self):
  29. "Dummy cache backend ignores cache set calls"
  30. self.cache.set("key", "value")
  31. self.assertEqual(self.cache.get("key"), None)
  32. def test_add(self):
  33. "Add doesn't do anything in dummy cache backend"
  34. self.cache.add("addkey1", "value")
  35. result = self.cache.add("addkey1", "newvalue")
  36. self.assertEqual(result, True)
  37. self.assertEqual(self.cache.get("addkey1"), None)
  38. def test_non_existent(self):
  39. "Non-existent keys aren't found in the dummy cache backend"
  40. self.assertEqual(self.cache.get("does_not_exist"), None)
  41. self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  42. def test_get_many(self):
  43. "get_many returns nothing for the dummy cache backend"
  44. self.cache.set('a', 'a')
  45. self.cache.set('b', 'b')
  46. self.cache.set('c', 'c')
  47. self.cache.set('d', 'd')
  48. self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {})
  49. self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {})
  50. def test_delete(self):
  51. "Cache deletion is transparently ignored on the dummy cache backend"
  52. self.cache.set("key1", "spam")
  53. self.cache.set("key2", "eggs")
  54. self.assertEqual(self.cache.get("key1"), None)
  55. self.cache.delete("key1")
  56. self.assertEqual(self.cache.get("key1"), None)
  57. self.assertEqual(self.cache.get("key2"), None)
  58. def test_has_key(self):
  59. "The has_key method doesn't ever return True for the dummy cache backend"
  60. self.cache.set("hello1", "goodbye1")
  61. self.assertEqual(self.cache.has_key("hello1"), False)
  62. self.assertEqual(self.cache.has_key("goodbye1"), False)
  63. def test_in(self):
  64. "The in operator doesn't ever return True for the dummy cache backend"
  65. self.cache.set("hello2", "goodbye2")
  66. self.assertEqual("hello2" in self.cache, False)
  67. self.assertEqual("goodbye2" in self.cache, False)
  68. def test_incr(self):
  69. "Dummy cache values can't be incremented"
  70. self.cache.set('answer', 42)
  71. self.assertRaises(ValueError, self.cache.incr, 'answer')
  72. self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
  73. def test_decr(self):
  74. "Dummy cache values can't be decremented"
  75. self.cache.set('answer', 42)
  76. self.assertRaises(ValueError, self.cache.decr, 'answer')
  77. self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
  78. def test_data_types(self):
  79. "All data types are ignored equally by the dummy cache"
  80. stuff = {
  81. 'string' : 'this is a string',
  82. 'int' : 42,
  83. 'list' : [1, 2, 3, 4],
  84. 'tuple' : (1, 2, 3, 4),
  85. 'dict' : {'A': 1, 'B' : 2},
  86. 'function' : f,
  87. 'class' : C,
  88. }
  89. self.cache.set("stuff", stuff)
  90. self.assertEqual(self.cache.get("stuff"), None)
  91. def test_expiration(self):
  92. "Expiration has no effect on the dummy cache"
  93. self.cache.set('expire1', 'very quickly', 1)
  94. self.cache.set('expire2', 'very quickly', 1)
  95. self.cache.set('expire3', 'very quickly', 1)
  96. time.sleep(2)
  97. self.assertEqual(self.cache.get("expire1"), None)
  98. self.cache.add("expire2", "newvalue")
  99. self.assertEqual(self.cache.get("expire2"), None)
  100. self.assertEqual(self.cache.has_key("expire3"), False)
  101. def test_unicode(self):
  102. "Unicode values are ignored by the dummy cache"
  103. stuff = {
  104. u'ascii': u'ascii_value',
  105. u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1',
  106. u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2',
  107. u'ascii': {u'x' : 1 }
  108. }
  109. for (key, value) in stuff.items():
  110. self.cache.set(key, value)
  111. self.assertEqual(self.cache.get(key), None)
  112. class BaseCacheTests(object):
  113. # A common set of tests to apply to all cache backends
  114. def test_simple(self):
  115. # Simple cache set/get works
  116. self.cache.set("key", "value")
  117. self.assertEqual(self.cache.get("key"), "value")
  118. def test_add(self):
  119. # A key can be added to a cache
  120. self.cache.add("addkey1", "value")
  121. result = self.cache.add("addkey1", "newvalue")
  122. self.assertEqual(result, False)
  123. self.assertEqual(self.cache.get("addkey1"), "value")
  124. def test_non_existent(self):
  125. # Non-existent cache keys return as None/default
  126. # get with non-existent keys
  127. self.assertEqual(self.cache.get("does_not_exist"), None)
  128. self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!")
  129. def test_get_many(self):
  130. # Multiple cache keys can be returned using get_many
  131. self.cache.set('a', 'a')
  132. self.cache.set('b', 'b')
  133. self.cache.set('c', 'c')
  134. self.cache.set('d', 'd')
  135. self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {'a' : 'a', 'c' : 'c', 'd' : 'd'})
  136. self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'})
  137. def test_delete(self):
  138. # Cache keys can be deleted
  139. self.cache.set("key1", "spam")
  140. self.cache.set("key2", "eggs")
  141. self.assertEqual(self.cache.get("key1"), "spam")
  142. self.cache.delete("key1")
  143. self.assertEqual(self.cache.get("key1"), None)
  144. self.assertEqual(self.cache.get("key2"), "eggs")
  145. def test_has_key(self):
  146. # The cache can be inspected for cache keys
  147. self.cache.set("hello1", "goodbye1")
  148. self.assertEqual(self.cache.has_key("hello1"), True)
  149. self.assertEqual(self.cache.has_key("goodbye1"), False)
  150. def test_in(self):
  151. # The in operator can be used to inspet cache contents
  152. self.cache.set("hello2", "goodbye2")
  153. self.assertEqual("hello2" in self.cache, True)
  154. self.assertEqual("goodbye2" in self.cache, False)
  155. def test_incr(self):
  156. # Cache values can be incremented
  157. self.cache.set('answer', 41)
  158. self.assertEqual(self.cache.incr('answer'), 42)
  159. self.assertEqual(self.cache.get('answer'), 42)
  160. self.assertEqual(self.cache.incr('answer', 10), 52)
  161. self.assertEqual(self.cache.get('answer'), 52)
  162. self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
  163. def test_decr(self):
  164. # Cache values can be decremented
  165. self.cache.set('answer', 43)
  166. self.assertEqual(self.cache.decr('answer'), 42)
  167. self.assertEqual(self.cache.get('answer'), 42)
  168. self.assertEqual(self.cache.decr('answer', 10), 32)
  169. self.assertEqual(self.cache.get('answer'), 32)
  170. self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
  171. def test_data_types(self):
  172. # Many different data types can be cached
  173. stuff = {
  174. 'string' : 'this is a string',
  175. 'int' : 42,
  176. 'list' : [1, 2, 3, 4],
  177. 'tuple' : (1, 2, 3, 4),
  178. 'dict' : {'A': 1, 'B' : 2},
  179. 'function' : f,
  180. 'class' : C,
  181. }
  182. self.cache.set("stuff", stuff)
  183. self.assertEqual(self.cache.get("stuff"), stuff)
  184. def test_cache_read_for_model_instance(self):
  185. # Don't want fields with callable as default to be called on cache read
  186. expensive_calculation.num_runs = 0
  187. Poll.objects.all().delete()
  188. my_poll = Poll.objects.create(question="Well?")
  189. self.assertEqual(Poll.objects.count(), 1)
  190. pub_date = my_poll.pub_date
  191. self.cache.set('question', my_poll)
  192. cached_poll = self.cache.get('question')
  193. self.assertEqual(cached_poll.pub_date, pub_date)
  194. # We only want the default expensive calculation run once
  195. self.assertEqual(expensive_calculation.num_runs, 1)
  196. def test_cache_write_for_model_instance_with_deferred(self):
  197. # Don't want fields with callable as default to be called on cache write
  198. expensive_calculation.num_runs = 0
  199. Poll.objects.all().delete()
  200. my_poll = Poll.objects.create(question="What?")
  201. self.assertEqual(expensive_calculation.num_runs, 1)
  202. defer_qs = Poll.objects.all().defer('question')
  203. self.assertEqual(defer_qs.count(), 1)
  204. self.assertEqual(expensive_calculation.num_runs, 1)
  205. self.cache.set('deferred_queryset', defer_qs)
  206. # cache set should not re-evaluate default functions
  207. self.assertEqual(expensive_calculation.num_runs, 1)
  208. def test_cache_read_for_model_instance_with_deferred(self):
  209. # Don't want fields with callable as default to be called on cache read
  210. expensive_calculation.num_runs = 0
  211. Poll.objects.all().delete()
  212. my_poll = Poll.objects.create(question="What?")
  213. self.assertEqual(expensive_calculation.num_runs, 1)
  214. defer_qs = Poll.objects.all().defer('question')
  215. self.assertEqual(defer_qs.count(), 1)
  216. self.cache.set('deferred_queryset', defer_qs)
  217. self.assertEqual(expensive_calculation.num_runs, 1)
  218. runs_before_cache_read = expensive_calculation.num_runs
  219. cached_polls = self.cache.get('deferred_queryset')
  220. # We only want the default expensive calculation run on creation and set
  221. self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read)
  222. def test_expiration(self):
  223. # Cache values can be set to expire
  224. self.cache.set('expire1', 'very quickly', 1)
  225. self.cache.set('expire2', 'very quickly', 1)
  226. self.cache.set('expire3', 'very quickly', 1)
  227. time.sleep(2)
  228. self.assertEqual(self.cache.get("expire1"), None)
  229. self.cache.add("expire2", "newvalue")
  230. self.assertEqual(self.cache.get("expire2"), "newvalue")
  231. self.assertEqual(self.cache.has_key("expire3"), False)
  232. def test_unicode(self):
  233. # Unicode values can be cached
  234. stuff = {
  235. u'ascii': u'ascii_value',
  236. u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1',
  237. u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2',
  238. u'ascii': {u'x' : 1 }
  239. }
  240. for (key, value) in stuff.items():
  241. self.cache.set(key, value)
  242. self.assertEqual(self.cache.get(key), value)
  243. class DBCacheTests(unittest.TestCase, BaseCacheTests):
  244. def setUp(self):
  245. management.call_command('createcachetable', 'test_cache_table', verbosity=0, interactive=False)
  246. self.cache = get_cache('db://test_cache_table')
  247. def tearDown(self):
  248. from django.db import connection
  249. cursor = connection.cursor()
  250. cursor.execute('DROP TABLE test_cache_table');
  251. class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
  252. def setUp(self):
  253. self.cache = get_cache('locmem://')
  254. # memcached backend isn't guaranteed to be available.
  255. # To check the memcached backend, the test settings file will
  256. # need to contain a CACHE_BACKEND setting that points at
  257. # your memcache server.
  258. if settings.CACHE_BACKEND.startswith('memcached://'):
  259. class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
  260. def setUp(self):
  261. self.cache = get_cache(settings.CACHE_BACKEND)
  262. class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
  263. """
  264. Specific test cases for the file-based cache.
  265. """
  266. def setUp(self):
  267. self.dirname = tempfile.mkdtemp()
  268. self.cache = get_cache('file://%s' % self.dirname)
  269. def tearDown(self):
  270. shutil.rmtree(self.dirname)
  271. def test_hashing(self):
  272. """Test that keys are hashed into subdirectories correctly"""
  273. self.cache.set("foo", "bar")
  274. keyhash = md5_constructor("foo").hexdigest()
  275. keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
  276. self.assert_(os.path.exists(keypath))
  277. def test_subdirectory_removal(self):
  278. """
  279. Make sure that the created subdirectories are correctly removed when empty.
  280. """
  281. self.cache.set("foo", "bar")
  282. keyhash = md5_constructor("foo").hexdigest()
  283. keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
  284. self.assert_(os.path.exists(keypath))
  285. self.cache.delete("foo")
  286. self.assert_(not os.path.exists(keypath))
  287. self.assert_(not os.path.exists(os.path.dirname(keypath)))
  288. self.assert_(not os.path.exists(os.path.dirname(os.path.dirname(keypath))))
  289. class CacheUtils(unittest.TestCase):
  290. """TestCase for django.utils.cache functions."""
  291. def setUp(self):
  292. self.path = '/cache/test/'
  293. self.old_settings_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  294. self.old_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
  295. settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
  296. settings.CACHE_MIDDLEWARE_SECONDS = 1
  297. def tearDown(self):
  298. settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.old_settings_key_prefix
  299. settings.CACHE_MIDDLEWARE_SECONDS = self.old_middleware_seconds
  300. def _get_request(self, path):
  301. request = HttpRequest()
  302. request.META = {
  303. 'SERVER_NAME': 'testserver',
  304. 'SERVER_PORT': 80,
  305. }
  306. request.path = request.path_info = "/cache/%s" % path
  307. return request
  308. def test_patch_vary_headers(self):
  309. headers = (
  310. # Initial vary, new headers, resulting vary.
  311. (None, ('Accept-Encoding',), 'Accept-Encoding'),
  312. ('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
  313. ('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
  314. ('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  315. ('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
  316. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  317. (None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
  318. ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  319. ('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
  320. )
  321. for initial_vary, newheaders, resulting_vary in headers:
  322. response = HttpResponse()
  323. if initial_vary is not None:
  324. response['Vary'] = initial_vary
  325. patch_vary_headers(response, newheaders)
  326. self.assertEqual(response['Vary'], resulting_vary)
  327. def test_get_cache_key(self):
  328. request = self._get_request(self.path)
  329. response = HttpResponse()
  330. key_prefix = 'localprefix'
  331. # Expect None if no headers have been set yet.
  332. self.assertEqual(get_cache_key(request), None)
  333. # Set headers to an empty list.
  334. learn_cache_key(request, response)
  335. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  336. # Verify that a specified key_prefix is taken in to account.
  337. learn_cache_key(request, response, key_prefix=key_prefix)
  338. self.assertEqual(get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  339. def test_learn_cache_key(self):
  340. request = self._get_request(self.path)
  341. response = HttpResponse()
  342. response['Vary'] = 'Pony'
  343. # Make sure that the Vary header is added to the key hash
  344. learn_cache_key(request, response)
  345. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
  346. if __name__ == '__main__':
  347. unittest.main()