test_descriptors.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. import logging
  17. from functools import partial
  18. import mock
  19. from twisted.internet import defer, reactor
  20. from synapse.api.errors import SynapseError
  21. from synapse.logging.context import (
  22. LoggingContext,
  23. PreserveLoggingContext,
  24. make_deferred_yieldable,
  25. )
  26. from synapse.util.caches import descriptors
  27. from tests import unittest
  28. logger = logging.getLogger(__name__)
  29. def run_on_reactor():
  30. d = defer.Deferred()
  31. reactor.callLater(0, d.callback, 0)
  32. return make_deferred_yieldable(d)
  33. class CacheTestCase(unittest.TestCase):
  34. def test_invalidate_all(self):
  35. cache = descriptors.Cache("testcache")
  36. callback_record = [False, False]
  37. def record_callback(idx):
  38. callback_record[idx] = True
  39. # add a couple of pending entries
  40. d1 = defer.Deferred()
  41. cache.set("key1", d1, partial(record_callback, 0))
  42. d2 = defer.Deferred()
  43. cache.set("key2", d2, partial(record_callback, 1))
  44. # lookup should return the deferreds
  45. self.assertIs(cache.get("key1"), d1)
  46. self.assertIs(cache.get("key2"), d2)
  47. # let one of the lookups complete
  48. d2.callback("result2")
  49. self.assertEqual(cache.get("key2"), "result2")
  50. # now do the invalidation
  51. cache.invalidate_all()
  52. # lookup should return none
  53. self.assertIsNone(cache.get("key1", None))
  54. self.assertIsNone(cache.get("key2", None))
  55. # both callbacks should have been callbacked
  56. self.assertTrue(callback_record[0], "Invalidation callback for key1 not called")
  57. self.assertTrue(callback_record[1], "Invalidation callback for key2 not called")
  58. # letting the other lookup complete should do nothing
  59. d1.callback("result1")
  60. self.assertIsNone(cache.get("key1", None))
  61. class DescriptorTestCase(unittest.TestCase):
  62. @defer.inlineCallbacks
  63. def test_cache(self):
  64. class Cls(object):
  65. def __init__(self):
  66. self.mock = mock.Mock()
  67. @descriptors.cached()
  68. def fn(self, arg1, arg2):
  69. return self.mock(arg1, arg2)
  70. obj = Cls()
  71. obj.mock.return_value = "fish"
  72. r = yield obj.fn(1, 2)
  73. self.assertEqual(r, "fish")
  74. obj.mock.assert_called_once_with(1, 2)
  75. obj.mock.reset_mock()
  76. # a call with different params should call the mock again
  77. obj.mock.return_value = "chips"
  78. r = yield obj.fn(1, 3)
  79. self.assertEqual(r, "chips")
  80. obj.mock.assert_called_once_with(1, 3)
  81. obj.mock.reset_mock()
  82. # the two values should now be cached
  83. r = yield obj.fn(1, 2)
  84. self.assertEqual(r, "fish")
  85. r = yield obj.fn(1, 3)
  86. self.assertEqual(r, "chips")
  87. obj.mock.assert_not_called()
  88. @defer.inlineCallbacks
  89. def test_cache_num_args(self):
  90. """Only the first num_args arguments should matter to the cache"""
  91. class Cls(object):
  92. def __init__(self):
  93. self.mock = mock.Mock()
  94. @descriptors.cached(num_args=1)
  95. def fn(self, arg1, arg2):
  96. return self.mock(arg1, arg2)
  97. obj = Cls()
  98. obj.mock.return_value = "fish"
  99. r = yield obj.fn(1, 2)
  100. self.assertEqual(r, "fish")
  101. obj.mock.assert_called_once_with(1, 2)
  102. obj.mock.reset_mock()
  103. # a call with different params should call the mock again
  104. obj.mock.return_value = "chips"
  105. r = yield obj.fn(2, 3)
  106. self.assertEqual(r, "chips")
  107. obj.mock.assert_called_once_with(2, 3)
  108. obj.mock.reset_mock()
  109. # the two values should now be cached; we should be able to vary
  110. # the second argument and still get the cached result.
  111. r = yield obj.fn(1, 4)
  112. self.assertEqual(r, "fish")
  113. r = yield obj.fn(2, 5)
  114. self.assertEqual(r, "chips")
  115. obj.mock.assert_not_called()
  116. def test_cache_logcontexts(self):
  117. """Check that logcontexts are set and restored correctly when
  118. using the cache."""
  119. complete_lookup = defer.Deferred()
  120. class Cls(object):
  121. @descriptors.cached()
  122. def fn(self, arg1):
  123. @defer.inlineCallbacks
  124. def inner_fn():
  125. with PreserveLoggingContext():
  126. yield complete_lookup
  127. defer.returnValue(1)
  128. return inner_fn()
  129. @defer.inlineCallbacks
  130. def do_lookup():
  131. with LoggingContext() as c1:
  132. c1.name = "c1"
  133. r = yield obj.fn(1)
  134. self.assertEqual(LoggingContext.current_context(), c1)
  135. defer.returnValue(r)
  136. def check_result(r):
  137. self.assertEqual(r, 1)
  138. obj = Cls()
  139. # set off a deferred which will do a cache lookup
  140. d1 = do_lookup()
  141. self.assertEqual(LoggingContext.current_context(), LoggingContext.sentinel)
  142. d1.addCallback(check_result)
  143. # and another
  144. d2 = do_lookup()
  145. self.assertEqual(LoggingContext.current_context(), 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. # we want this to behave like an asynchronous function
  159. yield run_on_reactor()
  160. raise SynapseError(400, "blah")
  161. return inner_fn()
  162. @defer.inlineCallbacks
  163. def do_lookup():
  164. with LoggingContext() as c1:
  165. c1.name = "c1"
  166. try:
  167. d = obj.fn(1)
  168. self.assertEqual(
  169. LoggingContext.current_context(), LoggingContext.sentinel
  170. )
  171. yield d
  172. self.fail("No exception thrown")
  173. except SynapseError:
  174. pass
  175. self.assertEqual(LoggingContext.current_context(), c1)
  176. obj = Cls()
  177. # set off a deferred which will do a cache lookup
  178. d1 = do_lookup()
  179. self.assertEqual(LoggingContext.current_context(), LoggingContext.sentinel)
  180. return d1
  181. @defer.inlineCallbacks
  182. def test_cache_default_args(self):
  183. class Cls(object):
  184. def __init__(self):
  185. self.mock = mock.Mock()
  186. @descriptors.cached()
  187. def fn(self, arg1, arg2=2, arg3=3):
  188. return self.mock(arg1, arg2, arg3)
  189. obj = Cls()
  190. obj.mock.return_value = "fish"
  191. r = yield obj.fn(1, 2, 3)
  192. self.assertEqual(r, "fish")
  193. obj.mock.assert_called_once_with(1, 2, 3)
  194. obj.mock.reset_mock()
  195. # a call with same params shouldn't call the mock again
  196. r = yield obj.fn(1, 2)
  197. self.assertEqual(r, "fish")
  198. obj.mock.assert_not_called()
  199. obj.mock.reset_mock()
  200. # a call with different params should call the mock again
  201. obj.mock.return_value = "chips"
  202. r = yield obj.fn(2, 3)
  203. self.assertEqual(r, "chips")
  204. obj.mock.assert_called_once_with(2, 3, 3)
  205. obj.mock.reset_mock()
  206. # the two values should now be cached
  207. r = yield obj.fn(1, 2)
  208. self.assertEqual(r, "fish")
  209. r = yield obj.fn(2, 3)
  210. self.assertEqual(r, "chips")
  211. obj.mock.assert_not_called()
  212. class CachedListDescriptorTestCase(unittest.TestCase):
  213. @defer.inlineCallbacks
  214. def test_cache(self):
  215. class Cls(object):
  216. def __init__(self):
  217. self.mock = mock.Mock()
  218. @descriptors.cached()
  219. def fn(self, arg1, arg2):
  220. pass
  221. @descriptors.cachedList("fn", "args1", inlineCallbacks=True)
  222. def list_fn(self, args1, arg2):
  223. assert LoggingContext.current_context().request == "c1"
  224. # we want this to behave like an asynchronous function
  225. yield run_on_reactor()
  226. assert LoggingContext.current_context().request == "c1"
  227. defer.returnValue(self.mock(args1, arg2))
  228. with LoggingContext() as c1:
  229. c1.request = "c1"
  230. obj = Cls()
  231. obj.mock.return_value = {10: "fish", 20: "chips"}
  232. d1 = obj.list_fn([10, 20], 2)
  233. self.assertEqual(LoggingContext.current_context(), LoggingContext.sentinel)
  234. r = yield d1
  235. self.assertEqual(LoggingContext.current_context(), c1)
  236. obj.mock.assert_called_once_with([10, 20], 2)
  237. self.assertEqual(r, {10: "fish", 20: "chips"})
  238. obj.mock.reset_mock()
  239. # a call with different params should call the mock again
  240. obj.mock.return_value = {30: "peas"}
  241. r = yield obj.list_fn([20, 30], 2)
  242. obj.mock.assert_called_once_with([30], 2)
  243. self.assertEqual(r, {20: "chips", 30: "peas"})
  244. obj.mock.reset_mock()
  245. # all the values should now be cached
  246. r = yield obj.fn(10, 2)
  247. self.assertEqual(r, "fish")
  248. r = yield obj.fn(20, 2)
  249. self.assertEqual(r, "chips")
  250. r = yield obj.fn(30, 2)
  251. self.assertEqual(r, "peas")
  252. r = yield obj.list_fn([10, 20, 30], 2)
  253. obj.mock.assert_not_called()
  254. self.assertEqual(r, {10: "fish", 20: "chips", 30: "peas"})
  255. @defer.inlineCallbacks
  256. def test_invalidate(self):
  257. """Make sure that invalidation callbacks are called."""
  258. class Cls(object):
  259. def __init__(self):
  260. self.mock = mock.Mock()
  261. @descriptors.cached()
  262. def fn(self, arg1, arg2):
  263. pass
  264. @descriptors.cachedList("fn", "args1", inlineCallbacks=True)
  265. def list_fn(self, args1, arg2):
  266. # we want this to behave like an asynchronous function
  267. yield run_on_reactor()
  268. defer.returnValue(self.mock(args1, arg2))
  269. obj = Cls()
  270. invalidate0 = mock.Mock()
  271. invalidate1 = mock.Mock()
  272. # cache miss
  273. obj.mock.return_value = {10: "fish", 20: "chips"}
  274. r1 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0)
  275. obj.mock.assert_called_once_with([10, 20], 2)
  276. self.assertEqual(r1, {10: "fish", 20: "chips"})
  277. obj.mock.reset_mock()
  278. # cache hit
  279. r2 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1)
  280. obj.mock.assert_not_called()
  281. self.assertEqual(r2, {10: "fish", 20: "chips"})
  282. invalidate0.assert_not_called()
  283. invalidate1.assert_not_called()
  284. # now if we invalidate the keys, both invalidations should get called
  285. obj.fn.invalidate((10, 2))
  286. invalidate0.assert_called_once()
  287. invalidate1.assert_called_once()