test_descriptors.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from functools import partial
  17. import logging
  18. import mock
  19. from synapse.api.errors import SynapseError
  20. from synapse.util import async
  21. from synapse.util import logcontext
  22. from twisted.internet import defer
  23. from synapse.util.caches import descriptors
  24. from tests import unittest
  25. logger = logging.getLogger(__name__)
  26. class CacheTestCase(unittest.TestCase):
  27. def test_invalidate_all(self):
  28. cache = descriptors.Cache("testcache")
  29. callback_record = [False, False]
  30. def record_callback(idx):
  31. callback_record[idx] = True
  32. # add a couple of pending entries
  33. d1 = defer.Deferred()
  34. cache.set("key1", d1, partial(record_callback, 0))
  35. d2 = defer.Deferred()
  36. cache.set("key2", d2, partial(record_callback, 1))
  37. # lookup should return the deferreds
  38. self.assertIs(cache.get("key1"), d1)
  39. self.assertIs(cache.get("key2"), d2)
  40. # let one of the lookups complete
  41. d2.callback("result2")
  42. self.assertEqual(cache.get("key2"), "result2")
  43. # now do the invalidation
  44. cache.invalidate_all()
  45. # lookup should return none
  46. self.assertIsNone(cache.get("key1", None))
  47. self.assertIsNone(cache.get("key2", None))
  48. # both callbacks should have been callbacked
  49. self.assertTrue(
  50. callback_record[0], "Invalidation callback for key1 not called",
  51. )
  52. self.assertTrue(
  53. callback_record[1], "Invalidation callback for key2 not called",
  54. )
  55. # letting the other lookup complete should do nothing
  56. d1.callback("result1")
  57. self.assertIsNone(cache.get("key1", None))
  58. class DescriptorTestCase(unittest.TestCase):
  59. @defer.inlineCallbacks
  60. def test_cache(self):
  61. class Cls(object):
  62. def __init__(self):
  63. self.mock = mock.Mock()
  64. @descriptors.cached()
  65. def fn(self, arg1, arg2):
  66. return self.mock(arg1, arg2)
  67. obj = Cls()
  68. obj.mock.return_value = 'fish'
  69. r = yield obj.fn(1, 2)
  70. self.assertEqual(r, 'fish')
  71. obj.mock.assert_called_once_with(1, 2)
  72. obj.mock.reset_mock()
  73. # a call with different params should call the mock again
  74. obj.mock.return_value = 'chips'
  75. r = yield obj.fn(1, 3)
  76. self.assertEqual(r, 'chips')
  77. obj.mock.assert_called_once_with(1, 3)
  78. obj.mock.reset_mock()
  79. # the two values should now be cached
  80. r = yield obj.fn(1, 2)
  81. self.assertEqual(r, 'fish')
  82. r = yield obj.fn(1, 3)
  83. self.assertEqual(r, 'chips')
  84. obj.mock.assert_not_called()
  85. @defer.inlineCallbacks
  86. def test_cache_num_args(self):
  87. """Only the first num_args arguments should matter to the cache"""
  88. class Cls(object):
  89. def __init__(self):
  90. self.mock = mock.Mock()
  91. @descriptors.cached(num_args=1)
  92. def fn(self, arg1, arg2):
  93. return self.mock(arg1, arg2)
  94. obj = Cls()
  95. obj.mock.return_value = 'fish'
  96. r = yield obj.fn(1, 2)
  97. self.assertEqual(r, 'fish')
  98. obj.mock.assert_called_once_with(1, 2)
  99. obj.mock.reset_mock()
  100. # a call with different params should call the mock again
  101. obj.mock.return_value = 'chips'
  102. r = yield obj.fn(2, 3)
  103. self.assertEqual(r, 'chips')
  104. obj.mock.assert_called_once_with(2, 3)
  105. obj.mock.reset_mock()
  106. # the two values should now be cached; we should be able to vary
  107. # the second argument and still get the cached result.
  108. r = yield obj.fn(1, 4)
  109. self.assertEqual(r, 'fish')
  110. r = yield obj.fn(2, 5)
  111. self.assertEqual(r, 'chips')
  112. obj.mock.assert_not_called()
  113. def test_cache_logcontexts(self):
  114. """Check that logcontexts are set and restored correctly when
  115. using the cache."""
  116. complete_lookup = defer.Deferred()
  117. class Cls(object):
  118. @descriptors.cached()
  119. def fn(self, arg1):
  120. @defer.inlineCallbacks
  121. def inner_fn():
  122. with logcontext.PreserveLoggingContext():
  123. yield complete_lookup
  124. defer.returnValue(1)
  125. return inner_fn()
  126. @defer.inlineCallbacks
  127. def do_lookup():
  128. with logcontext.LoggingContext() as c1:
  129. c1.name = "c1"
  130. r = yield obj.fn(1)
  131. self.assertEqual(logcontext.LoggingContext.current_context(),
  132. c1)
  133. defer.returnValue(r)
  134. def check_result(r):
  135. self.assertEqual(r, 1)
  136. obj = Cls()
  137. # set off a deferred which will do a cache lookup
  138. d1 = do_lookup()
  139. self.assertEqual(logcontext.LoggingContext.current_context(),
  140. logcontext.LoggingContext.sentinel)
  141. d1.addCallback(check_result)
  142. # and another
  143. d2 = do_lookup()
  144. self.assertEqual(logcontext.LoggingContext.current_context(),
  145. logcontext.LoggingContext.sentinel)
  146. d2.addCallback(check_result)
  147. # let the lookup complete
  148. complete_lookup.callback(None)
  149. return defer.gatherResults([d1, d2])
  150. def test_cache_logcontexts_with_exception(self):
  151. """Check that the cache sets and restores logcontexts correctly when
  152. the lookup function throws an exception"""
  153. class Cls(object):
  154. @descriptors.cached()
  155. def fn(self, arg1):
  156. @defer.inlineCallbacks
  157. def inner_fn():
  158. yield async.run_on_reactor()
  159. raise SynapseError(400, "blah")
  160. return inner_fn()
  161. @defer.inlineCallbacks
  162. def do_lookup():
  163. with logcontext.LoggingContext() as c1:
  164. c1.name = "c1"
  165. try:
  166. yield obj.fn(1)
  167. self.fail("No exception thrown")
  168. except SynapseError:
  169. pass
  170. self.assertEqual(logcontext.LoggingContext.current_context(),
  171. c1)
  172. obj = Cls()
  173. # set off a deferred which will do a cache lookup
  174. d1 = do_lookup()
  175. self.assertEqual(logcontext.LoggingContext.current_context(),
  176. logcontext.LoggingContext.sentinel)
  177. return d1
  178. @defer.inlineCallbacks
  179. def test_cache_default_args(self):
  180. class Cls(object):
  181. def __init__(self):
  182. self.mock = mock.Mock()
  183. @descriptors.cached()
  184. def fn(self, arg1, arg2=2, arg3=3):
  185. return self.mock(arg1, arg2, arg3)
  186. obj = Cls()
  187. obj.mock.return_value = 'fish'
  188. r = yield obj.fn(1, 2, 3)
  189. self.assertEqual(r, 'fish')
  190. obj.mock.assert_called_once_with(1, 2, 3)
  191. obj.mock.reset_mock()
  192. # a call with same params shouldn't call the mock again
  193. r = yield obj.fn(1, 2)
  194. self.assertEqual(r, 'fish')
  195. obj.mock.assert_not_called()
  196. obj.mock.reset_mock()
  197. # a call with different params should call the mock again
  198. obj.mock.return_value = 'chips'
  199. r = yield obj.fn(2, 3)
  200. self.assertEqual(r, 'chips')
  201. obj.mock.assert_called_once_with(2, 3, 3)
  202. obj.mock.reset_mock()
  203. # the two values should now be cached
  204. r = yield obj.fn(1, 2)
  205. self.assertEqual(r, 'fish')
  206. r = yield obj.fn(2, 3)
  207. self.assertEqual(r, 'chips')
  208. obj.mock.assert_not_called()