test_snapshot_cache.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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.snapshot_cache import SnapshotCache
  17. from twisted.internet.defer import Deferred
  18. class SnapshotCacheTestCase(unittest.TestCase):
  19. def setUp(self):
  20. self.cache = SnapshotCache()
  21. self.cache.DURATION_MS = 1
  22. def test_get_set(self):
  23. # Check that getting a missing key returns None
  24. self.assertEquals(self.cache.get(0, "key"), None)
  25. # Check that setting a key with a deferred returns
  26. # a deferred that resolves when the initial deferred does
  27. d = Deferred()
  28. set_result = self.cache.set(0, "key", d)
  29. self.assertIsNotNone(set_result)
  30. self.assertFalse(set_result.called)
  31. # Check that getting the key before the deferred has resolved
  32. # returns a deferred that resolves when the initial deferred does.
  33. get_result_at_10 = self.cache.get(10, "key")
  34. self.assertIsNotNone(get_result_at_10)
  35. self.assertFalse(get_result_at_10.called)
  36. # Check that the returned deferreds resolve when the initial deferred
  37. # does.
  38. d.callback("v")
  39. self.assertTrue(set_result.called)
  40. self.assertTrue(get_result_at_10.called)
  41. # Check that getting the key after the deferred has resolved
  42. # before the cache expires returns a resolved deferred.
  43. get_result_at_11 = self.cache.get(11, "key")
  44. self.assertIsNotNone(get_result_at_11)
  45. self.assertTrue(get_result_at_11.called)
  46. # Check that getting the key after the deferred has resolved
  47. # after the cache expires returns None
  48. get_result_at_12 = self.cache.get(12, "key")
  49. self.assertIsNone(get_result_at_12)