1
0

test_expiring_cache.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 synapse.util.caches.expiringcache import ExpiringCache
  16. from tests.utils import MockClock
  17. from .. import unittest
  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["key"] = 1
  54. clock.advance_time(0.5)
  55. cache["key2"] = 2
  56. self.assertEquals(cache.get("key"), 1)
  57. self.assertEquals(cache.get("key2"), 2)
  58. clock.advance_time(0.9)
  59. self.assertEquals(cache.get("key"), None)
  60. self.assertEquals(cache.get("key2"), 2)
  61. clock.advance_time(1)
  62. self.assertEquals(cache.get("key"), None)
  63. self.assertEquals(cache.get("key2"), None)