test_cached_call.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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 typing import NoReturn
  15. from unittest.mock import Mock
  16. from twisted.internet import defer
  17. from twisted.internet.defer import Deferred
  18. from synapse.util.caches.cached_call import CachedCall, RetryOnExceptionCachedCall
  19. from tests.test_utils import get_awaitable_result
  20. from tests.unittest import TestCase
  21. class CachedCallTestCase(TestCase):
  22. def test_get(self) -> None:
  23. """
  24. Happy-path test case: makes a couple of calls and makes sure they behave
  25. correctly
  26. """
  27. d: "Deferred[int]" = Deferred()
  28. async def f() -> int:
  29. return await d
  30. slow_call = Mock(side_effect=f)
  31. cached_call = CachedCall(slow_call)
  32. # the mock should not yet have been called
  33. slow_call.assert_not_called()
  34. # now fire off a couple of calls
  35. completed_results = []
  36. async def r() -> None:
  37. res = await cached_call.get()
  38. completed_results.append(res)
  39. r1 = defer.ensureDeferred(r())
  40. r2 = defer.ensureDeferred(r())
  41. # neither result should be complete yet
  42. self.assertNoResult(r1)
  43. self.assertNoResult(r2)
  44. # and the mock should have been called *once*, with no params
  45. slow_call.assert_called_once_with()
  46. # allow the deferred to complete, which should complete both the pending results
  47. d.callback(123)
  48. self.assertEqual(completed_results, [123, 123])
  49. self.successResultOf(r1)
  50. self.successResultOf(r2)
  51. # another call to the getter should complete immediately
  52. slow_call.reset_mock()
  53. r3 = get_awaitable_result(cached_call.get())
  54. self.assertEqual(r3, 123)
  55. slow_call.assert_not_called()
  56. def test_fast_call(self) -> None:
  57. """
  58. Test the behaviour when the underlying function completes immediately
  59. """
  60. async def f() -> int:
  61. return 12
  62. fast_call = Mock(side_effect=f)
  63. cached_call = CachedCall(fast_call)
  64. # the mock should not yet have been called
  65. fast_call.assert_not_called()
  66. # run the call a couple of times, which should complete immediately
  67. self.assertEqual(get_awaitable_result(cached_call.get()), 12)
  68. self.assertEqual(get_awaitable_result(cached_call.get()), 12)
  69. # the mock should have been called once
  70. fast_call.assert_called_once_with()
  71. class RetryOnExceptionCachedCallTestCase(TestCase):
  72. def test_get(self) -> None:
  73. # set up the RetryOnExceptionCachedCall around a function which will fail
  74. # (after a while)
  75. d: "Deferred[int]" = Deferred()
  76. async def f1() -> NoReturn:
  77. await d
  78. raise ValueError("moo")
  79. slow_call = Mock(side_effect=f1)
  80. cached_call = RetryOnExceptionCachedCall(slow_call)
  81. # the mock should not yet have been called
  82. slow_call.assert_not_called()
  83. # now fire off a couple of calls
  84. completed_results = []
  85. async def r() -> None:
  86. try:
  87. await cached_call.get()
  88. except Exception as e1:
  89. completed_results.append(e1)
  90. r1 = defer.ensureDeferred(r())
  91. r2 = defer.ensureDeferred(r())
  92. # neither result should be complete yet
  93. self.assertNoResult(r1)
  94. self.assertNoResult(r2)
  95. # and the mock should have been called *once*, with no params
  96. slow_call.assert_called_once_with()
  97. # complete the deferred, which should make the pending calls fail
  98. d.callback(0)
  99. self.assertEqual(len(completed_results), 2)
  100. for e in completed_results:
  101. self.assertIsInstance(e, ValueError)
  102. self.assertEqual(e.args, ("moo",))
  103. # reset the mock to return a successful result, and make another pair of calls
  104. # to the getter
  105. d = Deferred()
  106. async def f2() -> int:
  107. return await d
  108. slow_call.reset_mock()
  109. slow_call.side_effect = f2
  110. r3 = defer.ensureDeferred(cached_call.get())
  111. r4 = defer.ensureDeferred(cached_call.get())
  112. self.assertNoResult(r3)
  113. self.assertNoResult(r4)
  114. slow_call.assert_called_once_with()
  115. # let that call complete, and check the results
  116. d.callback(123)
  117. self.assertEqual(self.successResultOf(r3), 123)
  118. self.assertEqual(self.successResultOf(r4), 123)
  119. # and now more calls to the getter should complete immediately
  120. slow_call.reset_mock()
  121. self.assertEqual(get_awaitable_result(cached_call.get()), 123)
  122. slow_call.assert_not_called()