test_descriptors.py 33 KB

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