Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 4ae967c

Browse files
authored
Add missing type hints to test.util.caches (#14529)
1 parent 7f78b38 commit 4ae967c

File tree

7 files changed

+76
-66
lines changed

7 files changed

+76
-66
lines changed

changelog.d/14529.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add missing type hints.

mypy.ini

+6-5
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,6 @@ exclude = (?x)
5959
|tests/server_notices/test_resource_limits_server_notices.py
6060
|tests/test_state.py
6161
|tests/test_terms_auth.py
62-
|tests/util/caches/test_cached_call.py
63-
|tests/util/caches/test_deferred_cache.py
64-
|tests/util/caches/test_descriptors.py
65-
|tests/util/caches/test_response_cache.py
66-
|tests/util/caches/test_ttlcache.py
6762
|tests/util/test_async_helpers.py
6863
|tests/util/test_batching_queue.py
6964
|tests/util/test_dict_cache.py
@@ -133,6 +128,12 @@ disallow_untyped_defs = True
133128
[mypy-tests.federation.transport.test_client]
134129
disallow_untyped_defs = True
135130

131+
[mypy-tests.util.caches.*]
132+
disallow_untyped_defs = True
133+
134+
[mypy-tests.util.caches.test_descriptors]
135+
disallow_untyped_defs = False
136+
136137
[mypy-tests.utils]
137138
disallow_untyped_defs = True
138139

tests/util/caches/test_cached_call.py

+12-11
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
from typing import NoReturn
1415
from unittest.mock import Mock
1516

1617
from twisted.internet import defer
@@ -23,14 +24,14 @@
2324

2425

2526
class CachedCallTestCase(TestCase):
26-
def test_get(self):
27+
def test_get(self) -> None:
2728
"""
2829
Happy-path test case: makes a couple of calls and makes sure they behave
2930
correctly
3031
"""
31-
d = Deferred()
32+
d: "Deferred[int]" = Deferred()
3233

33-
async def f():
34+
async def f() -> int:
3435
return await d
3536

3637
slow_call = Mock(side_effect=f)
@@ -43,7 +44,7 @@ async def f():
4344
# now fire off a couple of calls
4445
completed_results = []
4546

46-
async def r():
47+
async def r() -> None:
4748
res = await cached_call.get()
4849
completed_results.append(res)
4950

@@ -69,12 +70,12 @@ async def r():
6970
self.assertEqual(r3, 123)
7071
slow_call.assert_not_called()
7172

72-
def test_fast_call(self):
73+
def test_fast_call(self) -> None:
7374
"""
7475
Test the behaviour when the underlying function completes immediately
7576
"""
7677

77-
async def f():
78+
async def f() -> int:
7879
return 12
7980

8081
fast_call = Mock(side_effect=f)
@@ -92,12 +93,12 @@ async def f():
9293

9394

9495
class RetryOnExceptionCachedCallTestCase(TestCase):
95-
def test_get(self):
96+
def test_get(self) -> None:
9697
# set up the RetryOnExceptionCachedCall around a function which will fail
9798
# (after a while)
98-
d = Deferred()
99+
d: "Deferred[int]" = Deferred()
99100

100-
async def f1():
101+
async def f1() -> NoReturn:
101102
await d
102103
raise ValueError("moo")
103104

@@ -110,7 +111,7 @@ async def f1():
110111
# now fire off a couple of calls
111112
completed_results = []
112113

113-
async def r():
114+
async def r() -> None:
114115
try:
115116
await cached_call.get()
116117
except Exception as e1:
@@ -137,7 +138,7 @@ async def r():
137138
# to the getter
138139
d = Deferred()
139140

140-
async def f2():
141+
async def f2() -> int:
141142
return await d
142143

143144
slow_call.reset_mock()

tests/util/caches/test_deferred_cache.py

+31-30
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
from functools import partial
16+
from typing import List, Tuple
1617

1718
from twisted.internet import defer
1819

@@ -22,28 +23,28 @@
2223

2324

2425
class DeferredCacheTestCase(TestCase):
25-
def test_empty(self):
26-
cache = DeferredCache("test")
26+
def test_empty(self) -> None:
27+
cache: DeferredCache[str, int] = DeferredCache("test")
2728
with self.assertRaises(KeyError):
2829
cache.get("foo")
2930

30-
def test_hit(self):
31-
cache = DeferredCache("test")
31+
def test_hit(self) -> None:
32+
cache: DeferredCache[str, int] = DeferredCache("test")
3233
cache.prefill("foo", 123)
3334

3435
self.assertEqual(self.successResultOf(cache.get("foo")), 123)
3536

36-
def test_hit_deferred(self):
37-
cache = DeferredCache("test")
38-
origin_d = defer.Deferred()
37+
def test_hit_deferred(self) -> None:
38+
cache: DeferredCache[str, int] = DeferredCache("test")
39+
origin_d: "defer.Deferred[int]" = defer.Deferred()
3940
set_d = cache.set("k1", origin_d)
4041

4142
# get should return an incomplete deferred
4243
get_d = cache.get("k1")
4344
self.assertFalse(get_d.called)
4445

4546
# add a callback that will make sure that the set_d gets called before the get_d
46-
def check1(r):
47+
def check1(r: str) -> str:
4748
self.assertTrue(set_d.called)
4849
return r
4950

@@ -55,16 +56,16 @@ def check1(r):
5556
self.assertEqual(self.successResultOf(set_d), 99)
5657
self.assertEqual(self.successResultOf(get_d), 99)
5758

58-
def test_callbacks(self):
59+
def test_callbacks(self) -> None:
5960
"""Invalidation callbacks are called at the right time"""
60-
cache = DeferredCache("test")
61+
cache: DeferredCache[str, int] = DeferredCache("test")
6162
callbacks = set()
6263

6364
# start with an entry, with a callback
6465
cache.prefill("k1", 10, callback=lambda: callbacks.add("prefill"))
6566

6667
# now replace that entry with a pending result
67-
origin_d = defer.Deferred()
68+
origin_d: "defer.Deferred[int]" = defer.Deferred()
6869
set_d = cache.set("k1", origin_d, callback=lambda: callbacks.add("set"))
6970

7071
# ... and also make a get request
@@ -89,15 +90,15 @@ def test_callbacks(self):
8990
cache.prefill("k1", 30)
9091
self.assertEqual(callbacks, {"set", "get"})
9192

92-
def test_set_fail(self):
93-
cache = DeferredCache("test")
93+
def test_set_fail(self) -> None:
94+
cache: DeferredCache[str, int] = DeferredCache("test")
9495
callbacks = set()
9596

9697
# start with an entry, with a callback
9798
cache.prefill("k1", 10, callback=lambda: callbacks.add("prefill"))
9899

99100
# now replace that entry with a pending result
100-
origin_d = defer.Deferred()
101+
origin_d: defer.Deferred = defer.Deferred()
101102
set_d = cache.set("k1", origin_d, callback=lambda: callbacks.add("set"))
102103

103104
# ... and also make a get request
@@ -126,9 +127,9 @@ def test_set_fail(self):
126127
cache.prefill("k1", 30)
127128
self.assertEqual(callbacks, {"prefill", "get2"})
128129

129-
def test_get_immediate(self):
130-
cache = DeferredCache("test")
131-
d1 = defer.Deferred()
130+
def test_get_immediate(self) -> None:
131+
cache: DeferredCache[str, int] = DeferredCache("test")
132+
d1: "defer.Deferred[int]" = defer.Deferred()
132133
cache.set("key1", d1)
133134

134135
# get_immediate should return default
@@ -142,27 +143,27 @@ def test_get_immediate(self):
142143
v = cache.get_immediate("key1", 1)
143144
self.assertEqual(v, 2)
144145

145-
def test_invalidate(self):
146-
cache = DeferredCache("test")
146+
def test_invalidate(self) -> None:
147+
cache: DeferredCache[Tuple[str], int] = DeferredCache("test")
147148
cache.prefill(("foo",), 123)
148149
cache.invalidate(("foo",))
149150

150151
with self.assertRaises(KeyError):
151152
cache.get(("foo",))
152153

153-
def test_invalidate_all(self):
154-
cache = DeferredCache("testcache")
154+
def test_invalidate_all(self) -> None:
155+
cache: DeferredCache[str, str] = DeferredCache("testcache")
155156

156157
callback_record = [False, False]
157158

158-
def record_callback(idx):
159+
def record_callback(idx: int) -> None:
159160
callback_record[idx] = True
160161

161162
# add a couple of pending entries
162-
d1 = defer.Deferred()
163+
d1: "defer.Deferred[str]" = defer.Deferred()
163164
cache.set("key1", d1, partial(record_callback, 0))
164165

165-
d2 = defer.Deferred()
166+
d2: "defer.Deferred[str]" = defer.Deferred()
166167
cache.set("key2", d2, partial(record_callback, 1))
167168

168169
# lookup should return pending deferreds
@@ -193,8 +194,8 @@ def record_callback(idx):
193194
with self.assertRaises(KeyError):
194195
cache.get("key1", None)
195196

196-
def test_eviction(self):
197-
cache = DeferredCache(
197+
def test_eviction(self) -> None:
198+
cache: DeferredCache[int, str] = DeferredCache(
198199
"test", max_entries=2, apply_cache_factor_from_config=False
199200
)
200201

@@ -208,8 +209,8 @@ def test_eviction(self):
208209
cache.get(2)
209210
cache.get(3)
210211

211-
def test_eviction_lru(self):
212-
cache = DeferredCache(
212+
def test_eviction_lru(self) -> None:
213+
cache: DeferredCache[int, str] = DeferredCache(
213214
"test", max_entries=2, apply_cache_factor_from_config=False
214215
)
215216

@@ -227,8 +228,8 @@ def test_eviction_lru(self):
227228
cache.get(1)
228229
cache.get(3)
229230

230-
def test_eviction_iterable(self):
231-
cache = DeferredCache(
231+
def test_eviction_iterable(self) -> None:
232+
cache: DeferredCache[int, List[str]] = DeferredCache(
232233
"test",
233234
max_entries=3,
234235
apply_cache_factor_from_config=False,

tests/util/caches/test_descriptors.py

+14-8
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
import logging
16-
from typing import Iterable, Set, Tuple
16+
from typing import Iterable, Set, Tuple, cast
1717
from unittest import mock
1818

1919
from twisted.internet import defer, reactor
2020
from twisted.internet.defer import CancelledError, Deferred
21+
from twisted.internet.interfaces import IReactorTime
2122

2223
from synapse.api.errors import SynapseError
2324
from synapse.logging.context import (
@@ -37,8 +38,8 @@
3738

3839

3940
def run_on_reactor():
40-
d = defer.Deferred()
41-
reactor.callLater(0, d.callback, 0)
41+
d: "Deferred[int]" = defer.Deferred()
42+
cast(IReactorTime, reactor).callLater(0, d.callback, 0)
4243
return make_deferred_yieldable(d)
4344

4445

@@ -224,7 +225,8 @@ def fn(self, arg1):
224225
callbacks: Set[str] = set()
225226

226227
# set off an asynchronous request
227-
obj.result = origin_d = defer.Deferred()
228+
origin_d: Deferred = defer.Deferred()
229+
obj.result = origin_d
228230

229231
d1 = obj.fn(1, on_invalidate=lambda: callbacks.add("d1"))
230232
self.assertFalse(d1.called)
@@ -262,7 +264,7 @@ def test_cache_logcontexts(self):
262264
"""Check that logcontexts are set and restored correctly when
263265
using the cache."""
264266

265-
complete_lookup = defer.Deferred()
267+
complete_lookup: Deferred = defer.Deferred()
266268

267269
class Cls:
268270
@descriptors.cached()
@@ -772,10 +774,14 @@ def fn(self, arg1, arg2):
772774

773775
@descriptors.cachedList(cached_method_name="fn", list_name="args1")
774776
async def list_fn(self, args1, arg2):
775-
assert current_context().name == "c1"
777+
context = current_context()
778+
assert isinstance(context, LoggingContext)
779+
assert context.name == "c1"
776780
# we want this to behave like an asynchronous function
777781
await run_on_reactor()
778-
assert current_context().name == "c1"
782+
context = current_context()
783+
assert isinstance(context, LoggingContext)
784+
assert context.name == "c1"
779785
return self.mock(args1, arg2)
780786

781787
with LoggingContext("c1") as c1:
@@ -834,7 +840,7 @@ def list_fn(self, args1) -> "Deferred[dict]":
834840
return self.mock(args1)
835841

836842
obj = Cls()
837-
deferred_result = Deferred()
843+
deferred_result: "Deferred[dict]" = Deferred()
838844
obj.mock.return_value = deferred_result
839845

840846
# start off several concurrent lookups of the same key

0 commit comments

Comments
 (0)