test_expiring_cache.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 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.expiringcache import ExpiringCache
  17. from tests.utils import MockClock
  18. class ExpiringCacheTestCase(unittest.TestCase):
  19. def test_get_set(self):
  20. clock = MockClock()
  21. cache = ExpiringCache("test", clock, max_len=1)
  22. cache["key"] = "value"
  23. self.assertEquals(cache.get("key"), "value")
  24. self.assertEquals(cache["key"], "value")
  25. def test_eviction(self):
  26. clock = MockClock()
  27. cache = ExpiringCache("test", clock, max_len=2)
  28. cache["key"] = "value"
  29. cache["key2"] = "value2"
  30. self.assertEquals(cache.get("key"), "value")
  31. self.assertEquals(cache.get("key2"), "value2")
  32. cache["key3"] = "value3"
  33. self.assertEquals(cache.get("key"), None)
  34. self.assertEquals(cache.get("key2"), "value2")
  35. self.assertEquals(cache.get("key3"), "value3")
  36. def test_iterable_eviction(self):
  37. clock = MockClock()
  38. cache = ExpiringCache("test", clock, max_len=5, iterable=True)
  39. cache["key"] = [1]
  40. cache["key2"] = [2, 3]
  41. cache["key3"] = [4, 5]
  42. self.assertEquals(cache.get("key"), [1])
  43. self.assertEquals(cache.get("key2"), [2, 3])
  44. self.assertEquals(cache.get("key3"), [4, 5])
  45. cache["key4"] = [6, 7]
  46. self.assertEquals(cache.get("key"), None)
  47. self.assertEquals(cache.get("key2"), None)
  48. self.assertEquals(cache.get("key3"), [4, 5])
  49. self.assertEquals(cache.get("key4"), [6, 7])
  50. def test_time_eviction(self):
  51. clock = MockClock()
  52. cache = ExpiringCache("test", clock, expiry_ms=1000)
  53. cache.start()
  54. cache["key"] = 1
  55. clock.advance_time(0.5)
  56. cache["key2"] = 2
  57. self.assertEquals(cache.get("key"), 1)
  58. self.assertEquals(cache.get("key2"), 2)
  59. clock.advance_time(0.9)
  60. self.assertEquals(cache.get("key"), None)
  61. self.assertEquals(cache.get("key2"), 2)
  62. clock.advance_time(1)
  63. self.assertEquals(cache.get("key"), None)
  64. self.assertEquals(cache.get("key2"), None)