test_response_cache.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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 parameterized import parameterized
  15. from twisted.internet import defer
  16. from synapse.util.caches.response_cache import ResponseCache, ResponseCacheContext
  17. from tests.server import get_clock
  18. from tests.unittest import TestCase
  19. class ResponseCacheTestCase(TestCase):
  20. """
  21. A TestCase class for ResponseCache.
  22. The test-case function naming has some logic to it in it's parts, here's some notes about it:
  23. wait: Denotes tests that have an element of "waiting" before its wrapped result becomes available
  24. (Generally these just use .delayed_return instead of .instant_return in it's wrapped call.)
  25. expire: Denotes tests that test expiry after assured existence.
  26. (These have cache with a short timeout_ms=, shorter than will be tested through advancing the clock)
  27. """
  28. def setUp(self):
  29. self.reactor, self.clock = get_clock()
  30. def with_cache(self, name: str, ms: int = 0) -> ResponseCache:
  31. return ResponseCache(self.clock, name, timeout_ms=ms)
  32. @staticmethod
  33. async def instant_return(o: str) -> str:
  34. return o
  35. async def delayed_return(self, o: str) -> str:
  36. await self.clock.sleep(1)
  37. return o
  38. def test_cache_hit(self):
  39. cache = self.with_cache("keeping_cache", ms=9001)
  40. expected_result = "howdy"
  41. wrap_d = defer.ensureDeferred(
  42. cache.wrap(0, self.instant_return, expected_result)
  43. )
  44. self.assertEqual(
  45. expected_result,
  46. self.successResultOf(wrap_d),
  47. "initial wrap result should be the same",
  48. )
  49. self.assertEqual(
  50. expected_result,
  51. self.successResultOf(cache.get(0)),
  52. "cache should have the result",
  53. )
  54. def test_cache_miss(self):
  55. cache = self.with_cache("trashing_cache", ms=0)
  56. expected_result = "howdy"
  57. wrap_d = defer.ensureDeferred(
  58. cache.wrap(0, self.instant_return, expected_result)
  59. )
  60. self.assertEqual(
  61. expected_result,
  62. self.successResultOf(wrap_d),
  63. "initial wrap result should be the same",
  64. )
  65. self.assertIsNone(cache.get(0), "cache should not have the result now")
  66. def test_cache_expire(self):
  67. cache = self.with_cache("short_cache", ms=1000)
  68. expected_result = "howdy"
  69. wrap_d = defer.ensureDeferred(
  70. cache.wrap(0, self.instant_return, expected_result)
  71. )
  72. self.assertEqual(expected_result, self.successResultOf(wrap_d))
  73. self.assertEqual(
  74. expected_result,
  75. self.successResultOf(cache.get(0)),
  76. "cache should still have the result",
  77. )
  78. # cache eviction timer is handled
  79. self.reactor.pump((2,))
  80. self.assertIsNone(cache.get(0), "cache should not have the result now")
  81. def test_cache_wait_hit(self):
  82. cache = self.with_cache("neutral_cache")
  83. expected_result = "howdy"
  84. wrap_d = defer.ensureDeferred(
  85. cache.wrap(0, self.delayed_return, expected_result)
  86. )
  87. self.assertNoResult(wrap_d)
  88. # function wakes up, returns result
  89. self.reactor.pump((2,))
  90. self.assertEqual(expected_result, self.successResultOf(wrap_d))
  91. def test_cache_wait_expire(self):
  92. cache = self.with_cache("medium_cache", ms=3000)
  93. expected_result = "howdy"
  94. wrap_d = defer.ensureDeferred(
  95. cache.wrap(0, self.delayed_return, expected_result)
  96. )
  97. self.assertNoResult(wrap_d)
  98. # stop at 1 second to callback cache eviction callLater at that time, then another to set time at 2
  99. self.reactor.pump((1, 1))
  100. self.assertEqual(expected_result, self.successResultOf(wrap_d))
  101. self.assertEqual(
  102. expected_result,
  103. self.successResultOf(cache.get(0)),
  104. "cache should still have the result",
  105. )
  106. # (1 + 1 + 2) > 3.0, cache eviction timer is handled
  107. self.reactor.pump((2,))
  108. self.assertIsNone(cache.get(0), "cache should not have the result now")
  109. @parameterized.expand([(True,), (False,)])
  110. def test_cache_context_nocache(self, should_cache: bool):
  111. """If the callback clears the should_cache bit, the result should not be cached"""
  112. cache = self.with_cache("medium_cache", ms=3000)
  113. expected_result = "howdy"
  114. call_count = 0
  115. async def non_caching(o: str, cache_context: ResponseCacheContext[int]):
  116. nonlocal call_count
  117. call_count += 1
  118. await self.clock.sleep(1)
  119. cache_context.should_cache = should_cache
  120. return o
  121. wrap_d = defer.ensureDeferred(
  122. cache.wrap(0, non_caching, expected_result, cache_context=True)
  123. )
  124. # there should be no result to start with
  125. self.assertNoResult(wrap_d)
  126. # a second call should also return a pending deferred
  127. wrap2_d = defer.ensureDeferred(
  128. cache.wrap(0, non_caching, expected_result, cache_context=True)
  129. )
  130. self.assertNoResult(wrap2_d)
  131. # and there should have been exactly one call
  132. self.assertEqual(call_count, 1)
  133. # let the call complete
  134. self.reactor.advance(1)
  135. # both results should have completed
  136. self.assertEqual(expected_result, self.successResultOf(wrap_d))
  137. self.assertEqual(expected_result, self.successResultOf(wrap2_d))
  138. if should_cache:
  139. self.assertEqual(
  140. expected_result,
  141. self.successResultOf(cache.get(0)),
  142. "cache should still have the result",
  143. )
  144. else:
  145. self.assertIsNone(cache.get(0), "cache should not have the result")