test_descriptors.py 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. # Copyright 2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import Iterable, Set, Tuple, cast
  17. from unittest import mock
  18. from twisted.internet import defer, reactor
  19. from twisted.internet.defer import CancelledError, Deferred
  20. from twisted.internet.interfaces import IReactorTime
  21. from synapse.api.errors import SynapseError
  22. from synapse.logging.context import (
  23. SENTINEL_CONTEXT,
  24. LoggingContext,
  25. PreserveLoggingContext,
  26. current_context,
  27. make_deferred_yieldable,
  28. )
  29. from synapse.util.caches import descriptors
  30. from synapse.util.caches.descriptors import cached, cachedList
  31. from tests import unittest
  32. from tests.test_utils import get_awaitable_result
  33. logger = logging.getLogger(__name__)
  34. def run_on_reactor():
  35. d: "Deferred[int]" = defer.Deferred()
  36. cast(IReactorTime, reactor).callLater(0, d.callback, 0)
  37. return make_deferred_yieldable(d)
  38. class DescriptorTestCase(unittest.TestCase):
  39. @defer.inlineCallbacks
  40. def test_cache(self):
  41. class Cls:
  42. def __init__(self):
  43. self.mock = mock.Mock()
  44. @descriptors.cached()
  45. def fn(self, arg1, arg2):
  46. return self.mock(arg1, arg2)
  47. obj = Cls()
  48. obj.mock.return_value = "fish"
  49. r = yield obj.fn(1, 2)
  50. self.assertEqual(r, "fish")
  51. obj.mock.assert_called_once_with(1, 2)
  52. obj.mock.reset_mock()
  53. # a call with different params should call the mock again
  54. obj.mock.return_value = "chips"
  55. r = yield obj.fn(1, 3)
  56. self.assertEqual(r, "chips")
  57. obj.mock.assert_called_once_with(1, 3)
  58. obj.mock.reset_mock()
  59. # the two values should now be cached
  60. r = yield obj.fn(1, 2)
  61. self.assertEqual(r, "fish")
  62. r = yield obj.fn(1, 3)
  63. self.assertEqual(r, "chips")
  64. obj.mock.assert_not_called()
  65. @defer.inlineCallbacks
  66. def test_cache_num_args(self):
  67. """Only the first num_args arguments should matter to the cache"""
  68. class Cls:
  69. def __init__(self):
  70. self.mock = mock.Mock()
  71. @descriptors.cached(num_args=1)
  72. def fn(self, arg1, arg2):
  73. return self.mock(arg1, arg2)
  74. obj = Cls()
  75. obj.mock.return_value = "fish"
  76. r = yield obj.fn(1, 2)
  77. self.assertEqual(r, "fish")
  78. obj.mock.assert_called_once_with(1, 2)
  79. obj.mock.reset_mock()
  80. # a call with different params should call the mock again
  81. obj.mock.return_value = "chips"
  82. r = yield obj.fn(2, 3)
  83. self.assertEqual(r, "chips")
  84. obj.mock.assert_called_once_with(2, 3)
  85. obj.mock.reset_mock()
  86. # the two values should now be cached; we should be able to vary
  87. # the second argument and still get the cached result.
  88. r = yield obj.fn(1, 4)
  89. self.assertEqual(r, "fish")
  90. r = yield obj.fn(2, 5)
  91. self.assertEqual(r, "chips")
  92. obj.mock.assert_not_called()
  93. @defer.inlineCallbacks
  94. def test_cache_uncached_args(self):
  95. """
  96. Only the arguments not named in uncached_args should matter to the cache
  97. Note that this is identical to test_cache_num_args, but provides the
  98. arguments differently.
  99. """
  100. class Cls:
  101. # Note that it is important that this is not the last argument to
  102. # test behaviour of skipping arguments properly.
  103. @descriptors.cached(uncached_args=("arg2",))
  104. def fn(self, arg1, arg2, arg3):
  105. return self.mock(arg1, arg2, arg3)
  106. def __init__(self):
  107. self.mock = mock.Mock()
  108. obj = Cls()
  109. obj.mock.return_value = "fish"
  110. r = yield obj.fn(1, 2, 3)
  111. self.assertEqual(r, "fish")
  112. obj.mock.assert_called_once_with(1, 2, 3)
  113. obj.mock.reset_mock()
  114. # a call with different params should call the mock again
  115. obj.mock.return_value = "chips"
  116. r = yield obj.fn(2, 3, 4)
  117. self.assertEqual(r, "chips")
  118. obj.mock.assert_called_once_with(2, 3, 4)
  119. obj.mock.reset_mock()
  120. # the two values should now be cached; we should be able to vary
  121. # the second argument and still get the cached result.
  122. r = yield obj.fn(1, 4, 3)
  123. self.assertEqual(r, "fish")
  124. r = yield obj.fn(2, 5, 4)
  125. self.assertEqual(r, "chips")
  126. obj.mock.assert_not_called()
  127. @defer.inlineCallbacks
  128. def test_cache_kwargs(self):
  129. """Test that keyword arguments are treated properly"""
  130. class Cls:
  131. def __init__(self):
  132. self.mock = mock.Mock()
  133. @descriptors.cached()
  134. def fn(self, arg1, kwarg1=2):
  135. return self.mock(arg1, kwarg1=kwarg1)
  136. obj = Cls()
  137. obj.mock.return_value = "fish"
  138. r = yield obj.fn(1, kwarg1=2)
  139. self.assertEqual(r, "fish")
  140. obj.mock.assert_called_once_with(1, kwarg1=2)
  141. obj.mock.reset_mock()
  142. # a call with different params should call the mock again
  143. obj.mock.return_value = "chips"
  144. r = yield obj.fn(1, kwarg1=3)
  145. self.assertEqual(r, "chips")
  146. obj.mock.assert_called_once_with(1, kwarg1=3)
  147. obj.mock.reset_mock()
  148. # the values should now be cached.
  149. r = yield obj.fn(1, kwarg1=2)
  150. self.assertEqual(r, "fish")
  151. # We should be able to not provide kwarg1 and get the cached value back.
  152. r = yield obj.fn(1)
  153. self.assertEqual(r, "fish")
  154. # Keyword arguments can be in any order.
  155. r = yield obj.fn(kwarg1=2, arg1=1)
  156. self.assertEqual(r, "fish")
  157. obj.mock.assert_not_called()
  158. def test_cache_with_sync_exception(self):
  159. """If the wrapped function throws synchronously, things should continue to work"""
  160. class Cls:
  161. @cached()
  162. def fn(self, arg1):
  163. raise SynapseError(100, "mai spoon iz too big!!1")
  164. obj = Cls()
  165. # this should fail immediately
  166. d = obj.fn(1)
  167. self.failureResultOf(d, SynapseError)
  168. # ... leaving the cache empty
  169. self.assertEqual(len(obj.fn.cache.cache), 0)
  170. # and a second call should result in a second exception
  171. d = obj.fn(1)
  172. self.failureResultOf(d, SynapseError)
  173. def test_cache_with_async_exception(self):
  174. """The wrapped function returns a failure"""
  175. class Cls:
  176. result = None
  177. call_count = 0
  178. @cached()
  179. def fn(self, arg1):
  180. self.call_count += 1
  181. return self.result
  182. obj = Cls()
  183. callbacks: Set[str] = set()
  184. # set off an asynchronous request
  185. origin_d: Deferred = defer.Deferred()
  186. obj.result = origin_d
  187. d1 = obj.fn(1, on_invalidate=lambda: callbacks.add("d1"))
  188. self.assertFalse(d1.called)
  189. # a second request should also return a deferred, but should not call the
  190. # function itself.
  191. d2 = obj.fn(1, on_invalidate=lambda: callbacks.add("d2"))
  192. self.assertFalse(d2.called)
  193. self.assertEqual(obj.call_count, 1)
  194. # no callbacks yet
  195. self.assertEqual(callbacks, set())
  196. # the original request fails
  197. e = Exception("bzz")
  198. origin_d.errback(e)
  199. # ... which should cause the lookups to fail similarly
  200. self.assertIs(self.failureResultOf(d1, Exception).value, e)
  201. self.assertIs(self.failureResultOf(d2, Exception).value, e)
  202. # ... and the callbacks to have been, uh, called.
  203. self.assertEqual(callbacks, {"d1", "d2"})
  204. # ... leaving the cache empty
  205. self.assertEqual(len(obj.fn.cache.cache), 0)
  206. # and a second call should work as normal
  207. obj.result = defer.succeed(100)
  208. d3 = obj.fn(1)
  209. self.assertEqual(self.successResultOf(d3), 100)
  210. self.assertEqual(obj.call_count, 2)
  211. def test_cache_logcontexts(self):
  212. """Check that logcontexts are set and restored correctly when
  213. using the cache."""
  214. complete_lookup: Deferred = defer.Deferred()
  215. class Cls:
  216. @descriptors.cached()
  217. def fn(self, arg1):
  218. @defer.inlineCallbacks
  219. def inner_fn():
  220. with PreserveLoggingContext():
  221. yield complete_lookup
  222. return 1
  223. return inner_fn()
  224. @defer.inlineCallbacks
  225. def do_lookup():
  226. with LoggingContext("c1") as c1:
  227. r = yield obj.fn(1)
  228. self.assertEqual(current_context(), c1)
  229. return r
  230. def check_result(r):
  231. self.assertEqual(r, 1)
  232. obj = Cls()
  233. # set off a deferred which will do a cache lookup
  234. d1 = do_lookup()
  235. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  236. d1.addCallback(check_result)
  237. # and another
  238. d2 = do_lookup()
  239. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  240. d2.addCallback(check_result)
  241. # let the lookup complete
  242. complete_lookup.callback(None)
  243. return defer.gatherResults([d1, d2])
  244. def test_cache_logcontexts_with_exception(self):
  245. """Check that the cache sets and restores logcontexts correctly when
  246. the lookup function throws an exception"""
  247. class Cls:
  248. @descriptors.cached()
  249. def fn(self, arg1):
  250. @defer.inlineCallbacks
  251. def inner_fn():
  252. # we want this to behave like an asynchronous function
  253. yield run_on_reactor()
  254. raise SynapseError(400, "blah")
  255. return inner_fn()
  256. @defer.inlineCallbacks
  257. def do_lookup():
  258. with LoggingContext("c1") as c1:
  259. try:
  260. d = obj.fn(1)
  261. self.assertEqual(
  262. current_context(),
  263. SENTINEL_CONTEXT,
  264. )
  265. yield d
  266. self.fail("No exception thrown")
  267. except SynapseError:
  268. pass
  269. self.assertEqual(current_context(), c1)
  270. # the cache should now be empty
  271. self.assertEqual(len(obj.fn.cache.cache), 0)
  272. obj = Cls()
  273. # set off a deferred which will do a cache lookup
  274. d1 = do_lookup()
  275. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  276. return d1
  277. @defer.inlineCallbacks
  278. def test_cache_default_args(self):
  279. class Cls:
  280. def __init__(self):
  281. self.mock = mock.Mock()
  282. @descriptors.cached()
  283. def fn(self, arg1, arg2=2, arg3=3):
  284. return self.mock(arg1, arg2, arg3)
  285. obj = Cls()
  286. obj.mock.return_value = "fish"
  287. r = yield obj.fn(1, 2, 3)
  288. self.assertEqual(r, "fish")
  289. obj.mock.assert_called_once_with(1, 2, 3)
  290. obj.mock.reset_mock()
  291. # a call with same params shouldn't call the mock again
  292. r = yield obj.fn(1, 2)
  293. self.assertEqual(r, "fish")
  294. obj.mock.assert_not_called()
  295. obj.mock.reset_mock()
  296. # a call with different params should call the mock again
  297. obj.mock.return_value = "chips"
  298. r = yield obj.fn(2, 3)
  299. self.assertEqual(r, "chips")
  300. obj.mock.assert_called_once_with(2, 3, 3)
  301. obj.mock.reset_mock()
  302. # the two values should now be cached
  303. r = yield obj.fn(1, 2)
  304. self.assertEqual(r, "fish")
  305. r = yield obj.fn(2, 3)
  306. self.assertEqual(r, "chips")
  307. obj.mock.assert_not_called()
  308. def test_cache_iterable(self):
  309. class Cls:
  310. def __init__(self):
  311. self.mock = mock.Mock()
  312. @descriptors.cached(iterable=True)
  313. def fn(self, arg1, arg2):
  314. return self.mock(arg1, arg2)
  315. obj = Cls()
  316. obj.mock.return_value = ["spam", "eggs"]
  317. r = obj.fn(1, 2)
  318. self.assertEqual(r.result, ["spam", "eggs"])
  319. obj.mock.assert_called_once_with(1, 2)
  320. obj.mock.reset_mock()
  321. # a call with different params should call the mock again
  322. obj.mock.return_value = ["chips"]
  323. r = obj.fn(1, 3)
  324. self.assertEqual(r.result, ["chips"])
  325. obj.mock.assert_called_once_with(1, 3)
  326. obj.mock.reset_mock()
  327. # the two values should now be cached
  328. self.assertEqual(len(obj.fn.cache.cache), 3)
  329. r = obj.fn(1, 2)
  330. self.assertEqual(r.result, ["spam", "eggs"])
  331. r = obj.fn(1, 3)
  332. self.assertEqual(r.result, ["chips"])
  333. obj.mock.assert_not_called()
  334. def test_cache_iterable_with_sync_exception(self):
  335. """If the wrapped function throws synchronously, things should continue to work"""
  336. class Cls:
  337. @descriptors.cached(iterable=True)
  338. def fn(self, arg1):
  339. raise SynapseError(100, "mai spoon iz too big!!1")
  340. obj = Cls()
  341. # this should fail immediately
  342. d = obj.fn(1)
  343. self.failureResultOf(d, SynapseError)
  344. # ... leaving the cache empty
  345. self.assertEqual(len(obj.fn.cache.cache), 0)
  346. # and a second call should result in a second exception
  347. d = obj.fn(1)
  348. self.failureResultOf(d, SynapseError)
  349. def test_invalidate_cascade(self):
  350. """Invalidations should cascade up through cache contexts"""
  351. class Cls:
  352. @cached(cache_context=True)
  353. async def func1(self, key, cache_context):
  354. return await self.func2(key, on_invalidate=cache_context.invalidate)
  355. @cached(cache_context=True)
  356. async def func2(self, key, cache_context):
  357. return await self.func3(key, on_invalidate=cache_context.invalidate)
  358. @cached(cache_context=True)
  359. async def func3(self, key, cache_context):
  360. self.invalidate = cache_context.invalidate
  361. return 42
  362. obj = Cls()
  363. top_invalidate = mock.Mock()
  364. r = get_awaitable_result(obj.func1("k1", on_invalidate=top_invalidate))
  365. self.assertEqual(r, 42)
  366. obj.invalidate()
  367. top_invalidate.assert_called_once()
  368. def test_cancel(self):
  369. """Test that cancelling a lookup does not cancel other lookups"""
  370. complete_lookup: "Deferred[None]" = Deferred()
  371. class Cls:
  372. @cached()
  373. async def fn(self, arg1):
  374. await complete_lookup
  375. return str(arg1)
  376. obj = Cls()
  377. d1 = obj.fn(123)
  378. d2 = obj.fn(123)
  379. self.assertFalse(d1.called)
  380. self.assertFalse(d2.called)
  381. # Cancel `d1`, which is the lookup that caused `fn` to run.
  382. d1.cancel()
  383. # `d2` should complete normally.
  384. complete_lookup.callback(None)
  385. self.failureResultOf(d1, CancelledError)
  386. self.assertEqual(d2.result, "123")
  387. def test_cancel_logcontexts(self):
  388. """Test that cancellation does not break logcontexts.
  389. * The `CancelledError` must be raised with the correct logcontext.
  390. * The inner lookup must not resume with a finished logcontext.
  391. * The inner lookup must not restore a finished logcontext when done.
  392. """
  393. complete_lookup: "Deferred[None]" = Deferred()
  394. class Cls:
  395. inner_context_was_finished = False
  396. @cached()
  397. async def fn(self, arg1):
  398. await make_deferred_yieldable(complete_lookup)
  399. self.inner_context_was_finished = current_context().finished
  400. return str(arg1)
  401. obj = Cls()
  402. async def do_lookup():
  403. with LoggingContext("c1") as c1:
  404. try:
  405. await obj.fn(123)
  406. self.fail("No CancelledError thrown")
  407. except CancelledError:
  408. self.assertEqual(
  409. current_context(),
  410. c1,
  411. "CancelledError was not raised with the correct logcontext",
  412. )
  413. # suppress the error and succeed
  414. d = defer.ensureDeferred(do_lookup())
  415. d.cancel()
  416. complete_lookup.callback(None)
  417. self.successResultOf(d)
  418. self.assertFalse(
  419. obj.inner_context_was_finished, "Tried to restart a finished logcontext"
  420. )
  421. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  422. class CacheDecoratorTestCase(unittest.HomeserverTestCase):
  423. """More tests for @cached
  424. The following is a set of tests that got lost in a different file for a while.
  425. There are probably duplicates of the tests in DescriptorTestCase. Ideally the
  426. duplicates would be removed and the two sets of classes combined.
  427. """
  428. @defer.inlineCallbacks
  429. def test_passthrough(self):
  430. class A:
  431. @cached()
  432. def func(self, key):
  433. return key
  434. a = A()
  435. self.assertEqual((yield a.func("foo")), "foo")
  436. self.assertEqual((yield a.func("bar")), "bar")
  437. @defer.inlineCallbacks
  438. def test_hit(self):
  439. callcount = [0]
  440. class A:
  441. @cached()
  442. def func(self, key):
  443. callcount[0] += 1
  444. return key
  445. a = A()
  446. yield a.func("foo")
  447. self.assertEqual(callcount[0], 1)
  448. self.assertEqual((yield a.func("foo")), "foo")
  449. self.assertEqual(callcount[0], 1)
  450. @defer.inlineCallbacks
  451. def test_invalidate(self):
  452. callcount = [0]
  453. class A:
  454. @cached()
  455. def func(self, key):
  456. callcount[0] += 1
  457. return key
  458. a = A()
  459. yield a.func("foo")
  460. self.assertEqual(callcount[0], 1)
  461. a.func.invalidate(("foo",))
  462. yield a.func("foo")
  463. self.assertEqual(callcount[0], 2)
  464. def test_invalidate_missing(self):
  465. class A:
  466. @cached()
  467. def func(self, key):
  468. return key
  469. A().func.invalidate(("what",))
  470. @defer.inlineCallbacks
  471. def test_max_entries(self):
  472. callcount = [0]
  473. class A:
  474. @cached(max_entries=10)
  475. def func(self, key):
  476. callcount[0] += 1
  477. return key
  478. a = A()
  479. for k in range(0, 12):
  480. yield a.func(k)
  481. self.assertEqual(callcount[0], 12)
  482. # There must have been at least 2 evictions, meaning if we calculate
  483. # all 12 values again, we must get called at least 2 more times
  484. for k in range(0, 12):
  485. yield a.func(k)
  486. self.assertTrue(
  487. callcount[0] >= 14, msg="Expected callcount >= 14, got %d" % (callcount[0])
  488. )
  489. def test_prefill(self):
  490. callcount = [0]
  491. d = defer.succeed(123)
  492. class A:
  493. @cached()
  494. def func(self, key):
  495. callcount[0] += 1
  496. return d
  497. a = A()
  498. a.func.prefill(("foo",), 456)
  499. self.assertEqual(a.func("foo").result, 456)
  500. self.assertEqual(callcount[0], 0)
  501. @defer.inlineCallbacks
  502. def test_invalidate_context(self):
  503. callcount = [0]
  504. callcount2 = [0]
  505. class A:
  506. @cached()
  507. def func(self, key):
  508. callcount[0] += 1
  509. return key
  510. @cached(cache_context=True)
  511. def func2(self, key, cache_context):
  512. callcount2[0] += 1
  513. return self.func(key, on_invalidate=cache_context.invalidate)
  514. a = A()
  515. yield a.func2("foo")
  516. self.assertEqual(callcount[0], 1)
  517. self.assertEqual(callcount2[0], 1)
  518. a.func.invalidate(("foo",))
  519. yield a.func("foo")
  520. self.assertEqual(callcount[0], 2)
  521. self.assertEqual(callcount2[0], 1)
  522. yield a.func2("foo")
  523. self.assertEqual(callcount[0], 2)
  524. self.assertEqual(callcount2[0], 2)
  525. @defer.inlineCallbacks
  526. def test_eviction_context(self):
  527. callcount = [0]
  528. callcount2 = [0]
  529. class A:
  530. @cached(max_entries=2)
  531. def func(self, key):
  532. callcount[0] += 1
  533. return key
  534. @cached(cache_context=True)
  535. def func2(self, key, cache_context):
  536. callcount2[0] += 1
  537. return self.func(key, on_invalidate=cache_context.invalidate)
  538. a = A()
  539. yield a.func2("foo")
  540. yield a.func2("foo2")
  541. self.assertEqual(callcount[0], 2)
  542. self.assertEqual(callcount2[0], 2)
  543. yield a.func2("foo")
  544. self.assertEqual(callcount[0], 2)
  545. self.assertEqual(callcount2[0], 2)
  546. yield a.func("foo3")
  547. self.assertEqual(callcount[0], 3)
  548. self.assertEqual(callcount2[0], 2)
  549. yield a.func2("foo")
  550. self.assertEqual(callcount[0], 4)
  551. self.assertEqual(callcount2[0], 3)
  552. @defer.inlineCallbacks
  553. def test_double_get(self):
  554. callcount = [0]
  555. callcount2 = [0]
  556. class A:
  557. @cached()
  558. def func(self, key):
  559. callcount[0] += 1
  560. return key
  561. @cached(cache_context=True)
  562. def func2(self, key, cache_context):
  563. callcount2[0] += 1
  564. return self.func(key, on_invalidate=cache_context.invalidate)
  565. a = A()
  566. a.func2.cache.cache = mock.Mock(wraps=a.func2.cache.cache)
  567. yield a.func2("foo")
  568. self.assertEqual(callcount[0], 1)
  569. self.assertEqual(callcount2[0], 1)
  570. a.func2.invalidate(("foo",))
  571. self.assertEqual(a.func2.cache.cache.del_multi.call_count, 1)
  572. yield a.func2("foo")
  573. a.func2.invalidate(("foo",))
  574. self.assertEqual(a.func2.cache.cache.del_multi.call_count, 2)
  575. self.assertEqual(callcount[0], 1)
  576. self.assertEqual(callcount2[0], 2)
  577. a.func.invalidate(("foo",))
  578. self.assertEqual(a.func2.cache.cache.del_multi.call_count, 3)
  579. yield a.func("foo")
  580. self.assertEqual(callcount[0], 2)
  581. self.assertEqual(callcount2[0], 2)
  582. yield a.func2("foo")
  583. self.assertEqual(callcount[0], 2)
  584. self.assertEqual(callcount2[0], 3)
  585. class CachedListDescriptorTestCase(unittest.TestCase):
  586. @defer.inlineCallbacks
  587. def test_cache(self):
  588. class Cls:
  589. def __init__(self):
  590. self.mock = mock.Mock()
  591. @descriptors.cached()
  592. def fn(self, arg1, arg2):
  593. pass
  594. @descriptors.cachedList(cached_method_name="fn", list_name="args1")
  595. async def list_fn(self, args1, arg2):
  596. context = current_context()
  597. assert isinstance(context, LoggingContext)
  598. assert context.name == "c1"
  599. # we want this to behave like an asynchronous function
  600. await run_on_reactor()
  601. context = current_context()
  602. assert isinstance(context, LoggingContext)
  603. assert context.name == "c1"
  604. return self.mock(args1, arg2)
  605. with LoggingContext("c1") as c1:
  606. obj = Cls()
  607. obj.mock.return_value = {10: "fish", 20: "chips"}
  608. # start the lookup off
  609. d1 = obj.list_fn([10, 20], 2)
  610. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  611. r = yield d1
  612. self.assertEqual(current_context(), c1)
  613. obj.mock.assert_called_once_with({10, 20}, 2)
  614. self.assertEqual(r, {10: "fish", 20: "chips"})
  615. obj.mock.reset_mock()
  616. # a call with different params should call the mock again
  617. obj.mock.return_value = {30: "peas"}
  618. r = yield obj.list_fn([20, 30], 2)
  619. obj.mock.assert_called_once_with({30}, 2)
  620. self.assertEqual(r, {20: "chips", 30: "peas"})
  621. obj.mock.reset_mock()
  622. # all the values should now be cached
  623. r = yield obj.fn(10, 2)
  624. self.assertEqual(r, "fish")
  625. r = yield obj.fn(20, 2)
  626. self.assertEqual(r, "chips")
  627. r = yield obj.fn(30, 2)
  628. self.assertEqual(r, "peas")
  629. r = yield obj.list_fn([10, 20, 30], 2)
  630. obj.mock.assert_not_called()
  631. self.assertEqual(r, {10: "fish", 20: "chips", 30: "peas"})
  632. # we should also be able to use a (single-use) iterable, and should
  633. # deduplicate the keys
  634. obj.mock.reset_mock()
  635. obj.mock.return_value = {40: "gravy"}
  636. iterable = (x for x in [10, 40, 40])
  637. r = yield obj.list_fn(iterable, 2)
  638. obj.mock.assert_called_once_with({40}, 2)
  639. self.assertEqual(r, {10: "fish", 40: "gravy"})
  640. def test_concurrent_lookups(self):
  641. """All concurrent lookups should get the same result"""
  642. class Cls:
  643. def __init__(self):
  644. self.mock = mock.Mock()
  645. @descriptors.cached()
  646. def fn(self, arg1):
  647. pass
  648. @descriptors.cachedList(cached_method_name="fn", list_name="args1")
  649. def list_fn(self, args1) -> "Deferred[dict]":
  650. return self.mock(args1)
  651. obj = Cls()
  652. deferred_result: "Deferred[dict]" = Deferred()
  653. obj.mock.return_value = deferred_result
  654. # start off several concurrent lookups of the same key
  655. d1 = obj.list_fn([10])
  656. d2 = obj.list_fn([10])
  657. d3 = obj.list_fn([10])
  658. # the mock should have been called exactly once
  659. obj.mock.assert_called_once_with({10})
  660. obj.mock.reset_mock()
  661. # ... and none of the calls should yet be complete
  662. self.assertFalse(d1.called)
  663. self.assertFalse(d2.called)
  664. self.assertFalse(d3.called)
  665. # complete the lookup. @cachedList functions need to complete with a map
  666. # of input->result
  667. deferred_result.callback({10: "peas"})
  668. # ... which should give the right result to all the callers
  669. self.assertEqual(self.successResultOf(d1), {10: "peas"})
  670. self.assertEqual(self.successResultOf(d2), {10: "peas"})
  671. self.assertEqual(self.successResultOf(d3), {10: "peas"})
  672. @defer.inlineCallbacks
  673. def test_invalidate(self):
  674. """Make sure that invalidation callbacks are called."""
  675. class Cls:
  676. def __init__(self):
  677. self.mock = mock.Mock()
  678. @descriptors.cached()
  679. def fn(self, arg1, arg2):
  680. pass
  681. @descriptors.cachedList(cached_method_name="fn", list_name="args1")
  682. async def list_fn(self, args1, arg2):
  683. # we want this to behave like an asynchronous function
  684. await run_on_reactor()
  685. return self.mock(args1, arg2)
  686. obj = Cls()
  687. invalidate0 = mock.Mock()
  688. invalidate1 = mock.Mock()
  689. # cache miss
  690. obj.mock.return_value = {10: "fish", 20: "chips"}
  691. r1 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0)
  692. obj.mock.assert_called_once_with({10, 20}, 2)
  693. self.assertEqual(r1, {10: "fish", 20: "chips"})
  694. obj.mock.reset_mock()
  695. # cache hit
  696. r2 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1)
  697. obj.mock.assert_not_called()
  698. self.assertEqual(r2, {10: "fish", 20: "chips"})
  699. invalidate0.assert_not_called()
  700. invalidate1.assert_not_called()
  701. # now if we invalidate the keys, both invalidations should get called
  702. obj.fn.invalidate((10, 2))
  703. invalidate0.assert_called_once()
  704. invalidate1.assert_called_once()
  705. def test_cancel(self):
  706. """Test that cancelling a lookup does not cancel other lookups"""
  707. complete_lookup: "Deferred[None]" = Deferred()
  708. class Cls:
  709. @cached()
  710. def fn(self, arg1):
  711. pass
  712. @cachedList(cached_method_name="fn", list_name="args")
  713. async def list_fn(self, args):
  714. await complete_lookup
  715. return {arg: str(arg) for arg in args}
  716. obj = Cls()
  717. d1 = obj.list_fn([123, 456])
  718. d2 = obj.list_fn([123, 456, 789])
  719. self.assertFalse(d1.called)
  720. self.assertFalse(d2.called)
  721. d1.cancel()
  722. # `d2` should complete normally.
  723. complete_lookup.callback(None)
  724. self.failureResultOf(d1, CancelledError)
  725. self.assertEqual(d2.result, {123: "123", 456: "456", 789: "789"})
  726. def test_cancel_logcontexts(self):
  727. """Test that cancellation does not break logcontexts.
  728. * The `CancelledError` must be raised with the correct logcontext.
  729. * The inner lookup must not resume with a finished logcontext.
  730. * The inner lookup must not restore a finished logcontext when done.
  731. """
  732. complete_lookup: "Deferred[None]" = Deferred()
  733. class Cls:
  734. inner_context_was_finished = False
  735. @cached()
  736. def fn(self, arg1):
  737. pass
  738. @cachedList(cached_method_name="fn", list_name="args")
  739. async def list_fn(self, args):
  740. await make_deferred_yieldable(complete_lookup)
  741. self.inner_context_was_finished = current_context().finished
  742. return {arg: str(arg) for arg in args}
  743. obj = Cls()
  744. async def do_lookup():
  745. with LoggingContext("c1") as c1:
  746. try:
  747. await obj.list_fn([123])
  748. self.fail("No CancelledError thrown")
  749. except CancelledError:
  750. self.assertEqual(
  751. current_context(),
  752. c1,
  753. "CancelledError was not raised with the correct logcontext",
  754. )
  755. # suppress the error and succeed
  756. d = defer.ensureDeferred(do_lookup())
  757. d.cancel()
  758. complete_lookup.callback(None)
  759. self.successResultOf(d)
  760. self.assertFalse(
  761. obj.inner_context_was_finished, "Tried to restart a finished logcontext"
  762. )
  763. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  764. def test_num_args_mismatch(self):
  765. """
  766. Make sure someone does not accidentally use @cachedList on a method with
  767. a mismatch in the number args to the underlying single cache method.
  768. """
  769. class Cls:
  770. @descriptors.cached(tree=True)
  771. def fn(self, room_id, event_id):
  772. pass
  773. # This is wrong ❌. `@cachedList` expects to be given the same number
  774. # of arguments as the underlying cached function, just with one of
  775. # the arguments being an iterable
  776. @descriptors.cachedList(cached_method_name="fn", list_name="keys")
  777. def list_fn(self, keys: Iterable[Tuple[str, str]]):
  778. pass
  779. # Corrected syntax ✅
  780. #
  781. # @cachedList(cached_method_name="fn", list_name="event_ids")
  782. # async def list_fn(
  783. # self, room_id: str, event_ids: Collection[str],
  784. # )
  785. obj = Cls()
  786. # Make sure this raises an error about the arg mismatch
  787. with self.assertRaises(TypeError):
  788. obj.list_fn([("foo", "bar")])