test_transactions.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # Copyright 2018-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 http import HTTPStatus
  15. from unittest.mock import Mock, call
  16. from twisted.internet import defer, reactor
  17. from synapse.logging.context import SENTINEL_CONTEXT, LoggingContext, current_context
  18. from synapse.rest.client.transactions import CLEANUP_PERIOD_MS, HttpTransactionCache
  19. from synapse.util import Clock
  20. from tests import unittest
  21. from tests.test_utils import make_awaitable
  22. from tests.utils import MockClock
  23. class HttpTransactionCacheTestCase(unittest.TestCase):
  24. def setUp(self) -> None:
  25. self.clock = MockClock()
  26. self.hs = Mock()
  27. self.hs.get_clock = Mock(return_value=self.clock)
  28. self.hs.get_auth = Mock()
  29. self.cache = HttpTransactionCache(self.hs)
  30. self.mock_http_response = (HTTPStatus.OK, "GOOD JOB!")
  31. self.mock_key = "foo"
  32. @defer.inlineCallbacks
  33. def test_executes_given_function(self):
  34. cb = Mock(return_value=make_awaitable(self.mock_http_response))
  35. res = yield self.cache.fetch_or_execute(
  36. self.mock_key, cb, "some_arg", keyword="arg"
  37. )
  38. cb.assert_called_once_with("some_arg", keyword="arg")
  39. self.assertEqual(res, self.mock_http_response)
  40. @defer.inlineCallbacks
  41. def test_deduplicates_based_on_key(self):
  42. cb = Mock(return_value=make_awaitable(self.mock_http_response))
  43. for i in range(3): # invoke multiple times
  44. res = yield self.cache.fetch_or_execute(
  45. self.mock_key, cb, "some_arg", keyword="arg", changing_args=i
  46. )
  47. self.assertEqual(res, self.mock_http_response)
  48. # expect only a single call to do the work
  49. cb.assert_called_once_with("some_arg", keyword="arg", changing_args=0)
  50. @defer.inlineCallbacks
  51. def test_logcontexts_with_async_result(self):
  52. @defer.inlineCallbacks
  53. def cb():
  54. yield Clock(reactor).sleep(0)
  55. return "yay"
  56. @defer.inlineCallbacks
  57. def test():
  58. with LoggingContext("c") as c1:
  59. res = yield self.cache.fetch_or_execute(self.mock_key, cb)
  60. self.assertIs(current_context(), c1)
  61. self.assertEqual(res, "yay")
  62. # run the test twice in parallel
  63. d = defer.gatherResults([test(), test()])
  64. self.assertIs(current_context(), SENTINEL_CONTEXT)
  65. yield d
  66. self.assertIs(current_context(), SENTINEL_CONTEXT)
  67. @defer.inlineCallbacks
  68. def test_does_not_cache_exceptions(self):
  69. """Checks that, if the callback throws an exception, it is called again
  70. for the next request.
  71. """
  72. called = [False]
  73. def cb():
  74. if called[0]:
  75. # return a valid result the second time
  76. return defer.succeed(self.mock_http_response)
  77. called[0] = True
  78. raise Exception("boo")
  79. with LoggingContext("test") as test_context:
  80. try:
  81. yield self.cache.fetch_or_execute(self.mock_key, cb)
  82. except Exception as e:
  83. self.assertEqual(e.args[0], "boo")
  84. self.assertIs(current_context(), test_context)
  85. res = yield self.cache.fetch_or_execute(self.mock_key, cb)
  86. self.assertEqual(res, self.mock_http_response)
  87. self.assertIs(current_context(), test_context)
  88. @defer.inlineCallbacks
  89. def test_does_not_cache_failures(self):
  90. """Checks that, if the callback returns a failure, it is called again
  91. for the next request.
  92. """
  93. called = [False]
  94. def cb():
  95. if called[0]:
  96. # return a valid result the second time
  97. return defer.succeed(self.mock_http_response)
  98. called[0] = True
  99. return defer.fail(Exception("boo"))
  100. with LoggingContext("test") as test_context:
  101. try:
  102. yield self.cache.fetch_or_execute(self.mock_key, cb)
  103. except Exception as e:
  104. self.assertEqual(e.args[0], "boo")
  105. self.assertIs(current_context(), test_context)
  106. res = yield self.cache.fetch_or_execute(self.mock_key, cb)
  107. self.assertEqual(res, self.mock_http_response)
  108. self.assertIs(current_context(), test_context)
  109. @defer.inlineCallbacks
  110. def test_cleans_up(self):
  111. cb = Mock(return_value=make_awaitable(self.mock_http_response))
  112. yield self.cache.fetch_or_execute(self.mock_key, cb, "an arg")
  113. # should NOT have cleaned up yet
  114. self.clock.advance_time_msec(CLEANUP_PERIOD_MS / 2)
  115. yield self.cache.fetch_or_execute(self.mock_key, cb, "an arg")
  116. # still using cache
  117. cb.assert_called_once_with("an arg")
  118. self.clock.advance_time_msec(CLEANUP_PERIOD_MS)
  119. yield self.cache.fetch_or_execute(self.mock_key, cb, "an arg")
  120. # no longer using cache
  121. self.assertEqual(cb.call_count, 2)
  122. self.assertEqual(cb.call_args_list, [call("an arg"), call("an arg")])