test_expiring_cache.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright 2017 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from synapse.util.caches.expiringcache import ExpiringCache
  15. from tests.utils import MockClock
  16. from .. import unittest
  17. class ExpiringCacheTestCase(unittest.HomeserverTestCase):
  18. def test_get_set(self):
  19. clock = MockClock()
  20. cache = ExpiringCache("test", clock, max_len=1)
  21. cache["key"] = "value"
  22. self.assertEqual(cache.get("key"), "value")
  23. self.assertEqual(cache["key"], "value")
  24. def test_eviction(self):
  25. clock = MockClock()
  26. cache = ExpiringCache("test", clock, max_len=2)
  27. cache["key"] = "value"
  28. cache["key2"] = "value2"
  29. self.assertEqual(cache.get("key"), "value")
  30. self.assertEqual(cache.get("key2"), "value2")
  31. cache["key3"] = "value3"
  32. self.assertEqual(cache.get("key"), None)
  33. self.assertEqual(cache.get("key2"), "value2")
  34. self.assertEqual(cache.get("key3"), "value3")
  35. def test_iterable_eviction(self):
  36. clock = MockClock()
  37. cache = ExpiringCache("test", clock, max_len=5, iterable=True)
  38. cache["key"] = [1]
  39. cache["key2"] = [2, 3]
  40. cache["key3"] = [4, 5]
  41. self.assertEqual(cache.get("key"), [1])
  42. self.assertEqual(cache.get("key2"), [2, 3])
  43. self.assertEqual(cache.get("key3"), [4, 5])
  44. cache["key4"] = [6, 7]
  45. self.assertEqual(cache.get("key"), None)
  46. self.assertEqual(cache.get("key2"), None)
  47. self.assertEqual(cache.get("key3"), [4, 5])
  48. self.assertEqual(cache.get("key4"), [6, 7])
  49. def test_time_eviction(self):
  50. clock = MockClock()
  51. cache = ExpiringCache("test", clock, expiry_ms=1000)
  52. cache["key"] = 1
  53. clock.advance_time(0.5)
  54. cache["key2"] = 2
  55. self.assertEqual(cache.get("key"), 1)
  56. self.assertEqual(cache.get("key2"), 2)
  57. clock.advance_time(0.9)
  58. self.assertEqual(cache.get("key"), None)
  59. self.assertEqual(cache.get("key2"), 2)
  60. clock.advance_time(1)
  61. self.assertEqual(cache.get("key"), None)
  62. self.assertEqual(cache.get("key2"), None)