test_descriptors.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. SENTINEL_CONTEXT,
  23. LoggingContext,
  24. PreserveLoggingContext,
  25. current_context,
  26. make_deferred_yieldable,
  27. )
  28. from synapse.util.caches import descriptors
  29. from synapse.util.caches.descriptors import cached
  30. from tests import unittest
  31. logger = logging.getLogger(__name__)
  32. def run_on_reactor():
  33. d = defer.Deferred()
  34. reactor.callLater(0, d.callback, 0)
  35. return make_deferred_yieldable(d)
  36. class CacheTestCase(unittest.TestCase):
  37. def test_invalidate_all(self):
  38. cache = descriptors.Cache("testcache")
  39. callback_record = [False, False]
  40. def record_callback(idx):
  41. callback_record[idx] = True
  42. # add a couple of pending entries
  43. d1 = defer.Deferred()
  44. cache.set("key1", d1, partial(record_callback, 0))
  45. d2 = defer.Deferred()
  46. cache.set("key2", d2, partial(record_callback, 1))
  47. # lookup should return observable deferreds
  48. self.assertFalse(cache.get("key1").has_called())
  49. self.assertFalse(cache.get("key2").has_called())
  50. # let one of the lookups complete
  51. d2.callback("result2")
  52. # for now at least, the cache will return real results rather than an
  53. # observabledeferred
  54. self.assertEqual(cache.get("key2"), "result2")
  55. # now do the invalidation
  56. cache.invalidate_all()
  57. # lookup should return none
  58. self.assertIsNone(cache.get("key1", None))
  59. self.assertIsNone(cache.get("key2", None))
  60. # both callbacks should have been callbacked
  61. self.assertTrue(callback_record[0], "Invalidation callback for key1 not called")
  62. self.assertTrue(callback_record[1], "Invalidation callback for key2 not called")
  63. # letting the other lookup complete should do nothing
  64. d1.callback("result1")
  65. self.assertIsNone(cache.get("key1", None))
  66. class DescriptorTestCase(unittest.TestCase):
  67. @defer.inlineCallbacks
  68. def test_cache(self):
  69. class Cls(object):
  70. def __init__(self):
  71. self.mock = mock.Mock()
  72. @descriptors.cached()
  73. def fn(self, arg1, arg2):
  74. return self.mock(arg1, arg2)
  75. obj = Cls()
  76. obj.mock.return_value = "fish"
  77. r = yield obj.fn(1, 2)
  78. self.assertEqual(r, "fish")
  79. obj.mock.assert_called_once_with(1, 2)
  80. obj.mock.reset_mock()
  81. # a call with different params should call the mock again
  82. obj.mock.return_value = "chips"
  83. r = yield obj.fn(1, 3)
  84. self.assertEqual(r, "chips")
  85. obj.mock.assert_called_once_with(1, 3)
  86. obj.mock.reset_mock()
  87. # the two values should now be cached
  88. r = yield obj.fn(1, 2)
  89. self.assertEqual(r, "fish")
  90. r = yield obj.fn(1, 3)
  91. self.assertEqual(r, "chips")
  92. obj.mock.assert_not_called()
  93. @defer.inlineCallbacks
  94. def test_cache_num_args(self):
  95. """Only the first num_args arguments should matter to the cache"""
  96. class Cls(object):
  97. def __init__(self):
  98. self.mock = mock.Mock()
  99. @descriptors.cached(num_args=1)
  100. def fn(self, arg1, arg2):
  101. return self.mock(arg1, arg2)
  102. obj = Cls()
  103. obj.mock.return_value = "fish"
  104. r = yield obj.fn(1, 2)
  105. self.assertEqual(r, "fish")
  106. obj.mock.assert_called_once_with(1, 2)
  107. obj.mock.reset_mock()
  108. # a call with different params should call the mock again
  109. obj.mock.return_value = "chips"
  110. r = yield obj.fn(2, 3)
  111. self.assertEqual(r, "chips")
  112. obj.mock.assert_called_once_with(2, 3)
  113. obj.mock.reset_mock()
  114. # the two values should now be cached; we should be able to vary
  115. # the second argument and still get the cached result.
  116. r = yield obj.fn(1, 4)
  117. self.assertEqual(r, "fish")
  118. r = yield obj.fn(2, 5)
  119. self.assertEqual(r, "chips")
  120. obj.mock.assert_not_called()
  121. def test_cache_with_sync_exception(self):
  122. """If the wrapped function throws synchronously, things should continue to work
  123. """
  124. class Cls(object):
  125. @cached()
  126. def fn(self, arg1):
  127. raise SynapseError(100, "mai spoon iz too big!!1")
  128. obj = Cls()
  129. # this should fail immediately
  130. d = obj.fn(1)
  131. self.failureResultOf(d, SynapseError)
  132. # ... leaving the cache empty
  133. self.assertEqual(len(obj.fn.cache.cache), 0)
  134. # and a second call should result in a second exception
  135. d = obj.fn(1)
  136. self.failureResultOf(d, SynapseError)
  137. def test_cache_logcontexts(self):
  138. """Check that logcontexts are set and restored correctly when
  139. using the cache."""
  140. complete_lookup = defer.Deferred()
  141. class Cls(object):
  142. @descriptors.cached()
  143. def fn(self, arg1):
  144. @defer.inlineCallbacks
  145. def inner_fn():
  146. with PreserveLoggingContext():
  147. yield complete_lookup
  148. return 1
  149. return inner_fn()
  150. @defer.inlineCallbacks
  151. def do_lookup():
  152. with LoggingContext() as c1:
  153. c1.name = "c1"
  154. r = yield obj.fn(1)
  155. self.assertEqual(current_context(), c1)
  156. return r
  157. def check_result(r):
  158. self.assertEqual(r, 1)
  159. obj = Cls()
  160. # set off a deferred which will do a cache lookup
  161. d1 = do_lookup()
  162. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  163. d1.addCallback(check_result)
  164. # and another
  165. d2 = do_lookup()
  166. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  167. d2.addCallback(check_result)
  168. # let the lookup complete
  169. complete_lookup.callback(None)
  170. return defer.gatherResults([d1, d2])
  171. def test_cache_logcontexts_with_exception(self):
  172. """Check that the cache sets and restores logcontexts correctly when
  173. the lookup function throws an exception"""
  174. class Cls(object):
  175. @descriptors.cached()
  176. def fn(self, arg1):
  177. @defer.inlineCallbacks
  178. def inner_fn():
  179. # we want this to behave like an asynchronous function
  180. yield run_on_reactor()
  181. raise SynapseError(400, "blah")
  182. return inner_fn()
  183. @defer.inlineCallbacks
  184. def do_lookup():
  185. with LoggingContext() as c1:
  186. c1.name = "c1"
  187. try:
  188. d = obj.fn(1)
  189. self.assertEqual(
  190. current_context(), SENTINEL_CONTEXT,
  191. )
  192. yield d
  193. self.fail("No exception thrown")
  194. except SynapseError:
  195. pass
  196. self.assertEqual(current_context(), c1)
  197. # the cache should now be empty
  198. self.assertEqual(len(obj.fn.cache.cache), 0)
  199. obj = Cls()
  200. # set off a deferred which will do a cache lookup
  201. d1 = do_lookup()
  202. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  203. return d1
  204. @defer.inlineCallbacks
  205. def test_cache_default_args(self):
  206. class Cls(object):
  207. def __init__(self):
  208. self.mock = mock.Mock()
  209. @descriptors.cached()
  210. def fn(self, arg1, arg2=2, arg3=3):
  211. return self.mock(arg1, arg2, arg3)
  212. obj = Cls()
  213. obj.mock.return_value = "fish"
  214. r = yield obj.fn(1, 2, 3)
  215. self.assertEqual(r, "fish")
  216. obj.mock.assert_called_once_with(1, 2, 3)
  217. obj.mock.reset_mock()
  218. # a call with same params shouldn't call the mock again
  219. r = yield obj.fn(1, 2)
  220. self.assertEqual(r, "fish")
  221. obj.mock.assert_not_called()
  222. obj.mock.reset_mock()
  223. # a call with different params should call the mock again
  224. obj.mock.return_value = "chips"
  225. r = yield obj.fn(2, 3)
  226. self.assertEqual(r, "chips")
  227. obj.mock.assert_called_once_with(2, 3, 3)
  228. obj.mock.reset_mock()
  229. # the two values should now be cached
  230. r = yield obj.fn(1, 2)
  231. self.assertEqual(r, "fish")
  232. r = yield obj.fn(2, 3)
  233. self.assertEqual(r, "chips")
  234. obj.mock.assert_not_called()
  235. def test_cache_iterable(self):
  236. class Cls(object):
  237. def __init__(self):
  238. self.mock = mock.Mock()
  239. @descriptors.cached(iterable=True)
  240. def fn(self, arg1, arg2):
  241. return self.mock(arg1, arg2)
  242. obj = Cls()
  243. obj.mock.return_value = ["spam", "eggs"]
  244. r = obj.fn(1, 2)
  245. self.assertEqual(r.result, ["spam", "eggs"])
  246. obj.mock.assert_called_once_with(1, 2)
  247. obj.mock.reset_mock()
  248. # a call with different params should call the mock again
  249. obj.mock.return_value = ["chips"]
  250. r = obj.fn(1, 3)
  251. self.assertEqual(r.result, ["chips"])
  252. obj.mock.assert_called_once_with(1, 3)
  253. obj.mock.reset_mock()
  254. # the two values should now be cached
  255. self.assertEqual(len(obj.fn.cache.cache), 3)
  256. r = obj.fn(1, 2)
  257. self.assertEqual(r.result, ["spam", "eggs"])
  258. r = obj.fn(1, 3)
  259. self.assertEqual(r.result, ["chips"])
  260. obj.mock.assert_not_called()
  261. def test_cache_iterable_with_sync_exception(self):
  262. """If the wrapped function throws synchronously, things should continue to work
  263. """
  264. class Cls(object):
  265. @descriptors.cached(iterable=True)
  266. def fn(self, arg1):
  267. raise SynapseError(100, "mai spoon iz too big!!1")
  268. obj = Cls()
  269. # this should fail immediately
  270. d = obj.fn(1)
  271. self.failureResultOf(d, SynapseError)
  272. # ... leaving the cache empty
  273. self.assertEqual(len(obj.fn.cache.cache), 0)
  274. # and a second call should result in a second exception
  275. d = obj.fn(1)
  276. self.failureResultOf(d, SynapseError)
  277. class CachedListDescriptorTestCase(unittest.TestCase):
  278. @defer.inlineCallbacks
  279. def test_cache(self):
  280. class Cls(object):
  281. def __init__(self):
  282. self.mock = mock.Mock()
  283. @descriptors.cached()
  284. def fn(self, arg1, arg2):
  285. pass
  286. @descriptors.cachedList("fn", "args1", inlineCallbacks=True)
  287. def list_fn(self, args1, arg2):
  288. assert current_context().request == "c1"
  289. # we want this to behave like an asynchronous function
  290. yield run_on_reactor()
  291. assert current_context().request == "c1"
  292. return self.mock(args1, arg2)
  293. with LoggingContext() as c1:
  294. c1.request = "c1"
  295. obj = Cls()
  296. obj.mock.return_value = {10: "fish", 20: "chips"}
  297. d1 = obj.list_fn([10, 20], 2)
  298. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  299. r = yield d1
  300. self.assertEqual(current_context(), c1)
  301. obj.mock.assert_called_once_with([10, 20], 2)
  302. self.assertEqual(r, {10: "fish", 20: "chips"})
  303. obj.mock.reset_mock()
  304. # a call with different params should call the mock again
  305. obj.mock.return_value = {30: "peas"}
  306. r = yield obj.list_fn([20, 30], 2)
  307. obj.mock.assert_called_once_with([30], 2)
  308. self.assertEqual(r, {20: "chips", 30: "peas"})
  309. obj.mock.reset_mock()
  310. # all the values should now be cached
  311. r = yield obj.fn(10, 2)
  312. self.assertEqual(r, "fish")
  313. r = yield obj.fn(20, 2)
  314. self.assertEqual(r, "chips")
  315. r = yield obj.fn(30, 2)
  316. self.assertEqual(r, "peas")
  317. r = yield obj.list_fn([10, 20, 30], 2)
  318. obj.mock.assert_not_called()
  319. self.assertEqual(r, {10: "fish", 20: "chips", 30: "peas"})
  320. @defer.inlineCallbacks
  321. def test_invalidate(self):
  322. """Make sure that invalidation callbacks are called."""
  323. class Cls(object):
  324. def __init__(self):
  325. self.mock = mock.Mock()
  326. @descriptors.cached()
  327. def fn(self, arg1, arg2):
  328. pass
  329. @descriptors.cachedList("fn", "args1", inlineCallbacks=True)
  330. def list_fn(self, args1, arg2):
  331. # we want this to behave like an asynchronous function
  332. yield run_on_reactor()
  333. return self.mock(args1, arg2)
  334. obj = Cls()
  335. invalidate0 = mock.Mock()
  336. invalidate1 = mock.Mock()
  337. # cache miss
  338. obj.mock.return_value = {10: "fish", 20: "chips"}
  339. r1 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0)
  340. obj.mock.assert_called_once_with([10, 20], 2)
  341. self.assertEqual(r1, {10: "fish", 20: "chips"})
  342. obj.mock.reset_mock()
  343. # cache hit
  344. r2 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1)
  345. obj.mock.assert_not_called()
  346. self.assertEqual(r2, {10: "fish", 20: "chips"})
  347. invalidate0.assert_not_called()
  348. invalidate1.assert_not_called()
  349. # now if we invalidate the keys, both invalidations should get called
  350. obj.fn.invalidate((10, 2))
  351. invalidate0.assert_called_once()
  352. invalidate1.assert_called_once()