1
0

test_snapshot_cache.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 twisted.internet.defer import Deferred
  16. from synapse.util.caches.snapshot_cache import SnapshotCache
  17. from .. import unittest
  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. if isinstance(get_result_at_11, Deferred):
  46. # The cache may return the actual result rather than a deferred
  47. self.assertTrue(get_result_at_11.called)
  48. # Check that getting the key after the deferred has resolved
  49. # after the cache expires returns None
  50. get_result_at_12 = self.cache.get(12, "key")
  51. self.assertIsNone(get_result_at_12)