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

Commit 7f2cabf

Browse files
authored
Fix-up type hints for tests.push module. (#14816)
1 parent d6bda5a commit 7f2cabf

File tree

7 files changed

+67
-62
lines changed

7 files changed

+67
-62
lines changed

changelog.d/14816.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add missing type hints.

mypy.ini

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,6 @@ exclude = (?x)
4848
|tests/logging/__init__.py
4949
|tests/logging/test_terse_json.py
5050
|tests/module_api/test_api.py
51-
|tests/push/test_email.py
52-
|tests/push/test_presentable_names.py
53-
|tests/push/test_push_rule_evaluator.py
5451
|tests/rest/client/test_transactions.py
5552
|tests/rest/media/v1/test_media_storage.py
5653
|tests/server.py
@@ -101,7 +98,7 @@ disallow_untyped_defs = True
10198
[mypy-tests.metrics.*]
10299
disallow_untyped_defs = True
103100

104-
[mypy-tests.push.test_bulk_push_rule_evaluator]
101+
[mypy-tests.push.*]
105102
disallow_untyped_defs = True
106103

107104
[mypy-tests.rest.*]

stubs/synapse/synapse_rust/push.pyi

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Collection, Dict, Mapping, Optional, Sequence, Tuple, Union
1+
from typing import Any, Collection, Dict, Mapping, Optional, Sequence, Set, Tuple, Union
22

33
from synapse.types import JsonDict
44

@@ -54,3 +54,6 @@ class PushRuleEvaluator:
5454
user_id: Optional[str],
5555
display_name: Optional[str],
5656
) -> Collection[Union[Mapping, str]]: ...
57+
def matches(
58+
self, condition: JsonDict, user_id: Optional[str], display_name: Optional[str]
59+
) -> bool: ...

tests/push/test_email.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,25 +13,28 @@
1313
# limitations under the License.
1414
import email.message
1515
import os
16-
from typing import Dict, List, Sequence, Tuple
16+
from typing import Any, Dict, List, Sequence, Tuple
1717

1818
import attr
1919
import pkg_resources
2020

2121
from twisted.internet.defer import Deferred
22+
from twisted.test.proto_helpers import MemoryReactor
2223

2324
import synapse.rest.admin
2425
from synapse.api.errors import Codes, SynapseError
2526
from synapse.rest.client import login, room
27+
from synapse.server import HomeServer
28+
from synapse.util import Clock
2629

2730
from tests.unittest import HomeserverTestCase
2831

2932

30-
@attr.s
33+
@attr.s(auto_attribs=True)
3134
class _User:
3235
"Helper wrapper for user ID and access token"
33-
id = attr.ib()
34-
token = attr.ib()
36+
id: str
37+
token: str
3538

3639

3740
class EmailPusherTests(HomeserverTestCase):
@@ -41,10 +44,9 @@ class EmailPusherTests(HomeserverTestCase):
4144
room.register_servlets,
4245
login.register_servlets,
4346
]
44-
user_id = True
4547
hijack_auth = False
4648

47-
def make_homeserver(self, reactor, clock):
49+
def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
4850

4951
config = self.default_config()
5052
config["email"] = {
@@ -72,17 +74,17 @@ def make_homeserver(self, reactor, clock):
7274
# List[Tuple[Deferred, args, kwargs]]
7375
self.email_attempts: List[Tuple[Deferred, Sequence, Dict]] = []
7476

75-
def sendmail(*args, **kwargs):
77+
def sendmail(*args: Any, **kwargs: Any) -> Deferred:
7678
# This mocks out synapse.reactor.send_email._sendmail.
77-
d = Deferred()
79+
d: Deferred = Deferred()
7880
self.email_attempts.append((d, args, kwargs))
7981
return d
8082

81-
hs.get_send_email_handler()._sendmail = sendmail
83+
hs.get_send_email_handler()._sendmail = sendmail # type: ignore[assignment]
8284

8385
return hs
8486

85-
def prepare(self, reactor, clock, hs):
87+
def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
8688
# Register the user who gets notified
8789
self.user_id = self.register_user("user", "pass")
8890
self.access_token = self.login("user", "pass")
@@ -129,7 +131,7 @@ def prepare(self, reactor, clock, hs):
129131
self.auth_handler = hs.get_auth_handler()
130132
self.store = hs.get_datastores().main
131133

132-
def test_need_validated_email(self):
134+
def test_need_validated_email(self) -> None:
133135
"""Test that we can only add an email pusher if the user has validated
134136
their email.
135137
"""
@@ -151,7 +153,7 @@ def test_need_validated_email(self):
151153
self.assertEqual(400, cm.exception.code)
152154
self.assertEqual(Codes.THREEPID_NOT_FOUND, cm.exception.errcode)
153155

154-
def test_simple_sends_email(self):
156+
def test_simple_sends_email(self) -> None:
155157
# Create a simple room with two users
156158
room = self.helper.create_room_as(self.user_id, tok=self.access_token)
157159
self.helper.invite(
@@ -171,7 +173,7 @@ def test_simple_sends_email(self):
171173

172174
self._check_for_mail()
173175

174-
def test_invite_sends_email(self):
176+
def test_invite_sends_email(self) -> None:
175177
# Create a room and invite the user to it
176178
room = self.helper.create_room_as(self.others[0].id, tok=self.others[0].token)
177179
self.helper.invite(
@@ -184,7 +186,7 @@ def test_invite_sends_email(self):
184186
# We should get emailed about the invite
185187
self._check_for_mail()
186188

187-
def test_invite_to_empty_room_sends_email(self):
189+
def test_invite_to_empty_room_sends_email(self) -> None:
188190
# Create a room and invite the user to it
189191
room = self.helper.create_room_as(self.others[0].id, tok=self.others[0].token)
190192
self.helper.invite(
@@ -200,7 +202,7 @@ def test_invite_to_empty_room_sends_email(self):
200202
# We should get emailed about the invite
201203
self._check_for_mail()
202204

203-
def test_multiple_members_email(self):
205+
def test_multiple_members_email(self) -> None:
204206
# We want to test multiple notifications, so we pause processing of push
205207
# while we send messages.
206208
self.pusher._pause_processing()
@@ -227,7 +229,7 @@ def test_multiple_members_email(self):
227229
# We should get emailed about those messages
228230
self._check_for_mail()
229231

230-
def test_multiple_rooms(self):
232+
def test_multiple_rooms(self) -> None:
231233
# We want to test multiple notifications from multiple rooms, so we pause
232234
# processing of push while we send messages.
233235
self.pusher._pause_processing()
@@ -257,7 +259,7 @@ def test_multiple_rooms(self):
257259
# We should get emailed about those messages
258260
self._check_for_mail()
259261

260-
def test_room_notifications_include_avatar(self):
262+
def test_room_notifications_include_avatar(self) -> None:
261263
# Create a room and set its avatar.
262264
room = self.helper.create_room_as(self.user_id, tok=self.access_token)
263265
self.helper.send_state(
@@ -290,7 +292,7 @@ def test_room_notifications_include_avatar(self):
290292
)
291293
self.assertIn("_matrix/media/v1/thumbnail/DUMMY_MEDIA_ID", html)
292294

293-
def test_empty_room(self):
295+
def test_empty_room(self) -> None:
294296
"""All users leaving a room shouldn't cause the pusher to break."""
295297
# Create a simple room with two users
296298
room = self.helper.create_room_as(self.user_id, tok=self.access_token)
@@ -309,7 +311,7 @@ def test_empty_room(self):
309311
# We should get emailed about that message
310312
self._check_for_mail()
311313

312-
def test_empty_room_multiple_messages(self):
314+
def test_empty_room_multiple_messages(self) -> None:
313315
"""All users leaving a room shouldn't cause the pusher to break."""
314316
# Create a simple room with two users
315317
room = self.helper.create_room_as(self.user_id, tok=self.access_token)
@@ -329,7 +331,7 @@ def test_empty_room_multiple_messages(self):
329331
# We should get emailed about that message
330332
self._check_for_mail()
331333

332-
def test_encrypted_message(self):
334+
def test_encrypted_message(self) -> None:
333335
room = self.helper.create_room_as(self.user_id, tok=self.access_token)
334336
self.helper.invite(
335337
room=room, src=self.user_id, tok=self.access_token, targ=self.others[0].id
@@ -342,7 +344,7 @@ def test_encrypted_message(self):
342344
# We should get emailed about that message
343345
self._check_for_mail()
344346

345-
def test_no_email_sent_after_removed(self):
347+
def test_no_email_sent_after_removed(self) -> None:
346348
# Create a simple room with two users
347349
room = self.helper.create_room_as(self.user_id, tok=self.access_token)
348350
self.helper.invite(
@@ -379,7 +381,7 @@ def test_no_email_sent_after_removed(self):
379381
pushers = list(pushers)
380382
self.assertEqual(len(pushers), 0)
381383

382-
def test_remove_unlinked_pushers_background_job(self):
384+
def test_remove_unlinked_pushers_background_job(self) -> None:
383385
"""Checks that all existing pushers associated with unlinked email addresses are removed
384386
upon running the remove_deleted_email_pushers background update.
385387
"""

tests/push/test_http.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
4646

4747
m = Mock()
4848

49-
def post_json_get_json(url, body):
49+
def post_json_get_json(url: str, body: JsonDict) -> Deferred:
5050
d: Deferred = Deferred()
5151
self.push_attempts.append((d, url, body))
5252
return make_deferred_yieldable(d)

tests/push/test_presentable_names.py

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
from typing import Iterable, Optional, Tuple
15+
from typing import Iterable, List, Optional, Tuple, cast
1616

1717
from synapse.api.constants import EventTypes, Membership
1818
from synapse.api.room_versions import RoomVersions
19-
from synapse.events import FrozenEvent
19+
from synapse.events import EventBase, FrozenEvent
2020
from synapse.push.presentable_names import calculate_room_name
2121
from synapse.types import StateKey, StateMap
2222

@@ -51,13 +51,15 @@ def __init__(self, events: Iterable[Tuple[StateKey, dict]]):
5151
)
5252

5353
async def get_event(
54-
self, event_id: StateKey, allow_none: bool = False
54+
self, event_id: str, allow_none: bool = False
5555
) -> Optional[FrozenEvent]:
5656
assert allow_none, "Mock not configured for allow_none = False"
5757

58-
return self._events.get(event_id)
58+
# Decode the state key from the event ID.
59+
state_key = cast(Tuple[str, str], tuple(event_id.split("|", 1)))
60+
return self._events.get(state_key)
5961

60-
async def get_events(self, event_ids: Iterable[StateKey]):
62+
async def get_events(self, event_ids: Iterable[StateKey]) -> StateMap[EventBase]:
6163
# This is cheating since it just returns all events.
6264
return self._events
6365

@@ -68,27 +70,27 @@ class PresentableNamesTestCase(unittest.HomeserverTestCase):
6870

6971
def _calculate_room_name(
7072
self,
71-
events: StateMap[dict],
73+
events: Iterable[Tuple[Tuple[str, str], dict]],
7274
user_id: str = "",
7375
fallback_to_members: bool = True,
7476
fallback_to_single_member: bool = True,
75-
):
76-
# This isn't 100% accurate, but works with MockDataStore.
77-
room_state_ids = {k[0]: k[0] for k in events}
77+
) -> Optional[str]:
78+
# Encode the state key into the event ID.
79+
room_state_ids = {k[0]: "|".join(k[0]) for k in events}
7880

7981
return self.get_success(
8082
calculate_room_name(
81-
MockDataStore(events),
83+
MockDataStore(events), # type: ignore[arg-type]
8284
room_state_ids,
8385
user_id or self.USER_ID,
8486
fallback_to_members,
8587
fallback_to_single_member,
8688
)
8789
)
8890

89-
def test_name(self):
91+
def test_name(self) -> None:
9092
"""A room name event should be used."""
91-
events = [
93+
events: List[Tuple[Tuple[str, str], dict]] = [
9294
((EventTypes.Name, ""), {"name": "test-name"}),
9395
]
9496
self.assertEqual("test-name", self._calculate_room_name(events))
@@ -100,9 +102,9 @@ def test_name(self):
100102
events = [((EventTypes.Name, ""), {"name": 1})]
101103
self.assertEqual(1, self._calculate_room_name(events))
102104

103-
def test_canonical_alias(self):
105+
def test_canonical_alias(self) -> None:
104106
"""An canonical alias should be used."""
105-
events = [
107+
events: List[Tuple[Tuple[str, str], dict]] = [
106108
((EventTypes.CanonicalAlias, ""), {"alias": "#test-name:test"}),
107109
]
108110
self.assertEqual("#test-name:test", self._calculate_room_name(events))
@@ -114,9 +116,9 @@ def test_canonical_alias(self):
114116
events = [((EventTypes.CanonicalAlias, ""), {"alias": "test-name"})]
115117
self.assertEqual("Empty Room", self._calculate_room_name(events))
116118

117-
def test_invite(self):
119+
def test_invite(self) -> None:
118120
"""An invite has special behaviour."""
119-
events = [
121+
events: List[Tuple[Tuple[str, str], dict]] = [
120122
((EventTypes.Member, self.USER_ID), {"membership": Membership.INVITE}),
121123
((EventTypes.Member, self.OTHER_USER_ID), {"displayname": "Other User"}),
122124
]
@@ -140,9 +142,9 @@ def test_invite(self):
140142
]
141143
self.assertEqual("Room Invite", self._calculate_room_name(events))
142144

143-
def test_no_members(self):
145+
def test_no_members(self) -> None:
144146
"""Behaviour of an empty room."""
145-
events = []
147+
events: List[Tuple[Tuple[str, str], dict]] = []
146148
self.assertEqual("Empty Room", self._calculate_room_name(events))
147149

148150
# Note that events with invalid (or missing) membership are ignored.
@@ -152,7 +154,7 @@ def test_no_members(self):
152154
]
153155
self.assertEqual("Empty Room", self._calculate_room_name(events))
154156

155-
def test_no_other_members(self):
157+
def test_no_other_members(self) -> None:
156158
"""Behaviour of a room with no other members in it."""
157159
events = [
158160
(
@@ -185,7 +187,7 @@ def test_no_other_members(self):
185187
self._calculate_room_name(events, user_id=self.OTHER_USER_ID),
186188
)
187189

188-
def test_one_other_member(self):
190+
def test_one_other_member(self) -> None:
189191
"""Behaviour of a room with a single other member."""
190192
events = [
191193
((EventTypes.Member, self.USER_ID), {"membership": Membership.JOIN}),
@@ -209,7 +211,7 @@ def test_one_other_member(self):
209211
]
210212
self.assertEqual("@user:test", self._calculate_room_name(events))
211213

212-
def test_other_members(self):
214+
def test_other_members(self) -> None:
213215
"""Behaviour of a room with multiple other members."""
214216
# Two other members.
215217
events = [

0 commit comments

Comments
 (0)