test_descriptors.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. # type-ignore: addCallback returns self, so as long as we await d1 (and d2)
  237. # below, this error is a false positive.
  238. d1.addCallback(check_result) # type: ignore[unused-awaitable]
  239. # and another
  240. d2 = do_lookup()
  241. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  242. d2.addCallback(check_result) # type: ignore[unused-awaitable]
  243. # let the lookup complete
  244. complete_lookup.callback(None)
  245. return defer.gatherResults([d1, d2])
  246. def test_cache_logcontexts_with_exception(self):
  247. """Check that the cache sets and restores logcontexts correctly when
  248. the lookup function throws an exception"""
  249. class Cls:
  250. @descriptors.cached()
  251. def fn(self, arg1):
  252. @defer.inlineCallbacks
  253. def inner_fn():
  254. # we want this to behave like an asynchronous function
  255. yield run_on_reactor()
  256. raise SynapseError(400, "blah")
  257. return inner_fn()
  258. @defer.inlineCallbacks
  259. def do_lookup():
  260. with LoggingContext("c1") as c1:
  261. try:
  262. d = obj.fn(1)
  263. self.assertEqual(
  264. current_context(),
  265. SENTINEL_CONTEXT,
  266. )
  267. yield d
  268. self.fail("No exception thrown")
  269. except SynapseError:
  270. pass
  271. self.assertEqual(current_context(), c1)
  272. # the cache should now be empty
  273. self.assertEqual(len(obj.fn.cache.cache), 0)
  274. obj = Cls()
  275. # set off a deferred which will do a cache lookup
  276. d1 = do_lookup()
  277. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  278. return d1
  279. @defer.inlineCallbacks
  280. def test_cache_default_args(self):
  281. class Cls:
  282. def __init__(self):
  283. self.mock = mock.Mock()
  284. @descriptors.cached()
  285. def fn(self, arg1, arg2=2, arg3=3):
  286. return self.mock(arg1, arg2, arg3)
  287. obj = Cls()
  288. obj.mock.return_value = "fish"
  289. r = yield obj.fn(1, 2, 3)
  290. self.assertEqual(r, "fish")
  291. obj.mock.assert_called_once_with(1, 2, 3)
  292. obj.mock.reset_mock()
  293. # a call with same params shouldn't call the mock again
  294. r = yield obj.fn(1, 2)
  295. self.assertEqual(r, "fish")
  296. obj.mock.assert_not_called()
  297. obj.mock.reset_mock()
  298. # a call with different params should call the mock again
  299. obj.mock.return_value = "chips"
  300. r = yield obj.fn(2, 3)
  301. self.assertEqual(r, "chips")
  302. obj.mock.assert_called_once_with(2, 3, 3)
  303. obj.mock.reset_mock()
  304. # the two values should now be cached
  305. r = yield obj.fn(1, 2)
  306. self.assertEqual(r, "fish")
  307. r = yield obj.fn(2, 3)
  308. self.assertEqual(r, "chips")
  309. obj.mock.assert_not_called()
  310. def test_cache_iterable(self):
  311. class Cls:
  312. def __init__(self):
  313. self.mock = mock.Mock()
  314. @descriptors.cached(iterable=True)
  315. def fn(self, arg1, arg2):
  316. return self.mock(arg1, arg2)
  317. obj = Cls()
  318. obj.mock.return_value = ["spam", "eggs"]
  319. r = obj.fn(1, 2)
  320. self.assertEqual(r.result, ["spam", "eggs"])
  321. obj.mock.assert_called_once_with(1, 2)
  322. obj.mock.reset_mock()
  323. # a call with different params should call the mock again
  324. obj.mock.return_value = ["chips"]
  325. r = obj.fn(1, 3)
  326. self.assertEqual(r.result, ["chips"])
  327. obj.mock.assert_called_once_with(1, 3)
  328. obj.mock.reset_mock()
  329. # the two values should now be cached
  330. self.assertEqual(len(obj.fn.cache.cache), 3)
  331. r = obj.fn(1, 2)
  332. self.assertEqual(r.result, ["spam", "eggs"])
  333. r = obj.fn(1, 3)
  334. self.assertEqual(r.result, ["chips"])
  335. obj.mock.assert_not_called()
  336. def test_cache_iterable_with_sync_exception(self):
  337. """If the wrapped function throws synchronously, things should continue to work"""
  338. class Cls:
  339. @descriptors.cached(iterable=True)
  340. def fn(self, arg1):
  341. raise SynapseError(100, "mai spoon iz too big!!1")
  342. obj = Cls()
  343. # this should fail immediately
  344. d = obj.fn(1)
  345. self.failureResultOf(d, SynapseError)
  346. # ... leaving the cache empty
  347. self.assertEqual(len(obj.fn.cache.cache), 0)
  348. # and a second call should result in a second exception
  349. d = obj.fn(1)
  350. self.failureResultOf(d, SynapseError)
  351. def test_invalidate_cascade(self):
  352. """Invalidations should cascade up through cache contexts"""
  353. class Cls:
  354. @cached(cache_context=True)
  355. async def func1(self, key, cache_context):
  356. return await self.func2(key, on_invalidate=cache_context.invalidate)
  357. @cached(cache_context=True)
  358. async def func2(self, key, cache_context):
  359. return await self.func3(key, on_invalidate=cache_context.invalidate)
  360. @cached(cache_context=True)
  361. async def func3(self, key, cache_context):
  362. self.invalidate = cache_context.invalidate
  363. return 42
  364. obj = Cls()
  365. top_invalidate = mock.Mock()
  366. r = get_awaitable_result(obj.func1("k1", on_invalidate=top_invalidate))
  367. self.assertEqual(r, 42)
  368. obj.invalidate()
  369. top_invalidate.assert_called_once()
  370. def test_cancel(self):
  371. """Test that cancelling a lookup does not cancel other lookups"""
  372. complete_lookup: "Deferred[None]" = Deferred()
  373. class Cls:
  374. @cached()
  375. async def fn(self, arg1):
  376. await complete_lookup
  377. return str(arg1)
  378. obj = Cls()
  379. d1 = obj.fn(123)
  380. d2 = obj.fn(123)
  381. self.assertFalse(d1.called)
  382. self.assertFalse(d2.called)
  383. # Cancel `d1`, which is the lookup that caused `fn` to run.
  384. d1.cancel()
  385. # `d2` should complete normally.
  386. complete_lookup.callback(None)
  387. self.failureResultOf(d1, CancelledError)
  388. self.assertEqual(d2.result, "123")
  389. def test_cancel_logcontexts(self):
  390. """Test that cancellation does not break logcontexts.
  391. * The `CancelledError` must be raised with the correct logcontext.
  392. * The inner lookup must not resume with a finished logcontext.
  393. * The inner lookup must not restore a finished logcontext when done.
  394. """
  395. complete_lookup: "Deferred[None]" = Deferred()
  396. class Cls:
  397. inner_context_was_finished = False
  398. @cached()
  399. async def fn(self, arg1):
  400. await make_deferred_yieldable(complete_lookup)
  401. self.inner_context_was_finished = current_context().finished
  402. return str(arg1)
  403. obj = Cls()
  404. async def do_lookup():
  405. with LoggingContext("c1") as c1:
  406. try:
  407. await obj.fn(123)
  408. self.fail("No CancelledError thrown")
  409. except CancelledError:
  410. self.assertEqual(
  411. current_context(),
  412. c1,
  413. "CancelledError was not raised with the correct logcontext",
  414. )
  415. # suppress the error and succeed
  416. d = defer.ensureDeferred(do_lookup())
  417. d.cancel()
  418. complete_lookup.callback(None)
  419. self.successResultOf(d)
  420. self.assertFalse(
  421. obj.inner_context_was_finished, "Tried to restart a finished logcontext"
  422. )
  423. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  424. class CacheDecoratorTestCase(unittest.HomeserverTestCase):
  425. """More tests for @cached
  426. The following is a set of tests that got lost in a different file for a while.
  427. There are probably duplicates of the tests in DescriptorTestCase. Ideally the
  428. duplicates would be removed and the two sets of classes combined.
  429. """
  430. @defer.inlineCallbacks
  431. def test_passthrough(self):
  432. class A:
  433. @cached()
  434. def func(self, key):
  435. return key
  436. a = A()
  437. self.assertEqual((yield a.func("foo")), "foo")
  438. self.assertEqual((yield a.func("bar")), "bar")
  439. @defer.inlineCallbacks
  440. def test_hit(self):
  441. callcount = [0]
  442. class A:
  443. @cached()
  444. def func(self, key):
  445. callcount[0] += 1
  446. return key
  447. a = A()
  448. yield a.func("foo")
  449. self.assertEqual(callcount[0], 1)
  450. self.assertEqual((yield a.func("foo")), "foo")
  451. self.assertEqual(callcount[0], 1)
  452. @defer.inlineCallbacks
  453. def test_invalidate(self):
  454. callcount = [0]
  455. class A:
  456. @cached()
  457. def func(self, key):
  458. callcount[0] += 1
  459. return key
  460. a = A()
  461. yield a.func("foo")
  462. self.assertEqual(callcount[0], 1)
  463. a.func.invalidate(("foo",))
  464. yield a.func("foo")
  465. self.assertEqual(callcount[0], 2)
  466. def test_invalidate_missing(self):
  467. class A:
  468. @cached()
  469. def func(self, key):
  470. return key
  471. A().func.invalidate(("what",))
  472. @defer.inlineCallbacks
  473. def test_max_entries(self):
  474. callcount = [0]
  475. class A:
  476. @cached(max_entries=10)
  477. def func(self, key):
  478. callcount[0] += 1
  479. return key
  480. a = A()
  481. for k in range(0, 12):
  482. yield a.func(k)
  483. self.assertEqual(callcount[0], 12)
  484. # There must have been at least 2 evictions, meaning if we calculate
  485. # all 12 values again, we must get called at least 2 more times
  486. for k in range(0, 12):
  487. yield a.func(k)
  488. self.assertTrue(
  489. callcount[0] >= 14, msg="Expected callcount >= 14, got %d" % (callcount[0])
  490. )
  491. def test_prefill(self):
  492. callcount = [0]
  493. d = defer.succeed(123)
  494. class A:
  495. @cached()
  496. def func(self, key):
  497. callcount[0] += 1
  498. return d
  499. a = A()
  500. a.func.prefill(("foo",), 456)
  501. self.assertEqual(a.func("foo").result, 456)
  502. self.assertEqual(callcount[0], 0)
  503. @defer.inlineCallbacks
  504. def test_invalidate_context(self):
  505. callcount = [0]
  506. callcount2 = [0]
  507. class A:
  508. @cached()
  509. def func(self, key):
  510. callcount[0] += 1
  511. return key
  512. @cached(cache_context=True)
  513. def func2(self, key, cache_context):
  514. callcount2[0] += 1
  515. return self.func(key, on_invalidate=cache_context.invalidate)
  516. a = A()
  517. yield a.func2("foo")
  518. self.assertEqual(callcount[0], 1)
  519. self.assertEqual(callcount2[0], 1)
  520. a.func.invalidate(("foo",))
  521. yield a.func("foo")
  522. self.assertEqual(callcount[0], 2)
  523. self.assertEqual(callcount2[0], 1)
  524. yield a.func2("foo")
  525. self.assertEqual(callcount[0], 2)
  526. self.assertEqual(callcount2[0], 2)
  527. @defer.inlineCallbacks
  528. def test_eviction_context(self):
  529. callcount = [0]
  530. callcount2 = [0]
  531. class A:
  532. @cached(max_entries=2)
  533. def func(self, key):
  534. callcount[0] += 1
  535. return key
  536. @cached(cache_context=True)
  537. def func2(self, key, cache_context):
  538. callcount2[0] += 1
  539. return self.func(key, on_invalidate=cache_context.invalidate)
  540. a = A()
  541. yield a.func2("foo")
  542. yield a.func2("foo2")
  543. self.assertEqual(callcount[0], 2)
  544. self.assertEqual(callcount2[0], 2)
  545. yield a.func2("foo")
  546. self.assertEqual(callcount[0], 2)
  547. self.assertEqual(callcount2[0], 2)
  548. yield a.func("foo3")
  549. self.assertEqual(callcount[0], 3)
  550. self.assertEqual(callcount2[0], 2)
  551. yield a.func2("foo")
  552. self.assertEqual(callcount[0], 4)
  553. self.assertEqual(callcount2[0], 3)
  554. @defer.inlineCallbacks
  555. def test_double_get(self):
  556. callcount = [0]
  557. callcount2 = [0]
  558. class A:
  559. @cached()
  560. def func(self, key):
  561. callcount[0] += 1
  562. return key
  563. @cached(cache_context=True)
  564. def func2(self, key, cache_context):
  565. callcount2[0] += 1
  566. return self.func(key, on_invalidate=cache_context.invalidate)
  567. a = A()
  568. a.func2.cache.cache = mock.Mock(wraps=a.func2.cache.cache)
  569. yield a.func2("foo")
  570. self.assertEqual(callcount[0], 1)
  571. self.assertEqual(callcount2[0], 1)
  572. a.func2.invalidate(("foo",))
  573. self.assertEqual(a.func2.cache.cache.del_multi.call_count, 1)
  574. yield a.func2("foo")
  575. a.func2.invalidate(("foo",))
  576. self.assertEqual(a.func2.cache.cache.del_multi.call_count, 2)
  577. self.assertEqual(callcount[0], 1)
  578. self.assertEqual(callcount2[0], 2)
  579. a.func.invalidate(("foo",))
  580. self.assertEqual(a.func2.cache.cache.del_multi.call_count, 3)
  581. yield a.func("foo")
  582. self.assertEqual(callcount[0], 2)
  583. self.assertEqual(callcount2[0], 2)
  584. yield a.func2("foo")
  585. self.assertEqual(callcount[0], 2)
  586. self.assertEqual(callcount2[0], 3)
  587. class CachedListDescriptorTestCase(unittest.TestCase):
  588. @defer.inlineCallbacks
  589. def test_cache(self):
  590. class Cls:
  591. def __init__(self):
  592. self.mock = mock.Mock()
  593. @descriptors.cached()
  594. def fn(self, arg1, arg2):
  595. pass
  596. @descriptors.cachedList(cached_method_name="fn", list_name="args1")
  597. async def list_fn(self, args1, arg2):
  598. context = current_context()
  599. assert isinstance(context, LoggingContext)
  600. assert context.name == "c1"
  601. # we want this to behave like an asynchronous function
  602. await run_on_reactor()
  603. context = current_context()
  604. assert isinstance(context, LoggingContext)
  605. assert context.name == "c1"
  606. return self.mock(args1, arg2)
  607. with LoggingContext("c1") as c1:
  608. obj = Cls()
  609. obj.mock.return_value = {10: "fish", 20: "chips"}
  610. # start the lookup off
  611. d1 = obj.list_fn([10, 20], 2)
  612. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  613. r = yield d1
  614. self.assertEqual(current_context(), c1)
  615. obj.mock.assert_called_once_with({10, 20}, 2)
  616. self.assertEqual(r, {10: "fish", 20: "chips"})
  617. obj.mock.reset_mock()
  618. # a call with different params should call the mock again
  619. obj.mock.return_value = {30: "peas"}
  620. r = yield obj.list_fn([20, 30], 2)
  621. obj.mock.assert_called_once_with({30}, 2)
  622. self.assertEqual(r, {20: "chips", 30: "peas"})
  623. obj.mock.reset_mock()
  624. # all the values should now be cached
  625. r = yield obj.fn(10, 2)
  626. self.assertEqual(r, "fish")
  627. r = yield obj.fn(20, 2)
  628. self.assertEqual(r, "chips")
  629. r = yield obj.fn(30, 2)
  630. self.assertEqual(r, "peas")
  631. r = yield obj.list_fn([10, 20, 30], 2)
  632. obj.mock.assert_not_called()
  633. self.assertEqual(r, {10: "fish", 20: "chips", 30: "peas"})
  634. # we should also be able to use a (single-use) iterable, and should
  635. # deduplicate the keys
  636. obj.mock.reset_mock()
  637. obj.mock.return_value = {40: "gravy"}
  638. iterable = (x for x in [10, 40, 40])
  639. r = yield obj.list_fn(iterable, 2)
  640. obj.mock.assert_called_once_with({40}, 2)
  641. self.assertEqual(r, {10: "fish", 40: "gravy"})
  642. def test_concurrent_lookups(self):
  643. """All concurrent lookups should get the same result"""
  644. class Cls:
  645. def __init__(self):
  646. self.mock = mock.Mock()
  647. @descriptors.cached()
  648. def fn(self, arg1):
  649. pass
  650. @descriptors.cachedList(cached_method_name="fn", list_name="args1")
  651. def list_fn(self, args1) -> "Deferred[dict]":
  652. return self.mock(args1)
  653. obj = Cls()
  654. deferred_result: "Deferred[dict]" = Deferred()
  655. obj.mock.return_value = deferred_result
  656. # start off several concurrent lookups of the same key
  657. d1 = obj.list_fn([10])
  658. d2 = obj.list_fn([10])
  659. d3 = obj.list_fn([10])
  660. # the mock should have been called exactly once
  661. obj.mock.assert_called_once_with({10})
  662. obj.mock.reset_mock()
  663. # ... and none of the calls should yet be complete
  664. self.assertFalse(d1.called)
  665. self.assertFalse(d2.called)
  666. self.assertFalse(d3.called)
  667. # complete the lookup. @cachedList functions need to complete with a map
  668. # of input->result
  669. deferred_result.callback({10: "peas"})
  670. # ... which should give the right result to all the callers
  671. self.assertEqual(self.successResultOf(d1), {10: "peas"})
  672. self.assertEqual(self.successResultOf(d2), {10: "peas"})
  673. self.assertEqual(self.successResultOf(d3), {10: "peas"})
  674. @defer.inlineCallbacks
  675. def test_invalidate(self):
  676. """Make sure that invalidation callbacks are called."""
  677. class Cls:
  678. def __init__(self):
  679. self.mock = mock.Mock()
  680. @descriptors.cached()
  681. def fn(self, arg1, arg2):
  682. pass
  683. @descriptors.cachedList(cached_method_name="fn", list_name="args1")
  684. async def list_fn(self, args1, arg2):
  685. # we want this to behave like an asynchronous function
  686. await run_on_reactor()
  687. return self.mock(args1, arg2)
  688. obj = Cls()
  689. invalidate0 = mock.Mock()
  690. invalidate1 = mock.Mock()
  691. # cache miss
  692. obj.mock.return_value = {10: "fish", 20: "chips"}
  693. r1 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0)
  694. obj.mock.assert_called_once_with({10, 20}, 2)
  695. self.assertEqual(r1, {10: "fish", 20: "chips"})
  696. obj.mock.reset_mock()
  697. # cache hit
  698. r2 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1)
  699. obj.mock.assert_not_called()
  700. self.assertEqual(r2, {10: "fish", 20: "chips"})
  701. invalidate0.assert_not_called()
  702. invalidate1.assert_not_called()
  703. # now if we invalidate the keys, both invalidations should get called
  704. obj.fn.invalidate((10, 2))
  705. invalidate0.assert_called_once()
  706. invalidate1.assert_called_once()
  707. def test_cancel(self):
  708. """Test that cancelling a lookup does not cancel other lookups"""
  709. complete_lookup: "Deferred[None]" = Deferred()
  710. class Cls:
  711. @cached()
  712. def fn(self, arg1):
  713. pass
  714. @cachedList(cached_method_name="fn", list_name="args")
  715. async def list_fn(self, args):
  716. await complete_lookup
  717. return {arg: str(arg) for arg in args}
  718. obj = Cls()
  719. d1 = obj.list_fn([123, 456])
  720. d2 = obj.list_fn([123, 456, 789])
  721. self.assertFalse(d1.called)
  722. self.assertFalse(d2.called)
  723. d1.cancel()
  724. # `d2` should complete normally.
  725. complete_lookup.callback(None)
  726. self.failureResultOf(d1, CancelledError)
  727. self.assertEqual(d2.result, {123: "123", 456: "456", 789: "789"})
  728. def test_cancel_logcontexts(self):
  729. """Test that cancellation does not break logcontexts.
  730. * The `CancelledError` must be raised with the correct logcontext.
  731. * The inner lookup must not resume with a finished logcontext.
  732. * The inner lookup must not restore a finished logcontext when done.
  733. """
  734. complete_lookup: "Deferred[None]" = Deferred()
  735. class Cls:
  736. inner_context_was_finished = False
  737. @cached()
  738. def fn(self, arg1):
  739. pass
  740. @cachedList(cached_method_name="fn", list_name="args")
  741. async def list_fn(self, args):
  742. await make_deferred_yieldable(complete_lookup)
  743. self.inner_context_was_finished = current_context().finished
  744. return {arg: str(arg) for arg in args}
  745. obj = Cls()
  746. async def do_lookup():
  747. with LoggingContext("c1") as c1:
  748. try:
  749. await obj.list_fn([123])
  750. self.fail("No CancelledError thrown")
  751. except CancelledError:
  752. self.assertEqual(
  753. current_context(),
  754. c1,
  755. "CancelledError was not raised with the correct logcontext",
  756. )
  757. # suppress the error and succeed
  758. d = defer.ensureDeferred(do_lookup())
  759. d.cancel()
  760. complete_lookup.callback(None)
  761. self.successResultOf(d)
  762. self.assertFalse(
  763. obj.inner_context_was_finished, "Tried to restart a finished logcontext"
  764. )
  765. self.assertEqual(current_context(), SENTINEL_CONTEXT)
  766. def test_num_args_mismatch(self):
  767. """
  768. Make sure someone does not accidentally use @cachedList on a method with
  769. a mismatch in the number args to the underlying single cache method.
  770. """
  771. class Cls:
  772. @descriptors.cached(tree=True)
  773. def fn(self, room_id, event_id):
  774. pass
  775. # This is wrong ❌. `@cachedList` expects to be given the same number
  776. # of arguments as the underlying cached function, just with one of
  777. # the arguments being an iterable
  778. @descriptors.cachedList(cached_method_name="fn", list_name="keys")
  779. def list_fn(self, keys: Iterable[Tuple[str, str]]):
  780. pass
  781. # Corrected syntax ✅
  782. #
  783. # @cachedList(cached_method_name="fn", list_name="event_ids")
  784. # async def list_fn(
  785. # self, room_id: str, event_ids: Collection[str],
  786. # )
  787. obj = Cls()
  788. # Make sure this raises an error about the arg mismatch
  789. with self.assertRaises(TypeError):
  790. obj.list_fn([("foo", "bar")])