You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1027 lines
33 KiB

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