Fix-up some type hints in the relations tests. (#11076)

This commit is contained in:
Patrick Cloke 2021-10-14 09:19:35 -04:00 committed by GitHub
parent 50d8601581
commit 1609ccf8fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 64 additions and 51 deletions

1
changelog.d/11076.misc Normal file
View File

@ -0,0 +1 @@
Fix type hints in the relations tests.

View File

@ -92,6 +92,7 @@ files =
tests/handlers/test_user_directory.py, tests/handlers/test_user_directory.py,
tests/rest/client/test_login.py, tests/rest/client/test_login.py,
tests/rest/client/test_auth.py, tests/rest/client/test_auth.py,
tests/rest/client/test_relations.py,
tests/rest/media/v1/test_filepath.py, tests/rest/media/v1/test_filepath.py,
tests/rest/media/v1/test_oembed.py, tests/rest/media/v1/test_oembed.py,
tests/storage/test_state.py, tests/storage/test_state.py,

View File

@ -13,15 +13,15 @@
# limitations under the License. # limitations under the License.
import itertools import itertools
import json import urllib.parse
import urllib from typing import Dict, List, Optional, Tuple
from typing import Optional
from synapse.api.constants import EventTypes, RelationTypes from synapse.api.constants import EventTypes, RelationTypes
from synapse.rest import admin from synapse.rest import admin
from synapse.rest.client import login, register, relations, room from synapse.rest.client import login, register, relations, room
from tests import unittest from tests import unittest
from tests.server import FakeChannel
class RelationsTestCase(unittest.HomeserverTestCase): class RelationsTestCase(unittest.HomeserverTestCase):
@ -34,16 +34,16 @@ class RelationsTestCase(unittest.HomeserverTestCase):
] ]
hijack_auth = False hijack_auth = False
def make_homeserver(self, reactor, clock): def default_config(self) -> dict:
# We need to enable msc1849 support for aggregations # We need to enable msc1849 support for aggregations
config = self.default_config() config = super().default_config()
config["experimental_msc1849_support_enabled"] = True config["experimental_msc1849_support_enabled"] = True
# We enable frozen dicts as relations/edits change event contents, so we # We enable frozen dicts as relations/edits change event contents, so we
# want to test that we don't modify the events in the caches. # want to test that we don't modify the events in the caches.
config["use_frozen_dicts"] = True config["use_frozen_dicts"] = True
return self.setup_test_homeserver(config=config) return config
def prepare(self, reactor, clock, hs): def prepare(self, reactor, clock, hs):
self.user_id, self.user_token = self._create_user("alice") self.user_id, self.user_token = self._create_user("alice")
@ -146,8 +146,8 @@ class RelationsTestCase(unittest.HomeserverTestCase):
self.assertEquals(200, channel.code, channel.json_body) self.assertEquals(200, channel.code, channel.json_body)
expected_event_ids.append(channel.json_body["event_id"]) expected_event_ids.append(channel.json_body["event_id"])
prev_token = None prev_token: Optional[str] = None
found_event_ids = [] found_event_ids: List[str] = []
for _ in range(20): for _ in range(20):
from_token = "" from_token = ""
if prev_token: if prev_token:
@ -203,8 +203,8 @@ class RelationsTestCase(unittest.HomeserverTestCase):
idx += 1 idx += 1
idx %= len(access_tokens) idx %= len(access_tokens)
prev_token = None prev_token: Optional[str] = None
found_groups = {} found_groups: Dict[str, int] = {}
for _ in range(20): for _ in range(20):
from_token = "" from_token = ""
if prev_token: if prev_token:
@ -270,8 +270,8 @@ class RelationsTestCase(unittest.HomeserverTestCase):
channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a") channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
self.assertEquals(200, channel.code, channel.json_body) self.assertEquals(200, channel.code, channel.json_body)
prev_token = None prev_token: Optional[str] = None
found_event_ids = [] found_event_ids: List[str] = []
encoded_key = urllib.parse.quote_plus("👍".encode()) encoded_key = urllib.parse.quote_plus("👍".encode())
for _ in range(20): for _ in range(20):
from_token = "" from_token = ""
@ -677,24 +677,23 @@ class RelationsTestCase(unittest.HomeserverTestCase):
def _send_relation( def _send_relation(
self, self,
relation_type, relation_type: str,
event_type, event_type: str,
key=None, key: Optional[str] = None,
content: Optional[dict] = None, content: Optional[dict] = None,
access_token=None, access_token: Optional[str] = None,
parent_id=None, parent_id: Optional[str] = None,
): ) -> FakeChannel:
"""Helper function to send a relation pointing at `self.parent_id` """Helper function to send a relation pointing at `self.parent_id`
Args: Args:
relation_type (str): One of `RelationTypes` relation_type: One of `RelationTypes`
event_type (str): The type of the event to create event_type: The type of the event to create
parent_id (str): The event_id this relation relates to. If None, then self.parent_id key: The aggregation key used for m.annotation relation type.
key (str|None): The aggregation key used for m.annotation relation content: The content of the created event.
type. access_token: The access token used to send the relation, defaults
content(dict|None): The content of the created event. to `self.user_token`
access_token (str|None): The access token used to send the relation, parent_id: The event_id this relation relates to. If None, then self.parent_id
defaults to `self.user_token`
Returns: Returns:
FakeChannel FakeChannel
@ -712,12 +711,12 @@ class RelationsTestCase(unittest.HomeserverTestCase):
"POST", "POST",
"/_matrix/client/unstable/rooms/%s/send_relation/%s/%s/%s%s" "/_matrix/client/unstable/rooms/%s/send_relation/%s/%s/%s%s"
% (self.room, original_id, relation_type, event_type, query), % (self.room, original_id, relation_type, event_type, query),
json.dumps(content or {}).encode("utf-8"), content or {},
access_token=access_token, access_token=access_token,
) )
return channel return channel
def _create_user(self, localpart): def _create_user(self, localpart: str) -> Tuple[str, str]:
user_id = self.register_user(localpart, "abc123") user_id = self.register_user(localpart, "abc123")
access_token = self.login(localpart, "abc123") access_token = self.login(localpart, "abc123")

View File

@ -1,3 +1,17 @@
# Copyright 2018-2021 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json import json
import logging import logging
from collections import deque from collections import deque
@ -27,9 +41,10 @@ from twisted.python.failure import Failure
from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactorClock from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactorClock
from twisted.web.http_headers import Headers from twisted.web.http_headers import Headers
from twisted.web.resource import IResource from twisted.web.resource import IResource
from twisted.web.server import Site from twisted.web.server import Request, Site
from synapse.http.site import SynapseRequest from synapse.http.site import SynapseRequest
from synapse.types import JsonDict
from synapse.util import Clock from synapse.util import Clock
from tests.utils import setup_test_homeserver as _sth from tests.utils import setup_test_homeserver as _sth
@ -198,14 +213,14 @@ class FakeSite:
def make_request( def make_request(
reactor, reactor,
site: Union[Site, FakeSite], site: Union[Site, FakeSite],
method, method: Union[bytes, str],
path, path: Union[bytes, str],
content=b"", content: Union[bytes, str, JsonDict] = b"",
access_token=None, access_token: Optional[str] = None,
request=SynapseRequest, request: Request = SynapseRequest,
shorthand=True, shorthand: bool = True,
federation_auth_origin=None, federation_auth_origin: Optional[bytes] = None,
content_is_form=False, content_is_form: bool = False,
await_result: bool = True, await_result: bool = True,
custom_headers: Optional[ custom_headers: Optional[
Iterable[Tuple[Union[bytes, str], Union[bytes, str]]] Iterable[Tuple[Union[bytes, str], Union[bytes, str]]]
@ -218,26 +233,23 @@ def make_request(
Returns the fake Channel object which records the response to the request. Returns the fake Channel object which records the response to the request.
Args: Args:
reactor:
site: The twisted Site to use to render the request site: The twisted Site to use to render the request
method: The HTTP request method ("verb").
method (bytes/unicode): The HTTP request method ("verb"). path: The HTTP path, suitably URL encoded (e.g. escaped UTF-8 & spaces and such).
path (bytes/unicode): The HTTP path, suitably URL encoded (e.g. content: The body of the request. JSON-encoded, if a str of bytes.
escaped UTF-8 & spaces and such). access_token: The access token to add as authorization for the request.
content (bytes or dict): The body of the request. JSON-encoded, if request: The request class to create.
a dict.
shorthand: Whether to try and be helpful and prefix the given URL shorthand: Whether to try and be helpful and prefix the given URL
with the usual REST API path, if it doesn't contain it. with the usual REST API path, if it doesn't contain it.
federation_auth_origin (bytes|None): if set to not-None, we will add a fake federation_auth_origin: if set to not-None, we will add a fake
Authorization header pretenting to be the given server name. Authorization header pretenting to be the given server name.
content_is_form: Whether the content is URL encoded form data. Adds the content_is_form: Whether the content is URL encoded form data. Adds the
'Content-Type': 'application/x-www-form-urlencoded' header. 'Content-Type': 'application/x-www-form-urlencoded' header.
custom_headers: (name, value) pairs to add as request headers
await_result: whether to wait for the request to complete rendering. If true, await_result: whether to wait for the request to complete rendering. If true,
will pump the reactor until the the renderer tells the channel the request will pump the reactor until the the renderer tells the channel the request
is finished. is finished.
custom_headers: (name, value) pairs to add as request headers
client_ip: The IP to use as the requesting IP. Useful for testing client_ip: The IP to use as the requesting IP. Useful for testing
ratelimiting. ratelimiting.

View File

@ -46,7 +46,7 @@ from synapse.logging.context import (
set_current_context, set_current_context,
) )
from synapse.server import HomeServer from synapse.server import HomeServer
from synapse.types import UserID, create_requester from synapse.types import JsonDict, UserID, create_requester
from synapse.util import Clock from synapse.util import Clock
from synapse.util.httpresourcetree import create_resource_tree from synapse.util.httpresourcetree import create_resource_tree
from synapse.util.ratelimitutils import FederationRateLimiter from synapse.util.ratelimitutils import FederationRateLimiter
@ -401,7 +401,7 @@ class HomeserverTestCase(TestCase):
self, self,
method: Union[bytes, str], method: Union[bytes, str],
path: Union[bytes, str], path: Union[bytes, str],
content: Union[bytes, dict] = b"", content: Union[bytes, str, JsonDict] = b"",
access_token: Optional[str] = None, access_token: Optional[str] = None,
request: Type[T] = SynapseRequest, request: Type[T] = SynapseRequest,
shorthand: bool = True, shorthand: bool = True,