test_lrucache.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from .. import unittest
  16. from synapse.util.caches.lrucache import LruCache
  17. from synapse.util.caches.treecache import TreeCache
  18. class LruCacheTestCase(unittest.TestCase):
  19. def test_get_set(self):
  20. cache = LruCache(1)
  21. cache["key"] = "value"
  22. self.assertEquals(cache.get("key"), "value")
  23. self.assertEquals(cache["key"], "value")
  24. def test_eviction(self):
  25. cache = LruCache(2)
  26. cache[1] = 1
  27. cache[2] = 2
  28. self.assertEquals(cache.get(1), 1)
  29. self.assertEquals(cache.get(2), 2)
  30. cache[3] = 3
  31. self.assertEquals(cache.get(1), None)
  32. self.assertEquals(cache.get(2), 2)
  33. self.assertEquals(cache.get(3), 3)
  34. def test_setdefault(self):
  35. cache = LruCache(1)
  36. self.assertEquals(cache.setdefault("key", 1), 1)
  37. self.assertEquals(cache.get("key"), 1)
  38. self.assertEquals(cache.setdefault("key", 2), 1)
  39. self.assertEquals(cache.get("key"), 1)
  40. def test_pop(self):
  41. cache = LruCache(1)
  42. cache["key"] = 1
  43. self.assertEquals(cache.pop("key"), 1)
  44. self.assertEquals(cache.pop("key"), None)
  45. def test_del_multi(self):
  46. cache = LruCache(4, 2, cache_type=TreeCache)
  47. cache[("animal", "cat")] = "mew"
  48. cache[("animal", "dog")] = "woof"
  49. cache[("vehicles", "car")] = "vroom"
  50. cache[("vehicles", "train")] = "chuff"
  51. self.assertEquals(len(cache), 4)
  52. self.assertEquals(cache.get(("animal", "cat")), "mew")
  53. self.assertEquals(cache.get(("vehicles", "car")), "vroom")
  54. cache.del_multi(("animal",))
  55. self.assertEquals(len(cache), 2)
  56. self.assertEquals(cache.get(("animal", "cat")), None)
  57. self.assertEquals(cache.get(("animal", "dog")), None)
  58. self.assertEquals(cache.get(("vehicles", "car")), "vroom")
  59. self.assertEquals(cache.get(("vehicles", "train")), "chuff")
  60. # Man from del_multi say "Yes".
  61. def test_clear(self):
  62. cache = LruCache(1)
  63. cache["key"] = 1
  64. cache.clear()
  65. self.assertEquals(len(cache), 0)