mirror of
https://github.com/element-hq/synapse
synced 2024-08-19 23:10:20 +00:00
Everything else, sorry
This commit is contained in:
parent
35258e0a1d
commit
dd92bedbcf
1 changed files with 136 additions and 107 deletions
|
@ -13,7 +13,18 @@
|
|||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import logging
|
||||
from typing import Any, Generator, Iterable, Set, Tuple, cast
|
||||
from typing import (
|
||||
Any,
|
||||
Dict,
|
||||
Generator,
|
||||
Iterable,
|
||||
List,
|
||||
Optional,
|
||||
Sequence,
|
||||
Set,
|
||||
Tuple,
|
||||
cast,
|
||||
)
|
||||
from unittest import mock
|
||||
|
||||
from twisted.internet import defer, reactor
|
||||
|
@ -29,7 +40,7 @@ from synapse.logging.context import (
|
|||
make_deferred_yieldable,
|
||||
)
|
||||
from synapse.util.caches import descriptors
|
||||
from synapse.util.caches.descriptors import cached, cachedList
|
||||
from synapse.util.caches.descriptors import _CacheContext, cached, cachedList
|
||||
|
||||
from tests import unittest
|
||||
from tests.test_utils import get_awaitable_result
|
||||
|
@ -57,7 +68,6 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
obj = Cls()
|
||||
|
||||
obj.mock.return_value = "fish"
|
||||
r: mock.Mock
|
||||
r = yield obj.fn(1, 2)
|
||||
self.assertEqual(r, "fish")
|
||||
obj.mock.assert_called_once_with(1, 2)
|
||||
|
@ -91,7 +101,6 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
|
||||
obj = Cls()
|
||||
obj.mock.return_value = "fish"
|
||||
r: mock.Mock
|
||||
r = yield obj.fn(1, 2)
|
||||
self.assertEqual(r, "fish")
|
||||
obj.mock.assert_called_once_with(1, 2)
|
||||
|
@ -133,7 +142,6 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
|
||||
obj = Cls()
|
||||
obj.mock.return_value = "fish"
|
||||
r: mock.Mock
|
||||
r = yield obj.fn(1, 2, 3)
|
||||
self.assertEqual(r, "fish")
|
||||
obj.mock.assert_called_once_with(1, 2, 3)
|
||||
|
@ -163,12 +171,11 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
self.mock = mock.Mock()
|
||||
|
||||
@descriptors.cached()
|
||||
def fn(self, arg1: int, kwarg1: int=2) -> mock.Mock:
|
||||
def fn(self, arg1: int, kwarg1: int = 2) -> mock.Mock:
|
||||
return self.mock(arg1, kwarg1=kwarg1)
|
||||
|
||||
obj = Cls()
|
||||
obj.mock.return_value = "fish"
|
||||
r: mock.Mock
|
||||
r = yield obj.fn(1, kwarg1=2)
|
||||
self.assertEqual(r, "fish")
|
||||
obj.mock.assert_called_once_with(1, kwarg1=2)
|
||||
|
@ -197,39 +204,42 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
|
||||
class Cls:
|
||||
@cached()
|
||||
def fn(self, arg1):
|
||||
def fn(self, arg1: int) -> None:
|
||||
raise SynapseError(100, "mai spoon iz too big!!1")
|
||||
|
||||
obj = Cls()
|
||||
|
||||
# this should fail immediately
|
||||
d = obj.fn(1)
|
||||
# type-ignore: mypy thinks the RHS is None; we need to fix the annotation for
|
||||
# @cached here.
|
||||
d: "Deferred[None]" = obj.fn(1) # type: ignore[assignment]
|
||||
self.failureResultOf(d, SynapseError)
|
||||
|
||||
# ... leaving the cache empty
|
||||
self.assertEqual(len(obj.fn.cache.cache), 0)
|
||||
|
||||
# and a second call should result in a second exception
|
||||
d = obj.fn(1)
|
||||
d = obj.fn(1) # type: ignore[assignment]
|
||||
self.failureResultOf(d, SynapseError)
|
||||
|
||||
def test_cache_with_async_exception(self) -> None:
|
||||
"""The wrapped function returns a failure"""
|
||||
|
||||
class Cls:
|
||||
result = None
|
||||
result: "Optional[Deferred[int]]" = None
|
||||
call_count = 0
|
||||
|
||||
@cached()
|
||||
def fn(self, arg1):
|
||||
def fn(self, arg1: int) -> "Deferred[int]":
|
||||
self.call_count += 1
|
||||
assert self.result is not None
|
||||
return self.result
|
||||
|
||||
obj = Cls()
|
||||
callbacks: Set[str] = set()
|
||||
|
||||
# set off an asynchronous request
|
||||
origin_d: Deferred = defer.Deferred()
|
||||
origin_d: Deferred[int] = defer.Deferred()
|
||||
obj.result = origin_d
|
||||
|
||||
d1 = obj.fn(1, on_invalidate=lambda: callbacks.add("d1"))
|
||||
|
@ -264,17 +274,17 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
self.assertEqual(self.successResultOf(d3), 100)
|
||||
self.assertEqual(obj.call_count, 2)
|
||||
|
||||
def test_cache_logcontexts(self) -> None:
|
||||
def test_cache_logcontexts(self) -> "Deferred[List[int]]":
|
||||
"""Check that logcontexts are set and restored correctly when
|
||||
using the cache."""
|
||||
|
||||
complete_lookup: Deferred = defer.Deferred()
|
||||
complete_lookup: "Deferred[None]" = defer.Deferred()
|
||||
|
||||
class Cls:
|
||||
@descriptors.cached()
|
||||
def fn(self, arg1):
|
||||
def fn(self, arg1: int) -> Deferred[int]:
|
||||
@defer.inlineCallbacks
|
||||
def inner_fn():
|
||||
def inner_fn() -> Generator["Deferred[Any]", Any, int]:
|
||||
with PreserveLoggingContext():
|
||||
yield complete_lookup
|
||||
return 1
|
||||
|
@ -282,13 +292,14 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
return inner_fn()
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def do_lookup():
|
||||
def do_lookup() -> Generator["Deferred[Any]", Any, int]:
|
||||
with LoggingContext("c1") as c1:
|
||||
r: int
|
||||
r = yield obj.fn(1)
|
||||
self.assertEqual(current_context(), c1)
|
||||
return r
|
||||
|
||||
def check_result(r):
|
||||
def check_result(r: Any) -> None:
|
||||
self.assertEqual(r, 1)
|
||||
|
||||
obj = Cls()
|
||||
|
@ -308,15 +319,15 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
|
||||
return defer.gatherResults([d1, d2])
|
||||
|
||||
def test_cache_logcontexts_with_exception(self) -> None:
|
||||
def test_cache_logcontexts_with_exception(self) -> "Deferred[None]":
|
||||
"""Check that the cache sets and restores logcontexts correctly when
|
||||
the lookup function throws an exception"""
|
||||
|
||||
class Cls:
|
||||
@descriptors.cached()
|
||||
def fn(self, arg1):
|
||||
def fn(self, arg1: int) -> "Deferred[None]":
|
||||
@defer.inlineCallbacks
|
||||
def inner_fn():
|
||||
def inner_fn() -> Generator["Deferred[Any]", Any, None]:
|
||||
# we want this to behave like an asynchronous function
|
||||
yield run_on_reactor()
|
||||
raise SynapseError(400, "blah")
|
||||
|
@ -324,7 +335,7 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
return inner_fn()
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def do_lookup():
|
||||
def do_lookup() -> Generator["Deferred[Any]", Any, None]:
|
||||
with LoggingContext("c1") as c1:
|
||||
try:
|
||||
d = obj.fn(1)
|
||||
|
@ -351,13 +362,13 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
return d1
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_cache_default_args(self) -> None:
|
||||
def test_cache_default_args(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
class Cls:
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.mock = mock.Mock()
|
||||
|
||||
@descriptors.cached()
|
||||
def fn(self, arg1, arg2=2, arg3=3):
|
||||
def fn(self, arg1: int, arg2: int = 2, arg3: int = 3) -> mock.Mock:
|
||||
return self.mock(arg1, arg2, arg3)
|
||||
|
||||
obj = Cls()
|
||||
|
@ -390,11 +401,11 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
|
||||
def test_cache_iterable(self) -> None:
|
||||
class Cls:
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.mock = mock.Mock()
|
||||
|
||||
@descriptors.cached(iterable=True)
|
||||
def fn(self, arg1, arg2):
|
||||
def fn(self, arg1: int, arg2: int) -> mock.Mock:
|
||||
return self.mock(arg1, arg2)
|
||||
|
||||
obj = Cls()
|
||||
|
@ -426,7 +437,7 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
|
||||
class Cls:
|
||||
@descriptors.cached(iterable=True)
|
||||
def fn(self, arg1):
|
||||
def fn(self, arg1: int) -> None:
|
||||
raise SynapseError(100, "mai spoon iz too big!!1")
|
||||
|
||||
obj = Cls()
|
||||
|
@ -447,15 +458,15 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
|
||||
class Cls:
|
||||
@cached(cache_context=True)
|
||||
async def func1(self, key, cache_context):
|
||||
async def func1(self, key: str, cache_context: _CacheContext) -> int:
|
||||
return await self.func2(key, on_invalidate=cache_context.invalidate)
|
||||
|
||||
@cached(cache_context=True)
|
||||
async def func2(self, key, cache_context):
|
||||
async def func2(self, key: str, cache_context: _CacheContext) -> int:
|
||||
return await self.func3(key, on_invalidate=cache_context.invalidate)
|
||||
|
||||
@cached(cache_context=True)
|
||||
async def func3(self, key, cache_context):
|
||||
async def func3(self, key: str, cache_context: _CacheContext) -> int:
|
||||
self.invalidate = cache_context.invalidate
|
||||
return 42
|
||||
|
||||
|
@ -473,14 +484,16 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
|
||||
class Cls:
|
||||
@cached()
|
||||
async def fn(self, arg1):
|
||||
async def fn(self, arg1: int) -> str:
|
||||
await complete_lookup
|
||||
return str(arg1)
|
||||
|
||||
obj = Cls()
|
||||
|
||||
d1 = obj.fn(123)
|
||||
d2 = obj.fn(123)
|
||||
# type-ignore: mypy sees the RHS as a coroutine. We need to improve the
|
||||
# annotation of @cached to fix this.
|
||||
d1: "Deferred[str]" = obj.fn(123) # type: ignore[assignment]
|
||||
d2: "Deferred[str]" = obj.fn(123) # type: ignore[assignment]
|
||||
self.assertFalse(d1.called)
|
||||
self.assertFalse(d2.called)
|
||||
|
||||
|
@ -505,14 +518,14 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
inner_context_was_finished = False
|
||||
|
||||
@cached()
|
||||
async def fn(self, arg1):
|
||||
async def fn(self, arg1: int) -> str:
|
||||
await make_deferred_yieldable(complete_lookup)
|
||||
self.inner_context_was_finished = current_context().finished
|
||||
return str(arg1)
|
||||
|
||||
obj = Cls()
|
||||
|
||||
async def do_lookup():
|
||||
async def do_lookup() -> None:
|
||||
with LoggingContext("c1") as c1:
|
||||
try:
|
||||
await obj.fn(123)
|
||||
|
@ -525,7 +538,7 @@ class DescriptorTestCase(unittest.TestCase):
|
|||
)
|
||||
# suppress the error and succeed
|
||||
|
||||
d = defer.ensureDeferred(do_lookup())
|
||||
d: "Deferred[None]" = defer.ensureDeferred(do_lookup())
|
||||
d.cancel()
|
||||
|
||||
complete_lookup.callback(None)
|
||||
|
@ -544,87 +557,90 @@ class CacheDecoratorTestCase(unittest.HomeserverTestCase):
|
|||
There are probably duplicates of the tests in DescriptorTestCase. Ideally the
|
||||
duplicates would be removed and the two sets of classes combined.
|
||||
"""
|
||||
# Through this class, mypy complains that the `xyz` expression in `(yield xyz)` has
|
||||
# a concrete type when it should have type `Deferred[Any]`. I think this would be
|
||||
# fixed by a better annotation for @cached.
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_passthrough(self) -> None:
|
||||
def test_passthrough(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
class A:
|
||||
@cached()
|
||||
def func(self, key):
|
||||
def func(self, key: str) -> str:
|
||||
return key
|
||||
|
||||
a = A()
|
||||
|
||||
self.assertEqual((yield a.func("foo")), "foo")
|
||||
self.assertEqual((yield a.func("bar")), "bar")
|
||||
self.assertEqual((yield a.func("foo")), "foo") # type: ignore[misc]
|
||||
self.assertEqual((yield a.func("bar")), "bar") # type: ignore[misc]
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_hit(self) -> None:
|
||||
def test_hit(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
callcount = [0]
|
||||
|
||||
class A:
|
||||
@cached()
|
||||
def func(self, key):
|
||||
def func(self, key: str) -> str:
|
||||
callcount[0] += 1
|
||||
return key
|
||||
|
||||
a = A()
|
||||
yield a.func("foo")
|
||||
yield a.func("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 1)
|
||||
|
||||
self.assertEqual((yield a.func("foo")), "foo")
|
||||
self.assertEqual((yield a.func("foo")), "foo") # type: ignore[misc]
|
||||
self.assertEqual(callcount[0], 1)
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_invalidate(self) -> None:
|
||||
def test_invalidate(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
callcount = [0]
|
||||
|
||||
class A:
|
||||
@cached()
|
||||
def func(self, key):
|
||||
def func(self, key: str) -> str:
|
||||
callcount[0] += 1
|
||||
return key
|
||||
|
||||
a = A()
|
||||
yield a.func("foo")
|
||||
yield a.func("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 1)
|
||||
|
||||
a.func.invalidate(("foo",))
|
||||
|
||||
yield a.func("foo")
|
||||
yield a.func("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 2)
|
||||
|
||||
def test_invalidate_missing(self) -> None:
|
||||
class A:
|
||||
@cached()
|
||||
def func(self, key):
|
||||
def func(self, key: str) -> str:
|
||||
return key
|
||||
|
||||
A().func.invalidate(("what",))
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_max_entries(self) -> None:
|
||||
def test_max_entries(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
callcount = [0]
|
||||
|
||||
class A:
|
||||
@cached(max_entries=10)
|
||||
def func(self, key):
|
||||
def func(self, key: int) -> int:
|
||||
callcount[0] += 1
|
||||
return key
|
||||
|
||||
a = A()
|
||||
|
||||
for k in range(0, 12):
|
||||
yield a.func(k)
|
||||
yield a.func(k) # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 12)
|
||||
|
||||
# There must have been at least 2 evictions, meaning if we calculate
|
||||
# all 12 values again, we must get called at least 2 more times
|
||||
for k in range(0, 12):
|
||||
yield a.func(k)
|
||||
yield a.func(k) # type: ignore[misc]
|
||||
|
||||
self.assertTrue(
|
||||
callcount[0] >= 14, msg="Expected callcount >= 14, got %d" % (callcount[0])
|
||||
|
@ -637,7 +653,7 @@ class CacheDecoratorTestCase(unittest.HomeserverTestCase):
|
|||
|
||||
class A:
|
||||
@cached()
|
||||
def func(self, key):
|
||||
def func(self, key: str) -> "Deferred[int]":
|
||||
callcount[0] += 1
|
||||
return d
|
||||
|
||||
|
@ -649,95 +665,95 @@ class CacheDecoratorTestCase(unittest.HomeserverTestCase):
|
|||
self.assertEqual(callcount[0], 0)
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_invalidate_context(self) -> None:
|
||||
def test_invalidate_context(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
callcount = [0]
|
||||
callcount2 = [0]
|
||||
|
||||
class A:
|
||||
@cached()
|
||||
def func(self, key):
|
||||
def func(self, key: str) -> str:
|
||||
callcount[0] += 1
|
||||
return key
|
||||
|
||||
@cached(cache_context=True)
|
||||
def func2(self, key, cache_context):
|
||||
def func2(self, key: str, cache_context: _CacheContext) -> str:
|
||||
callcount2[0] += 1
|
||||
return self.func(key, on_invalidate=cache_context.invalidate)
|
||||
|
||||
a = A()
|
||||
yield a.func2("foo")
|
||||
yield a.func2("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 1)
|
||||
self.assertEqual(callcount2[0], 1)
|
||||
|
||||
a.func.invalidate(("foo",))
|
||||
yield a.func("foo")
|
||||
yield a.func("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 2)
|
||||
self.assertEqual(callcount2[0], 1)
|
||||
|
||||
yield a.func2("foo")
|
||||
yield a.func2("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 2)
|
||||
self.assertEqual(callcount2[0], 2)
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_eviction_context(self) -> None:
|
||||
def test_eviction_context(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
callcount = [0]
|
||||
callcount2 = [0]
|
||||
|
||||
class A:
|
||||
@cached(max_entries=2)
|
||||
def func(self, key):
|
||||
def func(self, key: str) -> str:
|
||||
callcount[0] += 1
|
||||
return key
|
||||
|
||||
@cached(cache_context=True)
|
||||
def func2(self, key, cache_context):
|
||||
def func2(self, key: str, cache_context: _CacheContext) -> str:
|
||||
callcount2[0] += 1
|
||||
return self.func(key, on_invalidate=cache_context.invalidate)
|
||||
|
||||
a = A()
|
||||
yield a.func2("foo")
|
||||
yield a.func2("foo2")
|
||||
yield a.func2("foo") # type: ignore[misc]
|
||||
yield a.func2("foo2") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 2)
|
||||
self.assertEqual(callcount2[0], 2)
|
||||
|
||||
yield a.func2("foo")
|
||||
yield a.func2("foo") # type: ignore[misc]
|
||||
self.assertEqual(callcount[0], 2)
|
||||
self.assertEqual(callcount2[0], 2)
|
||||
|
||||
yield a.func("foo3")
|
||||
yield a.func("foo3") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 3)
|
||||
self.assertEqual(callcount2[0], 2)
|
||||
|
||||
yield a.func2("foo")
|
||||
yield a.func2("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 4)
|
||||
self.assertEqual(callcount2[0], 3)
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_double_get(self) -> None:
|
||||
def test_double_get(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
callcount = [0]
|
||||
callcount2 = [0]
|
||||
|
||||
class A:
|
||||
@cached()
|
||||
def func(self, key):
|
||||
def func(self, key: str) -> str:
|
||||
callcount[0] += 1
|
||||
return key
|
||||
|
||||
@cached(cache_context=True)
|
||||
def func2(self, key, cache_context):
|
||||
def func2(self, key: str, cache_context: _CacheContext) -> str:
|
||||
callcount2[0] += 1
|
||||
return self.func(key, on_invalidate=cache_context.invalidate)
|
||||
|
||||
a = A()
|
||||
a.func2.cache.cache = mock.Mock(wraps=a.func2.cache.cache)
|
||||
|
||||
yield a.func2("foo")
|
||||
yield a.func2("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 1)
|
||||
self.assertEqual(callcount2[0], 1)
|
||||
|
@ -745,7 +761,7 @@ class CacheDecoratorTestCase(unittest.HomeserverTestCase):
|
|||
a.func2.invalidate(("foo",))
|
||||
self.assertEqual(a.func2.cache.cache.del_multi.call_count, 1)
|
||||
|
||||
yield a.func2("foo")
|
||||
yield a.func2("foo") # type: ignore[misc]
|
||||
a.func2.invalidate(("foo",))
|
||||
self.assertEqual(a.func2.cache.cache.del_multi.call_count, 2)
|
||||
|
||||
|
@ -754,12 +770,12 @@ class CacheDecoratorTestCase(unittest.HomeserverTestCase):
|
|||
|
||||
a.func.invalidate(("foo",))
|
||||
self.assertEqual(a.func2.cache.cache.del_multi.call_count, 3)
|
||||
yield a.func("foo")
|
||||
yield a.func("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 2)
|
||||
self.assertEqual(callcount2[0], 2)
|
||||
|
||||
yield a.func2("foo")
|
||||
yield a.func2("foo") # type: ignore[misc]
|
||||
|
||||
self.assertEqual(callcount[0], 2)
|
||||
self.assertEqual(callcount2[0], 3)
|
||||
|
@ -767,17 +783,17 @@ class CacheDecoratorTestCase(unittest.HomeserverTestCase):
|
|||
|
||||
class CachedListDescriptorTestCase(unittest.TestCase):
|
||||
@defer.inlineCallbacks
|
||||
def test_cache(self) -> None:
|
||||
def test_cache(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
class Cls:
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.mock = mock.Mock()
|
||||
|
||||
@descriptors.cached()
|
||||
def fn(self, arg1, arg2):
|
||||
def fn(self, arg1: int, arg2: int) -> None:
|
||||
pass
|
||||
|
||||
@descriptors.cachedList(cached_method_name="fn", list_name="args1")
|
||||
async def list_fn(self, args1, arg2):
|
||||
async def list_fn(self, args1: Iterable[int], arg2: int) -> mock.Mock:
|
||||
context = current_context()
|
||||
assert isinstance(context, LoggingContext)
|
||||
assert context.name == "c1"
|
||||
|
@ -793,7 +809,9 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
obj.mock.return_value = {10: "fish", 20: "chips"}
|
||||
|
||||
# start the lookup off
|
||||
d1 = obj.list_fn([10, 20], 2)
|
||||
# type-ignore: mypy thinks the RHS is a coroutine; cachedList annotation
|
||||
# needs improving.
|
||||
d1: "Deferred[mock.Mock]" = obj.list_fn([10, 20], 2) # type: ignore[assignment, misc]
|
||||
self.assertEqual(current_context(), SENTINEL_CONTEXT)
|
||||
r = yield d1
|
||||
self.assertEqual(current_context(), c1)
|
||||
|
@ -803,19 +821,19 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
|
||||
# a call with different params should call the mock again
|
||||
obj.mock.return_value = {30: "peas"}
|
||||
r = yield obj.list_fn([20, 30], 2)
|
||||
r = yield obj.list_fn([20, 30], 2) # type: ignore[misc]
|
||||
obj.mock.assert_called_once_with({30}, 2)
|
||||
self.assertEqual(r, {20: "chips", 30: "peas"})
|
||||
obj.mock.reset_mock()
|
||||
|
||||
# all the values should now be cached
|
||||
r = yield obj.fn(10, 2)
|
||||
r = yield obj.fn(10, 2) # type: ignore[misc]
|
||||
self.assertEqual(r, "fish")
|
||||
r = yield obj.fn(20, 2)
|
||||
r = yield obj.fn(20, 2) # type: ignore[misc]
|
||||
self.assertEqual(r, "chips")
|
||||
r = yield obj.fn(30, 2)
|
||||
r = yield obj.fn(30, 2) # type: ignore[misc]
|
||||
self.assertEqual(r, "peas")
|
||||
r = yield obj.list_fn([10, 20, 30], 2)
|
||||
r = yield obj.list_fn([10, 20, 30], 2) # type: ignore[misc]
|
||||
obj.mock.assert_not_called()
|
||||
self.assertEqual(r, {10: "fish", 20: "chips", 30: "peas"})
|
||||
|
||||
|
@ -824,7 +842,7 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
obj.mock.reset_mock()
|
||||
obj.mock.return_value = {40: "gravy"}
|
||||
iterable = (x for x in [10, 40, 40])
|
||||
r = yield obj.list_fn(iterable, 2)
|
||||
r = yield obj.list_fn(iterable, 2) # type: ignore[misc]
|
||||
obj.mock.assert_called_once_with({40}, 2)
|
||||
self.assertEqual(r, {10: "fish", 40: "gravy"})
|
||||
|
||||
|
@ -832,19 +850,19 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
"""All concurrent lookups should get the same result"""
|
||||
|
||||
class Cls:
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.mock = mock.Mock()
|
||||
|
||||
@descriptors.cached()
|
||||
def fn(self, arg1):
|
||||
def fn(self, arg1: int) -> None:
|
||||
pass
|
||||
|
||||
@descriptors.cachedList(cached_method_name="fn", list_name="args1")
|
||||
def list_fn(self, args1) -> "Deferred[dict]":
|
||||
def list_fn(self, args1: Sequence[int]) -> mock.Mock:
|
||||
return self.mock(args1)
|
||||
|
||||
obj = Cls()
|
||||
deferred_result: "Deferred[dict]" = Deferred()
|
||||
deferred_result: "Deferred[Dict[int, str]]" = Deferred()
|
||||
obj.mock.return_value = deferred_result
|
||||
|
||||
# start off several concurrent lookups of the same key
|
||||
|
@ -871,19 +889,19 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
self.assertEqual(self.successResultOf(d3), {10: "peas"})
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def test_invalidate(self) -> None:
|
||||
def test_invalidate(self) -> Generator["Deferred[Any]", Any, None]:
|
||||
"""Make sure that invalidation callbacks are called."""
|
||||
|
||||
class Cls:
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.mock = mock.Mock()
|
||||
|
||||
@descriptors.cached()
|
||||
def fn(self, arg1, arg2):
|
||||
def fn(self, arg1: int, arg2: int) -> None:
|
||||
pass
|
||||
|
||||
@descriptors.cachedList(cached_method_name="fn", list_name="args1")
|
||||
async def list_fn(self, args1, arg2):
|
||||
async def list_fn(self, args1: Sequence[int], arg2: int) -> mock.Mock:
|
||||
# we want this to behave like an asynchronous function
|
||||
await run_on_reactor()
|
||||
return self.mock(args1, arg2)
|
||||
|
@ -894,13 +912,19 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
|
||||
# cache miss
|
||||
obj.mock.return_value = {10: "fish", 20: "chips"}
|
||||
r1 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0)
|
||||
r1: Dict[int, str]
|
||||
# type-ignore: mypy thinks the expression being yielded is a coroutine (and
|
||||
# similarly for r2 below). But the cachedList implementation should ensure the
|
||||
# expression is a deferred. Stick a type-ignore here, in lieu of a better
|
||||
# cachedList annotation.
|
||||
r1 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0) # type: ignore[misc]
|
||||
obj.mock.assert_called_once_with({10, 20}, 2)
|
||||
self.assertEqual(r1, {10: "fish", 20: "chips"})
|
||||
obj.mock.reset_mock()
|
||||
|
||||
# cache hit
|
||||
r2 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1)
|
||||
r2: Dict[int, str]
|
||||
r2 = yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1) # type: ignore[misc]
|
||||
obj.mock.assert_not_called()
|
||||
self.assertEqual(r2, {10: "fish", 20: "chips"})
|
||||
|
||||
|
@ -918,18 +942,23 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
|
||||
class Cls:
|
||||
@cached()
|
||||
def fn(self, arg1):
|
||||
def fn(self, arg1: int) -> None:
|
||||
pass
|
||||
|
||||
@cachedList(cached_method_name="fn", list_name="args")
|
||||
async def list_fn(self, args):
|
||||
async def list_fn(self, args: Sequence[int]) -> Dict[int, str]:
|
||||
await complete_lookup
|
||||
return {arg: str(arg) for arg in args}
|
||||
|
||||
obj = Cls()
|
||||
|
||||
d1 = obj.list_fn([123, 456])
|
||||
d2 = obj.list_fn([123, 456, 789])
|
||||
# type-ignore: the inner `list_fn` is a coroutine, so mypy thinks that the RHS
|
||||
# expressions below are coroutines. (Presumably, at runtime the cachedList
|
||||
# decorator uses ensureDeferred to convert them to Deferreds.) We could try to
|
||||
# improve the annotation on `cachedList` in the future to remove these
|
||||
# type-ignores.
|
||||
d1: "Deferred[Dict[int, str]]" = obj.list_fn([123, 456]) # type: ignore[assignment]
|
||||
d2: "Deferred[Dict[int, str]]" = obj.list_fn([123, 456, 789]) # type: ignore[assignment]
|
||||
self.assertFalse(d1.called)
|
||||
self.assertFalse(d2.called)
|
||||
|
||||
|
@ -953,18 +982,18 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
inner_context_was_finished = False
|
||||
|
||||
@cached()
|
||||
def fn(self, arg1):
|
||||
def fn(self, arg1: int) -> None:
|
||||
pass
|
||||
|
||||
@cachedList(cached_method_name="fn", list_name="args")
|
||||
async def list_fn(self, args):
|
||||
async def list_fn(self, args: Sequence[int]) -> Dict[int, str]:
|
||||
await make_deferred_yieldable(complete_lookup)
|
||||
self.inner_context_was_finished = current_context().finished
|
||||
return {arg: str(arg) for arg in args}
|
||||
|
||||
obj = Cls()
|
||||
|
||||
async def do_lookup():
|
||||
async def do_lookup() -> None:
|
||||
with LoggingContext("c1") as c1:
|
||||
try:
|
||||
await obj.list_fn([123])
|
||||
|
@ -995,14 +1024,14 @@ class CachedListDescriptorTestCase(unittest.TestCase):
|
|||
|
||||
class Cls:
|
||||
@descriptors.cached(tree=True)
|
||||
def fn(self, room_id, event_id):
|
||||
def fn(self, room_id: str, event_id: str) -> None:
|
||||
pass
|
||||
|
||||
# This is wrong ❌. `@cachedList` expects to be given the same number
|
||||
# of arguments as the underlying cached function, just with one of
|
||||
# the arguments being an iterable
|
||||
@descriptors.cachedList(cached_method_name="fn", list_name="keys")
|
||||
def list_fn(self, keys: Iterable[Tuple[str, str]]):
|
||||
def list_fn(self, keys: Iterable[Tuple[str, str]]) -> None:
|
||||
pass
|
||||
|
||||
# Corrected syntax ✅
|
||||
|
|
Loading…
Reference in a new issue