test_descriptors.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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 typing import Set
  18. from unittest 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, lru_cache
  30. from tests import unittest
  31. from tests.test_utils import get_awaitable_result
  32. logger = logging.getLogger(__name__)
  33. class LruCacheDecoratorTestCase(unittest.TestCase):
  34. def test_base(self):
  35. class Cls:
  36. def __init__(self):
  37. self.mock = mock.Mock()
  38. @lru_cache()
  39. def fn(self, arg1, arg2):
  40. return self.mock(arg1, arg2)
  41. obj = Cls()
  42. obj.mock.return_value = "fish"
  43. r = obj.fn(1, 2)
  44. self.assertEqual(r, "fish")
  45. obj.mock.assert_called_once_with(1, 2)
  46. obj.mock.reset_mock()
  47. # a call with different params should call the mock again
  48. obj.mock.return_value = "chips"
  49. r = obj.fn(1, 3)
  50. self.assertEqual(r, "chips")
  51. obj.mock.assert_called_once_with(1, 3)
  52. obj.mock.reset_mock()
  53. # the two values should now be cached
  54. r = obj.fn(1, 2)
  55. self.assertEqual(r, "fish")
  56. r = obj.fn(1, 3)
  57. self.assertEqual(r, "chips")
  58. obj.mock.assert_not_called()
  59. def run_on_reactor():
  60. d = defer.Deferred()
  61. reactor.callLater(0, d.callback, 0)
  62. return make_deferred_yieldable(d)
  63. class DescriptorTestCase(unittest.TestCase):
  64. @defer.inlineCallbacks
  65. def test_cache(self):
  66. class Cls:
  67. def __init__(self):
  68. self.mock = mock.Mock()
  69. @descriptors.cached()
  70. def fn(self, arg1, arg2):
  71. return self.mock(arg1, arg2)
  72. obj = Cls()
  73. obj.mock.return_value = "fish"
  74. r = yield obj.fn(1, 2)
  75. self.assertEqual(r, "fish")
  76. obj.mock.assert_called_once_with(1, 2)
  77. obj.mock.reset_mock()
  78. # a call with different params should call the mock again
  79. obj.mock.return_value = "chips"
  80. r = yield obj.fn(1, 3)
  81. self.assertEqual(r, "chips")
  82. obj.mock.assert_called_once_with(1, 3)
  83. obj.mock.reset_mock()
  84. # the two values should now be cached
  85. r = yield obj.fn(1, 2)
  86. self.assertEqual(r, "fish")
  87. r = yield obj.fn(1, 3)
  88. self.assertEqual(r, "chips")
  89. obj.mock.assert_not_called()
  90. @defer.inlineCallbacks
  91. def test_cache_num_args(self):
  92. """Only the first num_args arguments should matter to the cache"""
  93. class Cls:
  94. def __init__(self):
  95. self.mock = mock.Mock()
  96. @descriptors.cached(num_args=1)
  97. def fn(self, arg1, arg2):
  98. return self.mock(arg1, arg2)
  99. obj = Cls()
  100. obj.mock.return_value = "fish"
  101. r = yield obj.fn(1, 2)
  102. self.assertEqual(r, "fish")
  103. obj.mock.assert_called_once_with(1, 2)
  104. obj.mock.reset_mock()
  105. # a call with different params should call the mock again
  106. obj.mock.return_value = "chips"
  107. r = yield obj.fn(2, 3)
  108. self.assertEqual(r, "chips")
  109. obj.mock.assert_called_once_with(2, 3)
  110. obj.mock.reset_mock()
  111. # the two values should now be cached; we should be able to vary
  112. # the second argument and still get the cached result.
  113. r = yield obj.fn(1, 4)
  114. self.assertEqual(r, "fish")
  115. r = yield obj.fn(2, 5)
  116. self.assertEqual(r, "chips")
  117. obj.mock.assert_not_called()
  118. def test_cache_with_sync_exception(self):
  119. """If the wrapped function throws synchronously, things should continue to work"""
  120. class Cls:
  121. @cached()
  122. def fn(self, arg1):
  123. raise SynapseError(100, "mai spoon iz too big!!1")
  124. obj = Cls()
  125. # this should fail immediately
  126. d = obj.fn(1)
  127. self.failureResultOf(d, SynapseError)
  128. # ... leaving the cache empty
  129. self.assertEqual(len(obj.fn.cache.cache), 0)
  130. # and a second call should result in a second exception
  131. d = obj.fn(1)
  132. self.failureResultOf(d, SynapseError)
  133. def test_cache_with_async_exception(self):
  134. """The wrapped function returns a failure"""
  135. class Cls:
  136. result = None
  137. call_count = 0
  138. @cached()
  139. def fn(self, arg1):
  140. self.call_count += 1
  141. return self.result
  142. obj = Cls()
  143. callbacks = set() # type: Set[str]
  144. # set off an asynchronous request
  145. obj.result = origin_d = defer.Deferred()
  146. d1 = obj.fn(1, on_invalidate=lambda: callbacks.add("d1"))
  147. self.assertFalse(d1.called)
  148. # a second request should also return a deferred, but should not call the
  149. # function itself.
  150. d2 = obj.fn(1, on_invalidate=lambda: callbacks.add("d2"))
  151. self.assertFalse(d2.called)
  152. self.assertEqual(obj.call_count, 1)
  153. # no callbacks yet
  154. self.assertEqual(callbacks, set())
  155. # the original request fails
  156. e = Exception("bzz")
  157. origin_d.errback(e)
  158. # ... which should cause the lookups to fail similarly
  159. self.assertIs(self.failureResultOf(d1, Exception).value, e)
  160. self.assertIs(self.failureResultOf(d2, Exception).value, e)
  161. # ... and the callbacks to have been, uh, called.
  162. self.assertEqual(callbacks, {"d1", "d2"})
  163. # ... leaving the cache empty
  164. self.assertEqual(len(obj.fn.cache.cache), 0)
  165. # and a second call should work as normal
  166. obj.result = defer.succeed(100)
  167. d3 = obj.fn(1)
  168. self.assertEqual(self.successResultOf(d3), 100)
  169. self.assertEqual(obj.call_count, 2)
  170. def test_cache_logcontexts(self):
  171. """Check that logcontexts are set and restored correctly when
  172. using the cache."""
  173. complete_lookup = defer.Deferred()
  174. class Cls:
  175. @descriptors.cached()
  176. def fn(self, arg1):
  177. @defer.inlineCallbacks
  178. def inner_fn():
  179. with PreserveLoggingContext():
  180. yield complete_lookup
  181. return 1
  182. return inner_fn()
  183. @defer.inlineCallbacks
  184. def do_lookup():
  185. with LoggingContext("c1") as c1:
  186. r = yield obj.fn(1)
  187. self.assertEqual(current_context(), c1)
  188. return r
  189. def check_result(r):
  190. self.assertEqual(r, 1)
  191. obj = Cls()
  192. # set off a deferred which will do a cache lookup
  193. d1 = do_lookup()
  194. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  195. d1.addCallback(check_result)
  196. # and another
  197. d2 = do_lookup()
  198. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  199. d2.addCallback(check_result)
  200. # let the lookup complete
  201. complete_lookup.callback(None)
  202. return defer.gatherResults([d1, d2])
  203. def test_cache_logcontexts_with_exception(self):
  204. """Check that the cache sets and restores logcontexts correctly when
  205. the lookup function throws an exception"""
  206. class Cls:
  207. @descriptors.cached()
  208. def fn(self, arg1):
  209. @defer.inlineCallbacks
  210. def inner_fn():
  211. # we want this to behave like an asynchronous function
  212. yield run_on_reactor()
  213. raise SynapseError(400, "blah")
  214. return inner_fn()
  215. @defer.inlineCallbacks
  216. def do_lookup():
  217. with LoggingContext("c1") as c1:
  218. try:
  219. d = obj.fn(1)
  220. self.assertEqual(
  221. current_context(),
  222. SENTINEL_CONTEXT,
  223. )
  224. yield d
  225. self.fail("No exception thrown")
  226. except SynapseError:
  227. pass
  228. self.assertEqual(current_context(), c1)
  229. # the cache should now be empty
  230. self.assertEqual(len(obj.fn.cache.cache), 0)
  231. obj = Cls()
  232. # set off a deferred which will do a cache lookup
  233. d1 = do_lookup()
  234. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  235. return d1
  236. @defer.inlineCallbacks
  237. def test_cache_default_args(self):
  238. class Cls:
  239. def __init__(self):
  240. self.mock = mock.Mock()
  241. @descriptors.cached()
  242. def fn(self, arg1, arg2=2, arg3=3):
  243. return self.mock(arg1, arg2, arg3)
  244. obj = Cls()
  245. obj.mock.return_value = "fish"
  246. r = yield obj.fn(1, 2, 3)
  247. self.assertEqual(r, "fish")
  248. obj.mock.assert_called_once_with(1, 2, 3)
  249. obj.mock.reset_mock()
  250. # a call with same params shouldn't call the mock again
  251. r = yield obj.fn(1, 2)
  252. self.assertEqual(r, "fish")
  253. obj.mock.assert_not_called()
  254. obj.mock.reset_mock()
  255. # a call with different params should call the mock again
  256. obj.mock.return_value = "chips"
  257. r = yield obj.fn(2, 3)
  258. self.assertEqual(r, "chips")
  259. obj.mock.assert_called_once_with(2, 3, 3)
  260. obj.mock.reset_mock()
  261. # the two values should now be cached
  262. r = yield obj.fn(1, 2)
  263. self.assertEqual(r, "fish")
  264. r = yield obj.fn(2, 3)
  265. self.assertEqual(r, "chips")
  266. obj.mock.assert_not_called()
  267. def test_cache_iterable(self):
  268. class Cls:
  269. def __init__(self):
  270. self.mock = mock.Mock()
  271. @descriptors.cached(iterable=True)
  272. def fn(self, arg1, arg2):
  273. return self.mock(arg1, arg2)
  274. obj = Cls()
  275. obj.mock.return_value = ["spam", "eggs"]
  276. r = obj.fn(1, 2)
  277. self.assertEqual(r.result, ["spam", "eggs"])
  278. obj.mock.assert_called_once_with(1, 2)
  279. obj.mock.reset_mock()
  280. # a call with different params should call the mock again
  281. obj.mock.return_value = ["chips"]
  282. r = obj.fn(1, 3)
  283. self.assertEqual(r.result, ["chips"])
  284. obj.mock.assert_called_once_with(1, 3)
  285. obj.mock.reset_mock()
  286. # the two values should now be cached
  287. self.assertEqual(len(obj.fn.cache.cache), 3)
  288. r = obj.fn(1, 2)
  289. self.assertEqual(r.result, ["spam", "eggs"])
  290. r = obj.fn(1, 3)
  291. self.assertEqual(r.result, ["chips"])
  292. obj.mock.assert_not_called()
  293. def test_cache_iterable_with_sync_exception(self):
  294. """If the wrapped function throws synchronously, things should continue to work"""
  295. class Cls:
  296. @descriptors.cached(iterable=True)
  297. def fn(self, arg1):
  298. raise SynapseError(100, "mai spoon iz too big!!1")
  299. obj = Cls()
  300. # this should fail immediately
  301. d = obj.fn(1)
  302. self.failureResultOf(d, SynapseError)
  303. # ... leaving the cache empty
  304. self.assertEqual(len(obj.fn.cache.cache), 0)
  305. # and a second call should result in a second exception
  306. d = obj.fn(1)
  307. self.failureResultOf(d, SynapseError)
  308. def test_invalidate_cascade(self):
  309. """Invalidations should cascade up through cache contexts"""
  310. class Cls:
  311. @cached(cache_context=True)
  312. async def func1(self, key, cache_context):
  313. return await self.func2(key, on_invalidate=cache_context.invalidate)
  314. @cached(cache_context=True)
  315. async def func2(self, key, cache_context):
  316. return self.func3(key, on_invalidate=cache_context.invalidate)
  317. @lru_cache(cache_context=True)
  318. def func3(self, key, cache_context):
  319. self.invalidate = cache_context.invalidate
  320. return 42
  321. obj = Cls()
  322. top_invalidate = mock.Mock()
  323. r = get_awaitable_result(obj.func1("k1", on_invalidate=top_invalidate))
  324. self.assertEqual(r, 42)
  325. obj.invalidate()
  326. top_invalidate.assert_called_once()
  327. class CacheDecoratorTestCase(unittest.HomeserverTestCase):
  328. """More tests for @cached
  329. The following is a set of tests that got lost in a different file for a while.
  330. There are probably duplicates of the tests in DescriptorTestCase. Ideally the
  331. duplicates would be removed and the two sets of classes combined.
  332. """
  333. @defer.inlineCallbacks
  334. def test_passthrough(self):
  335. class A:
  336. @cached()
  337. def func(self, key):
  338. return key
  339. a = A()
  340. self.assertEquals((yield a.func("foo")), "foo")
  341. self.assertEquals((yield a.func("bar")), "bar")
  342. @defer.inlineCallbacks
  343. def test_hit(self):
  344. callcount = [0]
  345. class A:
  346. @cached()
  347. def func(self, key):
  348. callcount[0] += 1
  349. return key
  350. a = A()
  351. yield a.func("foo")
  352. self.assertEquals(callcount[0], 1)
  353. self.assertEquals((yield a.func("foo")), "foo")
  354. self.assertEquals(callcount[0], 1)
  355. @defer.inlineCallbacks
  356. def test_invalidate(self):
  357. callcount = [0]
  358. class A:
  359. @cached()
  360. def func(self, key):
  361. callcount[0] += 1
  362. return key
  363. a = A()
  364. yield a.func("foo")
  365. self.assertEquals(callcount[0], 1)
  366. a.func.invalidate(("foo",))
  367. yield a.func("foo")
  368. self.assertEquals(callcount[0], 2)
  369. def test_invalidate_missing(self):
  370. class A:
  371. @cached()
  372. def func(self, key):
  373. return key
  374. A().func.invalidate(("what",))
  375. @defer.inlineCallbacks
  376. def test_max_entries(self):
  377. callcount = [0]
  378. class A:
  379. @cached(max_entries=10)
  380. def func(self, key):
  381. callcount[0] += 1
  382. return key
  383. a = A()
  384. for k in range(0, 12):
  385. yield a.func(k)
  386. self.assertEquals(callcount[0], 12)
  387. # There must have been at least 2 evictions, meaning if we calculate
  388. # all 12 values again, we must get called at least 2 more times
  389. for k in range(0, 12):
  390. yield a.func(k)
  391. self.assertTrue(
  392. callcount[0] >= 14, msg="Expected callcount >= 14, got %d" % (callcount[0])
  393. )
  394. def test_prefill(self):
  395. callcount = [0]
  396. d = defer.succeed(123)
  397. class A:
  398. @cached()
  399. def func(self, key):
  400. callcount[0] += 1
  401. return d
  402. a = A()
  403. a.func.prefill(("foo",), 456)
  404. self.assertEquals(a.func("foo").result, 456)
  405. self.assertEquals(callcount[0], 0)
  406. @defer.inlineCallbacks
  407. def test_invalidate_context(self):
  408. callcount = [0]
  409. callcount2 = [0]
  410. class A:
  411. @cached()
  412. def func(self, key):
  413. callcount[0] += 1
  414. return key
  415. @cached(cache_context=True)
  416. def func2(self, key, cache_context):
  417. callcount2[0] += 1
  418. return self.func(key, on_invalidate=cache_context.invalidate)
  419. a = A()
  420. yield a.func2("foo")
  421. self.assertEquals(callcount[0], 1)
  422. self.assertEquals(callcount2[0], 1)
  423. a.func.invalidate(("foo",))
  424. yield a.func("foo")
  425. self.assertEquals(callcount[0], 2)
  426. self.assertEquals(callcount2[0], 1)
  427. yield a.func2("foo")
  428. self.assertEquals(callcount[0], 2)
  429. self.assertEquals(callcount2[0], 2)
  430. @defer.inlineCallbacks
  431. def test_eviction_context(self):
  432. callcount = [0]
  433. callcount2 = [0]
  434. class A:
  435. @cached(max_entries=2)
  436. def func(self, key):
  437. callcount[0] += 1
  438. return key
  439. @cached(cache_context=True)
  440. def func2(self, key, cache_context):
  441. callcount2[0] += 1
  442. return self.func(key, on_invalidate=cache_context.invalidate)
  443. a = A()
  444. yield a.func2("foo")
  445. yield a.func2("foo2")
  446. self.assertEquals(callcount[0], 2)
  447. self.assertEquals(callcount2[0], 2)
  448. yield a.func2("foo")
  449. self.assertEquals(callcount[0], 2)
  450. self.assertEquals(callcount2[0], 2)
  451. yield a.func("foo3")
  452. self.assertEquals(callcount[0], 3)
  453. self.assertEquals(callcount2[0], 2)
  454. yield a.func2("foo")
  455. self.assertEquals(callcount[0], 4)
  456. self.assertEquals(callcount2[0], 3)
  457. @defer.inlineCallbacks
  458. def test_double_get(self):
  459. callcount = [0]
  460. callcount2 = [0]
  461. class A:
  462. @cached()
  463. def func(self, key):
  464. callcount[0] += 1
  465. return key
  466. @cached(cache_context=True)
  467. def func2(self, key, cache_context):
  468. callcount2[0] += 1
  469. return self.func(key, on_invalidate=cache_context.invalidate)
  470. a = A()
  471. a.func2.cache.cache = mock.Mock(wraps=a.func2.cache.cache)
  472. yield a.func2("foo")
  473. self.assertEquals(callcount[0], 1)
  474. self.assertEquals(callcount2[0], 1)
  475. a.func2.invalidate(("foo",))
  476. self.assertEquals(a.func2.cache.cache.pop.call_count, 1)
  477. yield a.func2("foo")
  478. a.func2.invalidate(("foo",))
  479. self.assertEquals(a.func2.cache.cache.pop.call_count, 2)
  480. self.assertEquals(callcount[0], 1)
  481. self.assertEquals(callcount2[0], 2)
  482. a.func.invalidate(("foo",))
  483. self.assertEquals(a.func2.cache.cache.pop.call_count, 3)
  484. yield a.func("foo")
  485. self.assertEquals(callcount[0], 2)
  486. self.assertEquals(callcount2[0], 2)
  487. yield a.func2("foo")
  488. self.assertEquals(callcount[0], 2)
  489. self.assertEquals(callcount2[0], 3)
  490. class CachedListDescriptorTestCase(unittest.TestCase):
  491. @defer.inlineCallbacks
  492. def test_cache(self):
  493. class Cls:
  494. def __init__(self):
  495. self.mock = mock.Mock()
  496. @descriptors.cached()
  497. def fn(self, arg1, arg2):
  498. pass
  499. @descriptors.cachedList("fn", "args1")
  500. async def list_fn(self, args1, arg2):
  501. assert current_context().name == "c1"
  502. # we want this to behave like an asynchronous function
  503. await run_on_reactor()
  504. assert current_context().name == "c1"
  505. return self.mock(args1, arg2)
  506. with LoggingContext("c1") as c1:
  507. obj = Cls()
  508. obj.mock.return_value = {10: "fish", 20: "chips"}
  509. d1 = obj.list_fn([10, 20], 2)
  510. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  511. r = yield d1
  512. self.assertEqual(current_context(), c1)
  513. obj.mock.assert_called_once_with([10, 20], 2)
  514. self.assertEqual(r, {10: "fish", 20: "chips"})
  515. obj.mock.reset_mock()
  516. # a call with different params should call the mock again
  517. obj.mock.return_value = {30: "peas"}
  518. r = yield obj.list_fn([20, 30], 2)
  519. obj.mock.assert_called_once_with([30], 2)
  520. self.assertEqual(r, {20: "chips", 30: "peas"})
  521. obj.mock.reset_mock()
  522. # all the values should now be cached
  523. r = yield obj.fn(10, 2)
  524. self.assertEqual(r, "fish")
  525. r = yield obj.fn(20, 2)
  526. self.assertEqual(r, "chips")
  527. r = yield obj.fn(30, 2)
  528. self.assertEqual(r, "peas")
  529. r = yield obj.list_fn([10, 20, 30], 2)
  530. obj.mock.assert_not_called()
  531. self.assertEqual(r, {10: "fish", 20: "chips", 30: "peas"})
  532. @defer.inlineCallbacks
  533. def test_invalidate(self):
  534. """Make sure that invalidation callbacks are called."""
  535. class Cls:
  536. def __init__(self):
  537. self.mock = mock.Mock()
  538. @descriptors.cached()
  539. def fn(self, arg1, arg2):
  540. pass
  541. @descriptors.cachedList("fn", "args1")
  542. async def list_fn(self, args1, arg2):
  543. # we want this to behave like an asynchronous function
  544. await run_on_reactor()
  545. return self.mock(args1, arg2)
  546. obj = Cls()
  547. invalidate0 = mock.Mock()
  548. invalidate1 = mock.Mock()
  549. # cache miss
  550. obj.mock.return_value = {10: "fish", 20: "chips"}
  551. r1 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0)
  552. obj.mock.assert_called_once_with([10, 20], 2)
  553. self.assertEqual(r1, {10: "fish", 20: "chips"})
  554. obj.mock.reset_mock()
  555. # cache hit
  556. r2 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1)
  557. obj.mock.assert_not_called()
  558. self.assertEqual(r2, {10: "fish", 20: "chips"})
  559. invalidate0.assert_not_called()
  560. invalidate1.assert_not_called()
  561. # now if we invalidate the keys, both invalidations should get called
  562. obj.fn.invalidate((10, 2))
  563. invalidate0.assert_called_once()
  564. invalidate1.assert_called_once()