test_response_cache.py 7.2 KB

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