1
0

Use type hinting generics in standard collections (#19046)

aka PEP 585, added in Python 3.9

 - https://peps.python.org/pep-0585/
 - https://docs.astral.sh/ruff/rules/non-pep585-annotation/
This commit is contained in:
Andrew Ferrazzutti
2025-10-22 17:48:19 -04:00
committed by GitHub
parent cba3a814c6
commit fc244bb592
539 changed files with 4599 additions and 5066 deletions
+5 -6
View File
@@ -20,7 +20,6 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List
from unittest.mock import patch
import jsonschema
@@ -50,7 +49,7 @@ class FilteringTestCase(unittest.HomeserverTestCase):
def test_errors_on_invalid_filters(self) -> None:
# See USER_FILTER_SCHEMA for the filter schema.
invalid_filters: List[JsonDict] = [
invalid_filters: list[JsonDict] = [
# `account_data` must be a dictionary
{"account_data": "Hello World"},
# `event_format` must be "client" or "federation"
@@ -67,7 +66,7 @@ class FilteringTestCase(unittest.HomeserverTestCase):
def test_ignores_unknown_filter_fields(self) -> None:
# For forward compatibility, we must ignore unknown filter fields.
# See USER_FILTER_SCHEMA for the filter schema.
filters: List[JsonDict] = [
filters: list[JsonDict] = [
{"org.matrix.msc9999.future_option": True},
{"presence": {"org.matrix.msc9999.future_option": True}},
{"room": {"org.matrix.msc9999.future_option": True}},
@@ -78,7 +77,7 @@ class FilteringTestCase(unittest.HomeserverTestCase):
# Must not raise.
def test_valid_filters(self) -> None:
valid_filters: List[JsonDict] = [
valid_filters: list[JsonDict] = [
{
"room": {
"timeline": {"limit": 20},
@@ -557,7 +556,7 @@ class FilteringTestCase(unittest.HomeserverTestCase):
room_id="!foo:bar",
),
]
jsondicts: List[JsonDict] = [{}]
jsondicts: list[JsonDict] = [{}]
# For the following tests we patch the datastore method (intead of injecting
# events). This is a bit cheeky, but tests the logic of _check_event_relations.
@@ -565,7 +564,7 @@ class FilteringTestCase(unittest.HomeserverTestCase):
# Filter for a particular sender.
definition = {"related_by_senders": ["@foo:bar"]}
async def events_have_relations(*args: object, **kwargs: object) -> List[str]:
async def events_have_relations(*args: object, **kwargs: object) -> list[str]:
return ["$with_relation"]
with patch.object(
+2 -3
View File
@@ -17,7 +17,6 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List
from unittest.mock import Mock, patch
from parameterized import parameterized
@@ -58,7 +57,7 @@ class FederationReaderOpenIDListenerTests(HomeserverTestCase):
(["openid"], "auth_fail"),
]
)
def test_openid_listener(self, names: List[str], expectation: str) -> None:
def test_openid_listener(self, names: list[str], expectation: str) -> None:
"""
Test different openid listener configurations.
@@ -106,7 +105,7 @@ class SynapseHomeserverOpenIDListenerTests(HomeserverTestCase):
(["openid"], "auth_fail"),
]
)
def test_openid_listener(self, names: List[str], expectation: str) -> None:
def test_openid_listener(self, names: list[str], expectation: str) -> None:
"""
Test different openid listener configurations.
+3 -3
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, List, Mapping, Optional, Sequence, Union
from typing import Any, Mapping, Optional, Sequence, Union
from unittest.mock import Mock
from twisted.internet.testing import MemoryReactor
@@ -81,7 +81,7 @@ class ApplicationServiceApiTestCase(unittest.HomeserverTestCase):
url: str,
args: Mapping[Any, Any],
headers: Mapping[Union[str, bytes], Sequence[Union[str, bytes]]],
) -> List[JsonDict]:
) -> list[JsonDict]:
# Ensure the access token is passed as a header.
if not headers or not headers.get(b"Authorization"):
raise RuntimeError("Access token not provided")
@@ -157,7 +157,7 @@ class ApplicationServiceApiTestCase(unittest.HomeserverTestCase):
headers: Optional[
Mapping[Union[str, bytes], Sequence[Union[str, bytes]]]
] = None,
) -> List[JsonDict]:
) -> list[JsonDict]:
# Ensure the access token is passed as a both a query param and in the headers.
if not args.get(b"access_token"):
raise RuntimeError("Access token should be provided in query params.")
+4 -4
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List, Optional, Sequence, Tuple
from typing import Optional, Sequence
from unittest.mock import AsyncMock, Mock
from typing_extensions import TypeAlias
@@ -288,11 +288,11 @@ class ApplicationServiceSchedulerRecovererTestCase(unittest.HomeserverTestCase):
# Corresponds to synapse.appservice.scheduler._TransactionController.send
TxnCtrlArgs: TypeAlias = """
defer.Deferred[
Tuple[
tuple[
ApplicationService,
Sequence[EventBase],
Optional[List[JsonDict]],
Optional[List[JsonDict]],
Optional[list[JsonDict]],
Optional[list[JsonDict]],
Optional[TransactionOneTimeKeysCount],
Optional[TransactionUnusedFallbackKeys],
Optional[DeviceListUpdates],
+1 -2
View File
@@ -24,7 +24,6 @@ import tempfile
import unittest
from contextlib import redirect_stdout
from io import StringIO
from typing import List
from synapse.config.homeserver import HomeServerConfig
@@ -61,7 +60,7 @@ class ConfigFileTestCase(unittest.TestCase):
with open(self.config_file, "w") as f:
f.write("".join(contents))
def add_lines_to_config(self, lines: List[str]) -> None:
def add_lines_to_config(self, lines: list[str]) -> None:
with open(self.config_file, "a") as f:
for line in lines:
f.write(line + "\n")
+15 -15
View File
@@ -19,7 +19,7 @@
#
#
import time
from typing import Any, Dict, List, Optional, cast
from typing import Any, Optional, cast
from unittest.mock import Mock
import attr
@@ -60,7 +60,7 @@ class MockPerspectiveServer:
self.server_name = "mock_server"
self.key = signedjson.key.generate_signing_key("0")
def get_verify_keys(self) -> Dict[str, str]:
def get_verify_keys(self) -> dict[str, str]:
vk = signedjson.key.get_verify_key(self.key)
return {"%s:%s" % (vk.alg, vk.version): encode_verify_key_base64(vk)}
@@ -107,8 +107,8 @@ class KeyringTestCase(unittest.HomeserverTestCase):
first_lookup_deferred: "Deferred[None]" = Deferred()
async def first_lookup_fetch(
server_name: str, key_ids: List[str], minimum_valid_until_ts: int
) -> Dict[str, FetchKeyResult]:
server_name: str, key_ids: list[str], minimum_valid_until_ts: int
) -> dict[str, FetchKeyResult]:
# self.assertEqual(current_context().request.id, "context_11")
self.assertEqual(server_name, "server10")
self.assertEqual(key_ids, [get_key_id(key1)])
@@ -152,8 +152,8 @@ class KeyringTestCase(unittest.HomeserverTestCase):
# should block rather than start a second call
async def second_lookup_fetch(
server_name: str, key_ids: List[str], minimum_valid_until_ts: int
) -> Dict[str, FetchKeyResult]:
server_name: str, key_ids: list[str], minimum_valid_until_ts: int
) -> dict[str, FetchKeyResult]:
# self.assertEqual(current_context().request.id, "context_12")
return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 100)}
@@ -276,8 +276,8 @@ class KeyringTestCase(unittest.HomeserverTestCase):
# set up a mock fetcher which will return the key
async def get_keys(
server_name: str, key_ids: List[str], minimum_valid_until_ts: int
) -> Dict[str, FetchKeyResult]:
server_name: str, key_ids: list[str], minimum_valid_until_ts: int
) -> dict[str, FetchKeyResult]:
self.assertEqual(server_name, self.hs.hostname)
self.assertEqual(key_ids, [get_key_id(key2)])
@@ -302,8 +302,8 @@ class KeyringTestCase(unittest.HomeserverTestCase):
key1 = signedjson.key.generate_signing_key("1")
async def get_keys(
server_name: str, key_ids: List[str], minimum_valid_until_ts: int
) -> Dict[str, FetchKeyResult]:
server_name: str, key_ids: list[str], minimum_valid_until_ts: int
) -> dict[str, FetchKeyResult]:
# there should only be one request object (with the max validity)
self.assertEqual(server_name, "server1")
self.assertEqual(key_ids, [get_key_id(key1)])
@@ -344,16 +344,16 @@ class KeyringTestCase(unittest.HomeserverTestCase):
key1 = signedjson.key.generate_signing_key("1")
async def get_keys1(
server_name: str, key_ids: List[str], minimum_valid_until_ts: int
) -> Dict[str, FetchKeyResult]:
server_name: str, key_ids: list[str], minimum_valid_until_ts: int
) -> dict[str, FetchKeyResult]:
self.assertEqual(server_name, "server1")
self.assertEqual(key_ids, [get_key_id(key1)])
self.assertEqual(minimum_valid_until_ts, 1500)
return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 800)}
async def get_keys2(
server_name: str, key_ids: List[str], minimum_valid_until_ts: int
) -> Dict[str, FetchKeyResult]:
server_name: str, key_ids: list[str], minimum_valid_until_ts: int
) -> dict[str, FetchKeyResult]:
self.assertEqual(server_name, "server1")
self.assertEqual(key_ids, [get_key_id(key1)])
self.assertEqual(minimum_valid_until_ts, 1500)
@@ -701,7 +701,7 @@ class PerspectivesKeyFetcherTestCase(unittest.HomeserverTestCase):
SERVER_NAME, testkey, VALID_UNTIL_TS
)
def get_key_from_perspectives(response: JsonDict) -> Dict[str, FetchKeyResult]:
def get_key_from_perspectives(response: JsonDict) -> dict[str, FetchKeyResult]:
fetcher = PerspectivesKeyFetcher(self.hs)
self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
return self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
+4 -4
View File
@@ -21,7 +21,7 @@
import asyncio
from asyncio import Future
from http import HTTPStatus
from typing import Any, Awaitable, Dict, List, Optional, Tuple, TypeVar, cast
from typing import Any, Awaitable, Optional, TypeVar, cast
from unittest.mock import Mock
import attr
@@ -527,7 +527,7 @@ def sync_join(
testcase: HomeserverTestCase,
user_id: str,
since_token: Optional[StreamToken] = None,
) -> Tuple[List[JoinedSyncResult], StreamToken]:
) -> tuple[list[JoinedSyncResult], StreamToken]:
"""Perform a sync request for the given user and return the user join updates
they've received, as well as the next_batch token.
@@ -765,7 +765,7 @@ class MockEvent:
sender: str
type: str
content: Dict[str, Any]
content: dict[str, Any]
room_id: str = "!someroom"
state_key: Optional[str] = None
@@ -802,7 +802,7 @@ def make_multiple_awaitable(result: TV) -> Awaitable[TV]:
def create_module(
config_override: Optional[Dict[str, Any]] = None, worker_name: Optional[str] = None
config_override: Optional[dict[str, Any]] = None, worker_name: Optional[str] = None
) -> InviteAutoAccepter:
# Create a mock based on the ModuleApi spec, but override some mocked functions
# because some capabilities are needed for running the tests.
+7 -7
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Dict, Iterable, List, Optional, Set, Tuple, Union
from typing import Iterable, Optional, Union
from unittest.mock import AsyncMock, Mock
import attr
@@ -46,7 +46,7 @@ from tests.unittest import (
@attr.s
class PresenceRouterTestConfig:
users_who_should_receive_all_presence = attr.ib(type=List[str], default=[])
users_who_should_receive_all_presence = attr.ib(type=list[str], default=[])
class LegacyPresenceRouterTestModule:
@@ -56,14 +56,14 @@ class LegacyPresenceRouterTestModule:
async def get_users_for_states(
self, state_updates: Iterable[UserPresenceState]
) -> Dict[str, Set[UserPresenceState]]:
) -> dict[str, set[UserPresenceState]]:
users_to_state = {
user_id: set(state_updates)
for user_id in self._config.users_who_should_receive_all_presence
}
return users_to_state
async def get_interested_users(self, user_id: str) -> Union[Set[str], str]:
async def get_interested_users(self, user_id: str) -> Union[set[str], str]:
if user_id in self._config.users_who_should_receive_all_presence:
return PresenceRouter.ALL_USERS
@@ -106,14 +106,14 @@ class PresenceRouterTestModule:
async def get_users_for_states(
self, state_updates: Iterable[UserPresenceState]
) -> Dict[str, Set[UserPresenceState]]:
) -> dict[str, set[UserPresenceState]]:
users_to_state = {
user_id: set(state_updates)
for user_id in self._config.users_who_should_receive_all_presence
}
return users_to_state
async def get_interested_users(self, user_id: str) -> Union[Set[str], str]:
async def get_interested_users(self, user_id: str) -> Union[set[str], str]:
if user_id in self._config.users_who_should_receive_all_presence:
return PresenceRouter.ALL_USERS
@@ -511,7 +511,7 @@ def sync_presence(
testcase: HomeserverTestCase,
user_id: str,
since_token: Optional[StreamToken] = None,
) -> Tuple[List[UserPresenceState], StreamToken]:
) -> tuple[list[UserPresenceState], StreamToken]:
"""Perform a sync request for the given user and return the user presence updates
they've received, as well as the next_batch token.
+2 -2
View File
@@ -20,7 +20,7 @@
#
import unittest as stdlib_unittest
from typing import Any, List, Mapping, Optional
from typing import Any, Mapping, Optional
import attr
from parameterized import parameterized
@@ -648,7 +648,7 @@ class SerializeEventTestCase(stdlib_unittest.TestCase):
def serialize(
self,
ev: EventBase,
fields: Optional[List[str]],
fields: Optional[list[str]],
include_admin_metadata: bool = False,
) -> JsonDict:
return serialize_event(
+6 -6
View File
@@ -1,4 +1,4 @@
from typing import Callable, Collection, List, Optional, Tuple
from typing import Callable, Collection, Optional
from unittest import mock
from unittest.mock import AsyncMock, Mock
@@ -55,8 +55,8 @@ class FederationCatchUpTestCases(FederatingHomeserverTestCase):
)
# whenever send_transaction is called, record the pdu data
self.pdus: List[JsonDict] = []
self.failed_pdus: List[JsonDict] = []
self.pdus: list[JsonDict] = []
self.failed_pdus: list[JsonDict] = []
self.is_online = True
self.federation_transport_client.send_transaction.side_effect = (
self.record_transaction
@@ -269,7 +269,7 @@ class FederationCatchUpTestCases(FederatingHomeserverTestCase):
def make_fake_destination_queue(
self, destination: str = "host2"
) -> Tuple[PerDestinationQueue, List[EventBase]]:
) -> tuple[PerDestinationQueue, list[EventBase]]:
"""
Makes a fake per-destination queue.
"""
@@ -279,8 +279,8 @@ class FederationCatchUpTestCases(FederatingHomeserverTestCase):
async def fake_send(
destination_tm: str,
pending_pdus: List[EventBase],
_pending_edus: List[Edu],
pending_pdus: list[EventBase],
_pending_edus: list[Edu],
) -> None:
assert destination == destination_tm
results_list.extend(pending_pdus)
@@ -23,7 +23,7 @@ import logging
import time
import urllib.parse
from http import HTTPStatus
from typing import Any, Callable, Optional, Set, Tuple, TypeVar, Union
from typing import Any, Callable, Optional, TypeVar, Union
from unittest.mock import Mock
import attr
@@ -147,7 +147,7 @@ class OutOfBandMembershipTests(unittest.FederatingHomeserverTestCase):
def do_sync(
self, sync_body: JsonDict, *, since: Optional[str] = None, tok: str
) -> Tuple[JsonDict, str]:
) -> tuple[JsonDict, str]:
"""Do a sliding sync request with given body.
Asserts the request was successful.
@@ -350,7 +350,7 @@ class OutOfBandMembershipTests(unittest.FederatingHomeserverTestCase):
self.federation_http_client.get_json.side_effect = get_json
# PDU's that hs1 sent to hs2
collected_pdus_from_hs1_federation_send: Set[str] = set()
collected_pdus_from_hs1_federation_send: set[str] = set()
async def put_json(
destination: str,
@@ -503,7 +503,7 @@ class OutOfBandMembershipTests(unittest.FederatingHomeserverTestCase):
T = TypeVar("T")
# PDU's that hs1 sent to hs2
collected_pdus_from_hs1_federation_send: Set[str] = set()
collected_pdus_from_hs1_federation_send: set[str] = set()
async def put_json(
destination: str,
+5 -5
View File
@@ -17,7 +17,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Callable, FrozenSet, List, Optional, Set
from typing import Callable, Optional
from unittest.mock import AsyncMock, Mock
from signedjson import key, sign
@@ -435,7 +435,7 @@ class FederationSenderPresenceTestCases(HomeserverTestCase):
# A set of all user presence we see, this should end up matching the
# number we sent out above.
seen_users: Set[str] = set()
seen_users: set[str] = set()
for edu in presence_edus:
presence_states = edu["content"]["push"]
@@ -483,12 +483,12 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
# stub out `get_rooms_for_user` and `get_current_hosts_in_room` so that the
# server thinks the user shares a room with `@user2:host2`
def get_rooms_for_user(user_id: str) -> "defer.Deferred[FrozenSet[str]]":
def get_rooms_for_user(user_id: str) -> "defer.Deferred[frozenset[str]]":
return defer.succeed(frozenset({test_room_id}))
hs.get_datastores().main.get_rooms_for_user = get_rooms_for_user # type: ignore[assignment]
async def get_current_hosts_in_room(room_id: str) -> Set[str]:
async def get_current_hosts_in_room(room_id: str) -> set[str]:
if room_id == test_room_id:
return {"host2"}
else:
@@ -504,7 +504,7 @@ class FederationSenderDevicesTestCases(HomeserverTestCase):
self.device_handler = device_handler
# whenever send_transaction is called, record the edu data
self.edus: List[JsonDict] = []
self.edus: list[JsonDict] = []
self.federation_transport_client.send_transaction.side_effect = (
self.record_transaction
)
@@ -20,7 +20,6 @@
#
from http import HTTPStatus
from typing import Dict, List, Tuple
from twisted.web.resource import Resource
@@ -52,14 +51,14 @@ class CancellableFederationServlet(BaseFederationServlet):
@cancellable
async def on_GET(
self, origin: str, content: None, query: Dict[bytes, List[bytes]]
) -> Tuple[int, JsonDict]:
self, origin: str, content: None, query: dict[bytes, list[bytes]]
) -> tuple[int, JsonDict]:
await self.clock.sleep(1.0)
return HTTPStatus.OK, {"result": True}
async def on_POST(
self, origin: str, content: JsonDict, query: Dict[bytes, List[bytes]]
) -> Tuple[int, JsonDict]:
self, origin: str, content: JsonDict, query: dict[bytes, list[bytes]]
) -> tuple[int, JsonDict]:
await self.clock.sleep(1.0)
return HTTPStatus.OK, {"result": True}
+2 -2
View File
@@ -20,7 +20,7 @@
#
import json
from typing import List, Optional
from typing import Optional
from unittest.mock import Mock
import ijson.common
@@ -98,7 +98,7 @@ class SendJoinParserTestCase(TestCase):
def test_servers_in_room(self) -> None:
"""Check that the servers_in_room field is correctly parsed"""
def parse(response: JsonDict) -> Optional[List[str]]:
def parse(response: JsonDict) -> Optional[list[str]]:
parser = SendJoinParser(RoomVersions.V1, False)
serialised_response = json.dumps(response).encode()
+3 -3
View File
@@ -19,7 +19,7 @@
#
#
from collections import OrderedDict
from typing import Any, Dict, List, Optional
from typing import Any, Optional
from twisted.internet.testing import MemoryReactor
@@ -161,8 +161,8 @@ class KnockingStrippedStateEventHelperMixin(HomeserverTestCase):
def check_knock_room_state_against_room_state(
self,
knock_room_state: List[Dict],
expected_room_state: Dict,
knock_room_state: list[dict],
expected_room_state: dict,
) -> None:
"""Test a list of stripped room state events received over federation against a
dict of expected state events.
+4 -6
View File
@@ -24,9 +24,7 @@ from typing import (
Any,
Awaitable,
Callable,
Dict,
Iterable,
List,
Optional,
TypeVar,
)
@@ -450,7 +448,7 @@ class ApplicationServicesHandlerSendEventsTestCase(unittest.HomeserverTestCase):
hs.get_application_service_handler().scheduler.txn_ctrl.send = self.send_mock # type: ignore[method-assign]
# Mock out application services, and allow defining our own in tests
self._services: List[ApplicationService] = []
self._services: list[ApplicationService] = []
self.hs.get_datastores().main.get_app_services = Mock( # type: ignore[method-assign]
return_value=self._services
)
@@ -884,7 +882,7 @@ class ApplicationServicesHandlerSendEventsTestCase(unittest.HomeserverTestCase):
# Count the total number of to-device messages that were sent out per-service.
# Ensure that we only sent to-device messages to interested services, and that
# each interested service received the full count of to-device messages.
service_id_to_message_count: Dict[str, int] = {}
service_id_to_message_count: dict[str, int] = {}
for call in self.send_mock.call_args_list:
(
@@ -1023,7 +1021,7 @@ class ApplicationServicesHandlerSendEventsTestCase(unittest.HomeserverTestCase):
def _register_application_service(
self,
namespaces: Optional[Dict[str, Iterable[Dict]]] = None,
namespaces: Optional[dict[str, Iterable[dict]]] = None,
) -> ApplicationService:
"""
Register a new application service, with the given namespaces of interest.
@@ -1073,7 +1071,7 @@ class ApplicationServicesHandlerDeviceListsTestCase(unittest.HomeserverTestCase)
hs.get_application_service_api().put_json = self.put_json # type: ignore[method-assign]
# Mock out application services, and allow defining our own in tests
self._services: List[ApplicationService] = []
self._services: list[ApplicationService] = []
self.hs.get_datastores().main.get_app_services = Mock( # type: ignore[method-assign]
return_value=self._services
)
+2 -2
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, Dict
from typing import Any
from unittest.mock import AsyncMock, Mock
from twisted.internet.testing import MemoryReactor
@@ -35,7 +35,7 @@ SERVER_URL = "https://issuer/"
class CasHandlerTestCase(HomeserverTestCase):
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["public_baseurl"] = BASE_URL
cas_config = {
+4 -4
View File
@@ -19,7 +19,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, Awaitable, Callable, Dict
from typing import Any, Awaitable, Callable
from unittest.mock import AsyncMock, Mock
from twisted.internet.testing import MemoryReactor
@@ -43,7 +43,7 @@ class DirectoryTestCase(unittest.HomeserverTestCase):
self.mock_federation = AsyncMock()
self.mock_registry = Mock()
self.query_handlers: Dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
self.query_handlers: dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
def register_query_handler(
query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
@@ -410,7 +410,7 @@ class TestCreateAliasACL(unittest.HomeserverTestCase):
servlets = [directory.register_servlets, room.register_servlets]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
# Add custom alias creation rules to the config.
@@ -476,7 +476,7 @@ class TestCreatePublishedRoomACL(unittest.HomeserverTestCase):
data = {"room_alias_name": "unofficial_test"}
allowed_localpart = "allowed"
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
# Add custom room list publication rules to the config.
+3 -3
View File
@@ -20,7 +20,7 @@
#
#
import time
from typing import Dict, Iterable
from typing import Iterable
from unittest import mock
from parameterized import parameterized
@@ -291,7 +291,7 @@ class E2eKeysHandlerTestCase(unittest.HomeserverTestCase):
(chris, "chris_dev_2", "alg2"): 1,
}
# Convert to the format the handler wants.
query: Dict[str, Dict[str, Dict[str, int]]] = {}
query: dict[str, dict[str, dict[str, int]]] = {}
for (user_id, device_id, algorithm), count in claims_to_make.items():
query.setdefault(user_id, {}).setdefault(device_id, {})[algorithm] = count
claim_res = self.get_success(
@@ -1510,7 +1510,7 @@ class E2eKeysHandlerTestCase(unittest.HomeserverTestCase):
)
# Setup a response.
response: Dict[str, Dict[str, Dict[str, JsonDict]]] = {
response: dict[str, dict[str, dict[str, JsonDict]]] = {
local_user: {device_id_1: {**as_otk, **as_fallback_key}}
}
self.appservice_api.claim_client_keys.return_value = (response, [])
+2 -3
View File
@@ -19,7 +19,6 @@
#
#
import logging
from typing import Tuple
from twisted.internet.testing import MemoryReactor
@@ -64,7 +63,7 @@ class EventCreationTestCase(unittest.HomeserverTestCase):
self.requester = create_requester(self.user_id, device_id=device_id)
def _create_and_persist_member_event(self) -> Tuple[EventBase, EventContext]:
def _create_and_persist_member_event(self) -> tuple[EventBase, EventContext]:
# Create a member event we can use as an auth_event
memberEvent, memberEventContext = self.get_success(
create_event(
@@ -86,7 +85,7 @@ class EventCreationTestCase(unittest.HomeserverTestCase):
def _create_duplicate_event(
self, txn_id: str
) -> Tuple[EventBase, UnpersistedEventContextBase]:
) -> tuple[EventBase, UnpersistedEventContextBase]:
"""Create a new event with the given transaction ID. All events produced
by this method will be considered duplicates.
"""
+5 -5
View File
@@ -25,7 +25,7 @@ import time
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, HTTPServer
from io import BytesIO
from typing import Any, ClassVar, Coroutine, Dict, Generator, Optional, TypeVar, Union
from typing import Any, ClassVar, Coroutine, Generator, Optional, TypeVar, Union
from unittest.mock import ANY, AsyncMock, Mock
from urllib.parse import parse_qs
@@ -130,7 +130,7 @@ class MSC3861OAuthDelegation(HomeserverTestCase):
keys.register_servlets,
]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["public_baseurl"] = BASE_URL
config["disable_registration"] = True
@@ -834,7 +834,7 @@ class MasAuthDelegation(HomeserverTestCase):
return deferred
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["public_baseurl"] = BASE_URL
config["disable_registration"] = True
@@ -1100,9 +1100,9 @@ class DisabledEndpointsTestCase(HomeserverTestCase):
admin.register_servlets,
]
config: Dict[str, Any]
config: dict[str, Any]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["public_baseurl"] = BASE_URL
config["disable_registration"] = True
+4 -4
View File
@@ -19,7 +19,7 @@
#
#
import os
from typing import Any, Awaitable, ContextManager, Dict, Optional, Tuple
from typing import Any, Awaitable, ContextManager, Optional
from unittest.mock import ANY, AsyncMock, Mock, patch
from urllib.parse import parse_qs, urlparse
@@ -152,7 +152,7 @@ class OidcHandlerTestCase(HomeserverTestCase):
if not HAS_OIDC:
skip = "requires OIDC"
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["public_baseurl"] = BASE_URL
return config
@@ -204,7 +204,7 @@ class OidcHandlerTestCase(HomeserverTestCase):
client_redirect_url: str = "http://client/redirect",
scope: str = "openid",
with_sid: bool = False,
) -> Tuple[SynapseRequest, FakeAuthorizationGrant]:
) -> tuple[SynapseRequest, FakeAuthorizationGrant]:
"""Start an authorization request, and get the callback request back."""
nonce = random_string(10)
state = random_string(10)
@@ -222,7 +222,7 @@ class OidcHandlerTestCase(HomeserverTestCase):
def assertRenderedError(
self, error: str, error_description: Optional[str] = None
) -> Tuple[Any, ...]:
) -> tuple[Any, ...]:
self.render_error.assert_called_once()
args = self.render_error.call_args[0]
self.assertEqual(args[1], error)
+5 -5
View File
@@ -22,7 +22,7 @@
"""Tests for the password_auth_provider interface"""
from http import HTTPStatus
from typing import Any, Dict, List, Optional, Type, Union
from typing import Any, Optional, Union
from unittest.mock import AsyncMock, Mock
from twisted.internet.testing import MemoryReactor
@@ -75,7 +75,7 @@ class LegacyCustomAuthProvider:
def __init__(self, config: None, account_handler: AccountHandler):
pass
def get_supported_login_types(self) -> Dict[str, List[str]]:
def get_supported_login_types(self) -> dict[str, list[str]]:
return {"test.login_type": ["test_field"]}
def check_auth(self, *args: str) -> Mock:
@@ -109,7 +109,7 @@ class LegacyPasswordCustomAuthProvider:
def __init__(self, config: None, account_handler: AccountHandler):
pass
def get_supported_login_types(self) -> Dict[str, List[str]]:
def get_supported_login_types(self) -> dict[str, list[str]]:
return {"m.login.password": ["password"], "test.login_type": ["test_field"]}
def check_auth(self, *args: str) -> Mock:
@@ -139,7 +139,7 @@ class PasswordCustomAuthProvider:
return mock_password_provider.check_password(*args)
def legacy_providers_config(*providers: Type[Any]) -> dict:
def legacy_providers_config(*providers: type[Any]) -> dict:
"""Returns a config dict that will enable the given legacy password auth providers"""
return {
"password_providers": [
@@ -149,7 +149,7 @@ def legacy_providers_config(*providers: Type[Any]) -> dict:
}
def providers_config(*providers: Type[Any]) -> dict:
def providers_config(*providers: type[Any]) -> dict:
"""Returns a config dict that will enable the given modules"""
return {
"modules": [
+3 -3
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, Awaitable, Callable, Dict
from typing import Any, Awaitable, Callable
from unittest.mock import AsyncMock, Mock
from parameterized import parameterized
@@ -44,7 +44,7 @@ class ProfileTestCase(unittest.HomeserverTestCase):
self.mock_federation = AsyncMock()
self.mock_registry = Mock()
self.query_handlers: Dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
self.query_handlers: dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
def register_query_handler(
query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
@@ -377,7 +377,7 @@ class ProfileTestCase(unittest.HomeserverTestCase):
self.get_success(self.handler.check_avatar_size_and_mime_type(remote_mxc))
)
def _setup_local_files(self, names_and_props: Dict[str, Dict[str, Any]]) -> None:
def _setup_local_files(self, names_and_props: dict[str, dict[str, Any]]) -> None:
"""Stores metadata about files in the database.
Args:
+1 -2
View File
@@ -20,7 +20,6 @@
#
from copy import deepcopy
from typing import List
from twisted.internet.testing import MemoryReactor
@@ -334,7 +333,7 @@ class ReceiptsTestCase(unittest.HomeserverTestCase):
self.assertEqual(events, original_events)
def _test_filters_private(
self, events: List[JsonDict], expected_output: List[JsonDict]
self, events: list[JsonDict], expected_output: list[JsonDict]
) -> None:
"""Tests that the _filter_out_private returns the expected output"""
filtered_events = self.event_source.filter_out_private_receipts(
+10 -10
View File
@@ -19,7 +19,7 @@
#
#
from typing import Any, Collection, List, Optional, Tuple
from typing import Any, Collection, Optional
from unittest.mock import AsyncMock, Mock
from twisted.internet.testing import MemoryReactor
@@ -65,7 +65,7 @@ class TestSpamChecker:
self,
email_threepid: Optional[dict],
username: Optional[str],
request_info: Collection[Tuple[str, str]],
request_info: Collection[tuple[str, str]],
auth_provider_id: Optional[str],
) -> RegistrationBehaviour:
return RegistrationBehaviour.ALLOW
@@ -76,7 +76,7 @@ class DenyAll(TestSpamChecker):
self,
email_threepid: Optional[dict],
username: Optional[str],
request_info: Collection[Tuple[str, str]],
request_info: Collection[tuple[str, str]],
auth_provider_id: Optional[str],
) -> RegistrationBehaviour:
return RegistrationBehaviour.DENY
@@ -87,7 +87,7 @@ class BanAll(TestSpamChecker):
self,
email_threepid: Optional[dict],
username: Optional[str],
request_info: Collection[Tuple[str, str]],
request_info: Collection[tuple[str, str]],
auth_provider_id: Optional[str],
) -> RegistrationBehaviour:
return RegistrationBehaviour.SHADOW_BAN
@@ -98,7 +98,7 @@ class BanBadIdPUser(TestSpamChecker):
self,
email_threepid: Optional[dict],
username: Optional[str],
request_info: Collection[Tuple[str, str]],
request_info: Collection[tuple[str, str]],
auth_provider_id: Optional[str] = None,
) -> RegistrationBehaviour:
# Reject any user coming from CAS and whose username contains profanity
@@ -115,7 +115,7 @@ class TestLegacyRegistrationSpamChecker:
self,
email_threepid: Optional[dict],
username: Optional[str],
request_info: Collection[Tuple[str, str]],
request_info: Collection[tuple[str, str]],
) -> RegistrationBehaviour:
return RegistrationBehaviour.ALLOW
@@ -125,7 +125,7 @@ class LegacyAllowAll(TestLegacyRegistrationSpamChecker):
self,
email_threepid: Optional[dict],
username: Optional[str],
request_info: Collection[Tuple[str, str]],
request_info: Collection[tuple[str, str]],
) -> RegistrationBehaviour:
return RegistrationBehaviour.ALLOW
@@ -135,7 +135,7 @@ class LegacyDenyAll(TestLegacyRegistrationSpamChecker):
self,
email_threepid: Optional[dict],
username: Optional[str],
request_info: Collection[Tuple[str, str]],
request_info: Collection[tuple[str, str]],
) -> RegistrationBehaviour:
return RegistrationBehaviour.DENY
@@ -779,7 +779,7 @@ class RegistrationTestCase(unittest.HomeserverTestCase):
localpart: str,
displayname: Optional[str],
password_hash: Optional[str] = None,
) -> Tuple[str, str]:
) -> tuple[str, str]:
"""Creates a new user if the user does not exist,
else revokes all previous access tokens and generates a new one.
@@ -842,7 +842,7 @@ class RemoteAutoJoinTestCase(unittest.HomeserverTestCase):
async def lookup_room_alias(
*args: Any, **kwargs: Any
) -> Tuple[RoomID, List[str]]:
) -> tuple[RoomID, list[str]]:
return RoomID.from_string(self.room_id), ["remotetest"]
self.room_member_handler = Mock(spec=["update_membership", "lookup_room_alias"])
+3 -3
View File
@@ -1,5 +1,5 @@
from http import HTTPStatus
from typing import Optional, Set
from typing import Optional
from synapse.rest import admin
from synapse.rest.client import directory, login, room
@@ -69,7 +69,7 @@ class RoomListHandlerTestCase(unittest.HomeserverTestCase):
limit=50, from_federation_origin="test2"
)
)
room_ids_in_test2_list: Set[str] = {
room_ids_in_test2_list: set[str] = {
entry["room_id"] for entry in room_list["chunk"]
}
@@ -78,7 +78,7 @@ class RoomListHandlerTestCase(unittest.HomeserverTestCase):
limit=50, from_federation_origin="test3"
)
)
room_ids_in_test3_list: Set[str] = {
room_ids_in_test3_list: set[str] = {
entry["room_id"] for entry in room_list["chunk"]
}
+12 -12
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
from typing import Any, Iterable, Optional
from unittest import mock
from twisted.internet.defer import ensureDeferred
@@ -60,7 +60,7 @@ def _create_event(
return result
def _order(*events: mock.Mock) -> List[mock.Mock]:
def _order(*events: mock.Mock) -> list[mock.Mock]:
return sorted(events, key=_child_events_comparison_key)
@@ -152,7 +152,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
room_id: str,
token: str,
order: Optional[str] = None,
via: Optional[List[str]] = None,
via: Optional[list[str]] = None,
) -> None:
"""Add a child room to a space."""
if via is None:
@@ -170,7 +170,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
)
def _assert_hierarchy(
self, result: JsonDict, rooms_and_children: Iterable[Tuple[str, Iterable[str]]]
self, result: JsonDict, rooms_and_children: Iterable[tuple[str, Iterable[str]]]
) -> None:
"""
Assert that the expected room IDs are in the response.
@@ -547,7 +547,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
)
# The result should have the space and all of the links, plus some of the
# rooms and a pagination token.
expected: List[Tuple[str, Iterable[str]]] = [(self.space, room_ids)]
expected: list[tuple[str, Iterable[str]]] = [(self.space, room_ids)]
expected += [(room_id, ()) for room_id in room_ids[:6]]
self._assert_hierarchy(result, expected)
self.assertIn("next_batch", result)
@@ -646,7 +646,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
create_requester(self.user), self.space, max_depth=0
)
)
expected: List[Tuple[str, Iterable[str]]] = [(spaces[0], [rooms[0], spaces[1]])]
expected: list[tuple[str, Iterable[str]]] = [(spaces[0], [rooms[0], spaces[1]])]
self._assert_hierarchy(result, expected)
# A single additional layer.
@@ -740,7 +740,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
async def summarize_remote_room_hierarchy(
_self: Any, room: Any, suggested_only: bool
) -> Tuple[Optional[_RoomEntry], Dict[str, JsonDict], Set[str]]:
) -> tuple[Optional[_RoomEntry], dict[str, JsonDict], set[str]]:
return requested_room_entry, {subroom: child_room}, set()
# Add a room to the space which is on another server.
@@ -793,7 +793,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
async def summarize_remote_room_hierarchy(
_self: Any, room: Any, suggested_only: bool
) -> Tuple[Optional[_RoomEntry], Dict[str, JsonDict], Set[str]]:
) -> tuple[Optional[_RoomEntry], dict[str, JsonDict], set[str]]:
return requested_room_entry, {fed_subroom: child_room}, set()
expected = [
@@ -921,7 +921,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
async def summarize_remote_room_hierarchy(
_self: Any, room: Any, suggested_only: bool
) -> Tuple[Optional[_RoomEntry], Dict[str, JsonDict], Set[str]]:
) -> tuple[Optional[_RoomEntry], dict[str, JsonDict], set[str]]:
return subspace_room_entry, dict(children_rooms), set()
# Add a room to the space which is on another server.
@@ -985,7 +985,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
async def summarize_remote_room_hierarchy(
_self: Any, room: Any, suggested_only: bool
) -> Tuple[Optional[_RoomEntry], Dict[str, JsonDict], Set[str]]:
) -> tuple[Optional[_RoomEntry], dict[str, JsonDict], set[str]]:
return fed_room_entry, {}, set()
# Add a room to the space which is on another server.
@@ -1120,7 +1120,7 @@ class SpaceSummaryTestCase(unittest.HomeserverTestCase):
async def summarize_remote_room_hierarchy(
_self: Any, room: Any, suggested_only: bool
) -> Tuple[Optional[_RoomEntry], Dict[str, JsonDict], Set[str]]:
) -> tuple[Optional[_RoomEntry], dict[str, JsonDict], set[str]]:
return requested_room_entry, {fed_subroom: child_room}, set()
expected = [
@@ -1233,7 +1233,7 @@ class RoomSummaryTestCase(unittest.HomeserverTestCase):
async def summarize_remote_room_hierarchy(
_self: Any, room: Any, suggested_only: bool
) -> Tuple[Optional[_RoomEntry], Dict[str, JsonDict], Set[str]]:
) -> tuple[Optional[_RoomEntry], dict[str, JsonDict], set[str]]:
return requested_room_entry, {}, set()
with mock.patch(
+4 -4
View File
@@ -19,7 +19,7 @@
#
#
from typing import Any, Dict, Optional, Set, Tuple
from typing import Any, Optional
from unittest.mock import AsyncMock, Mock
import attr
@@ -73,7 +73,7 @@ class TestMappingProvider:
return None
@staticmethod
def get_saml_attributes(config: None) -> Tuple[Set[str], Set[str]]:
def get_saml_attributes(config: None) -> tuple[set[str], set[str]]:
return {"uid"}, {"displayName"}
def get_remote_user_id(
@@ -102,10 +102,10 @@ class TestRedirectMappingProvider(TestMappingProvider):
class SamlHandlerTestCase(HomeserverTestCase):
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["public_baseurl"] = BASE_URL
saml_config: Dict[str, Any] = {
saml_config: dict[str, Any] = {
"sp_config": {"metadata": {}},
# Disable grandfathering.
"grandfathered_mxid_source_attribute": None,
+7 -7
View File
@@ -20,7 +20,7 @@
#
from typing import Callable, List, Tuple, Type, Union
from typing import Callable, Union
from unittest.mock import patch
from zope.interface import implementer
@@ -58,18 +58,18 @@ def TestingESMTPTLSClientFactory(
class _DummyMessageDelivery:
def __init__(self) -> None:
# (recipient, message) tuples
self.messages: List[Tuple[smtp.Address, bytes]] = []
self.messages: list[tuple[smtp.Address, bytes]] = []
def receivedHeader(
self,
helo: Tuple[bytes, bytes],
helo: tuple[bytes, bytes],
origin: smtp.Address,
recipients: List[smtp.User],
recipients: list[smtp.User],
) -> None:
return None
def validateFrom(
self, helo: Tuple[bytes, bytes], origin: smtp.Address
self, helo: tuple[bytes, bytes], origin: smtp.Address
) -> smtp.Address:
return origin
@@ -89,7 +89,7 @@ class _DummyMessage:
def __init__(self, delivery: _DummyMessageDelivery, user: smtp.User):
self._delivery = delivery
self._user = user
self._buffer: List[bytes] = []
self._buffer: list[bytes] = []
def lineReceived(self, line: bytes) -> None:
self._buffer.append(line)
@@ -104,7 +104,7 @@ class _DummyMessage:
class SendEmailHandlerTestCaseIPv4(HomeserverTestCase):
ip_class: Union[Type[IPv4Address], Type[IPv6Address]] = IPv4Address
ip_class: Union[type[IPv4Address], type[IPv6Address]] = IPv4Address
def setUp(self) -> None:
super().setUp()
+8 -8
View File
@@ -18,7 +18,7 @@
#
#
import logging
from typing import AbstractSet, Dict, Mapping, Optional, Set, Tuple
from typing import AbstractSet, Mapping, Optional
from unittest.mock import patch
import attr
@@ -3278,7 +3278,7 @@ class FilterRoomsRelevantForSyncTestCase(HomeserverTestCase):
user: UserID,
to_token: StreamToken,
from_token: Optional[StreamToken],
) -> Tuple[Dict[str, RoomsForUserType], AbstractSet[str], AbstractSet[str]]:
) -> tuple[dict[str, RoomsForUserType], AbstractSet[str], AbstractSet[str]]:
"""
Get the rooms the user should be syncing with
"""
@@ -3615,7 +3615,7 @@ class SortRoomsTestCase(HomeserverTestCase):
user: UserID,
to_token: StreamToken,
from_token: Optional[StreamToken],
) -> Tuple[Dict[str, RoomsForUserType], AbstractSet[str], AbstractSet[str]]:
) -> tuple[dict[str, RoomsForUserType], AbstractSet[str], AbstractSet[str]]:
"""
Get the rooms the user should be syncing with
"""
@@ -3824,13 +3824,13 @@ class SortRoomsTestCase(HomeserverTestCase):
@attr.s(slots=True, auto_attribs=True, frozen=True)
class RequiredStateChangesTestParameters:
previous_required_state_map: Dict[str, Set[str]]
request_required_state_map: Dict[str, Set[str]]
previous_required_state_map: dict[str, set[str]]
request_required_state_map: dict[str, set[str]]
state_deltas: StateMap[str]
expected_with_state_deltas: Tuple[
expected_with_state_deltas: tuple[
Optional[Mapping[str, AbstractSet[str]]], StateFilter
]
expected_without_state_deltas: Tuple[
expected_without_state_deltas: tuple[
Optional[Mapping[str, AbstractSet[str]]], StateFilter
]
@@ -4785,7 +4785,7 @@ class RequiredStateChangesTestCase(unittest.TestCase):
self,
_test_label: str,
event_type: str,
extra_state_keys: Set[str],
extra_state_keys: set[str],
) -> None:
"""
Test that we limit the number of state_keys that we remember but always include
+2 -2
View File
@@ -18,7 +18,7 @@
#
#
from http import HTTPStatus
from typing import BinaryIO, Callable, Dict, List, Optional, Tuple
from typing import BinaryIO, Callable, Optional
from unittest.mock import Mock
from twisted.internet.testing import MemoryReactor
@@ -120,7 +120,7 @@ async def mock_get_file(
max_size: Optional[int] = None,
headers: Optional[RawHeaders] = None,
is_allowed_content_type: Optional[Callable[[str], bool]] = None,
) -> Tuple[int, Dict[bytes, List[bytes]], str, int]:
) -> tuple[int, dict[bytes, list[bytes]], str, int]:
fake_response = FakeResponse(code=404)
if url == "http://my.server/me.png":
fake_response = FakeResponse(
+4 -4
View File
@@ -18,7 +18,7 @@
#
#
from typing import Any, Dict, List, Optional, Tuple, cast
from typing import Any, Optional, cast
from twisted.internet.testing import MemoryReactor
@@ -74,9 +74,9 @@ class StatsRoomTests(unittest.HomeserverTestCase):
)
)
async def get_all_room_state(self) -> List[Optional[str]]:
async def get_all_room_state(self) -> list[Optional[str]]:
rows = cast(
List[Tuple[Optional[str]]],
list[tuple[Optional[str]]],
await self.store.db_pool.simple_select_list(
"room_stats_state", None, retcols=("topic",)
),
@@ -85,7 +85,7 @@ class StatsRoomTests(unittest.HomeserverTestCase):
def _get_current_stats(
self, stats_type: str, stat_id: str
) -> Optional[Dict[str, Any]]:
) -> Optional[dict[str, Any]]:
table, id_col = stats.TYPE_TO_TABLE[stats_type]
cols = list(stats.ABSOLUTE_STATS_FIELDS[stats_type])
+3 -3
View File
@@ -18,7 +18,7 @@
#
#
from http import HTTPStatus
from typing import Collection, ContextManager, List, Optional
from typing import Collection, ContextManager, Optional
from unittest.mock import AsyncMock, Mock, patch
from parameterized import parameterized, parameterized_class
@@ -872,7 +872,7 @@ class SyncTestCase(tests.unittest.HomeserverTestCase):
# ... And the state should be empty
self.assertEqual(sync_room_result.state, {})
def _patch_get_latest_events(self, latest_events: List[str]) -> ContextManager:
def _patch_get_latest_events(self, latest_events: list[str]) -> ContextManager:
"""Monkey-patch `get_prev_events_for_room`
Returns a context manager which will replace the implementation of
@@ -902,7 +902,7 @@ class SyncTestCase(tests.unittest.HomeserverTestCase):
async def _check_sigs_and_hash_for_pulled_events_and_fetch(
dest: str, pdus: Collection[EventBase], room_version: RoomVersion
) -> List[EventBase]:
) -> list[EventBase]:
return list(pdus)
self.client._check_sigs_and_hash_for_pulled_events_and_fetch = ( # type: ignore[method-assign]
+4 -5
View File
@@ -21,7 +21,6 @@
import json
from typing import Dict, List, Set
from unittest.mock import ANY, AsyncMock, Mock, call
from netaddr import IPSet
@@ -110,7 +109,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
return hs
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
d = super().create_resource_dict()
d["/_matrix/federation"] = TransportLayerServer(self.hs)
return d
@@ -143,7 +142,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
return_value=None
)
self.room_members: List[UserID] = []
self.room_members: list[UserID] = []
async def check_user_in_room(room_id: str, requester: Requester) -> None:
if requester.user.to_string() not in [
@@ -163,7 +162,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
side_effect=check_host_in_room
)
async def get_current_hosts_in_room(room_id: str) -> Set[str]:
async def get_current_hosts_in_room(room_id: str) -> set[str]:
return {member.domain for member in self.room_members}
hs.get_storage_controllers().state.get_current_hosts_in_room = Mock( # type: ignore[method-assign]
@@ -174,7 +173,7 @@ class TypingNotificationsTestCase(unittest.HomeserverTestCase):
side_effect=get_current_hosts_in_room
)
async def get_users_in_room(room_id: str) -> Set[str]:
async def get_users_in_room(room_id: str) -> set[str]:
return {str(u) for u in self.room_members}
self.datastore.get_users_in_room = Mock(side_effect=get_users_in_room)
+2 -2
View File
@@ -17,7 +17,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, Tuple
from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from urllib.parse import quote
@@ -313,7 +313,7 @@ class UserDirectoryTestCase(unittest.HomeserverTestCase):
def _create_rooms_and_inject_memberships(
self, creator: str, token: str, joiner: str
) -> Tuple[str, str]:
) -> tuple[str, str]:
"""Create a public and private room as a normal user.
Then get the `joiner` into those rooms.
"""
+3 -4
View File
@@ -19,7 +19,6 @@
#
import os.path
import subprocess
from typing import List
from incremental import Version
from zope.interface import implementer
@@ -85,7 +84,7 @@ subjectAltName = %(sanentries)s
"""
def create_test_cert_file(sanlist: List[bytes]) -> str:
def create_test_cert_file(sanlist: list[bytes]) -> str:
"""build an x509 certificate file
Args:
@@ -151,7 +150,7 @@ class TestServerTLSConnectionFactory:
"""An SSL connection creator which returns connections which present a certificate
signed by our test CA."""
def __init__(self, sanlist: List[bytes]):
def __init__(self, sanlist: list[bytes]):
"""
Args:
sanlist: a list of subjectAltName values for the cert
@@ -166,7 +165,7 @@ class TestServerTLSConnectionFactory:
def wrap_server_factory_for_tls(
factory: IProtocolFactory, clock: IReactorTime, sanlist: List[bytes]
factory: IProtocolFactory, clock: IReactorTime, sanlist: list[bytes]
) -> TLSMemoryBIOFactory:
"""Wrap an existing Protocol Factory with a test TLSMemoryBIOFactory
@@ -20,7 +20,7 @@
import base64
import logging
import os
from typing import Generator, List, Optional, cast
from typing import Generator, Optional, cast
from unittest.mock import AsyncMock, call, patch
import treq
@@ -110,7 +110,7 @@ class MatrixFederationAgentTests(unittest.TestCase):
client_factory: IProtocolFactory,
ssl: bool = True,
expected_sni: Optional[bytes] = None,
tls_sanlist: Optional[List[bytes]] = None,
tls_sanlist: Optional[list[bytes]] = None,
) -> HTTPChannel:
"""Builds a test server, and completes the outgoing client connection
Args:
+14 -14
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Dict, Generator, List, Tuple, cast
from typing import Generator, cast
from unittest.mock import Mock
from twisted.internet import defer
@@ -44,20 +44,20 @@ class SrvResolverTestCase(unittest.TestCase):
type=dns.SRV, payload=dns.Record_SRV(target=host_name)
)
result_deferred: "Deferred[Tuple[List[dns.RRHeader], None, None]]" = Deferred()
result_deferred: "Deferred[tuple[list[dns.RRHeader], None, None]]" = Deferred()
dns_client_mock.lookupService.return_value = result_deferred
cache: Dict[bytes, List[Server]] = {}
cache: dict[bytes, list[Server]] = {}
resolver = SrvResolver(dns_client=dns_client_mock, cache=cache)
@defer.inlineCallbacks
def do_lookup() -> Generator["Deferred[object]", object, List[Server]]:
def do_lookup() -> Generator["Deferred[object]", object, list[Server]]:
with LoggingContext(
name="one",
server_name="test_server",
) as ctx:
resolve_d = resolver.resolve_service(service_name)
result: List[Server]
result: list[Server]
result = yield defer.ensureDeferred(resolve_d) # type: ignore[assignment]
# should have restored our context
@@ -95,7 +95,7 @@ class SrvResolverTestCase(unittest.TestCase):
cache = {service_name: [cast(Server, entry)]}
resolver = SrvResolver(dns_client=dns_client_mock, cache=cache)
servers: List[Server]
servers: list[Server]
servers = yield defer.ensureDeferred(resolver.resolve_service(service_name)) # type: ignore[assignment]
dns_client_mock.lookupService.assert_called_once_with(service_name)
@@ -122,7 +122,7 @@ class SrvResolverTestCase(unittest.TestCase):
dns_client=dns_client_mock, cache=cache, get_time=clock.time
)
servers: List[Server]
servers: list[Server]
servers = yield defer.ensureDeferred(resolver.resolve_service(service_name)) # type: ignore[assignment]
self.assertFalse(dns_client_mock.lookupService.called)
@@ -138,7 +138,7 @@ class SrvResolverTestCase(unittest.TestCase):
service_name = b"test_service.example.com"
cache: Dict[bytes, List[Server]] = {}
cache: dict[bytes, list[Server]] = {}
resolver = SrvResolver(dns_client=dns_client_mock, cache=cache)
with self.assertRaises(error.DNSServerError):
@@ -152,10 +152,10 @@ class SrvResolverTestCase(unittest.TestCase):
service_name = b"test_service.example.com"
cache: Dict[bytes, List[Server]] = {}
cache: dict[bytes, list[Server]] = {}
resolver = SrvResolver(dns_client=dns_client_mock, cache=cache)
servers: List[Server]
servers: list[Server]
servers = yield defer.ensureDeferred(resolver.resolve_service(service_name)) # type: ignore[assignment]
self.assertEqual(len(servers), 0)
@@ -167,10 +167,10 @@ class SrvResolverTestCase(unittest.TestCase):
"""
service_name = b"test_service.example.com"
lookup_deferred: "Deferred[Tuple[List[dns.RRHeader], None, None]]" = Deferred()
lookup_deferred: "Deferred[tuple[list[dns.RRHeader], None, None]]" = Deferred()
dns_client_mock = Mock()
dns_client_mock.lookupService.return_value = lookup_deferred
cache: Dict[bytes, List[Server]] = {}
cache: dict[bytes, list[Server]] = {}
resolver = SrvResolver(dns_client=dns_client_mock, cache=cache)
# Old versions of Twisted don't have an ensureDeferred in failureResultOf.
@@ -193,10 +193,10 @@ class SrvResolverTestCase(unittest.TestCase):
"""
service_name = b"test_service.example.com"
lookup_deferred: "Deferred[Tuple[List[dns.RRHeader], None, None]]" = Deferred()
lookup_deferred: "Deferred[tuple[list[dns.RRHeader], None, None]]" = Deferred()
dns_client_mock = Mock()
dns_client_mock.lookupService.return_value = lookup_deferred
cache: Dict[bytes, List[Server]] = {}
cache: dict[bytes, list[Server]] = {}
resolver = SrvResolver(dns_client=dns_client_mock, cache=cache)
# Old versions of Twisted don't have an ensureDeferred in successResultOf.
+8 -12
View File
@@ -26,12 +26,8 @@ from typing import (
Any,
Callable,
ContextManager,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
TypeVar,
Union,
)
@@ -208,7 +204,7 @@ def make_request_with_cancellation_test(
# The set of previously seen `await`s.
# Each element is a stringified stack trace.
seen_awaits: Set[Tuple[str, ...]] = set()
seen_awaits: set[tuple[str, ...]] = set()
_log_for_request(
0, f"Running make_request_with_cancellation_test for {test_name}..."
@@ -337,7 +333,7 @@ class Deferred__await__Patch:
deferred_patch.unblock_awaits()
"""
def __init__(self, seen_awaits: Set[Tuple[str, ...]], request_number: int):
def __init__(self, seen_awaits: set[tuple[str, ...]], request_number: int):
"""
Args:
seen_awaits: The set of stack traces of `await`s that have been previously
@@ -365,10 +361,10 @@ class Deferred__await__Patch:
# unresolved `Deferred` and return it out of `Deferred.__await__` /
# `coroutine.send()`. We have to resolve it later, in case the `await`ing
# coroutine is part of some shared processing, such as `@cached`.
self._to_unblock: Dict[Deferred, Union[object, Failure]] = {}
self._to_unblock: dict[Deferred, Union[object, Failure]] = {}
# The last stack we logged.
self._previous_stack: List[inspect.FrameInfo] = []
self._previous_stack: list[inspect.FrameInfo] = []
def patch(self) -> ContextManager[Mock]:
"""Returns a context manager which patches `Deferred.__await__`."""
@@ -507,8 +503,8 @@ def _log_for_request(request_number: int, message: str) -> None:
def _log_await_stack(
stack: List[inspect.FrameInfo],
previous_stack: List[inspect.FrameInfo],
stack: list[inspect.FrameInfo],
previous_stack: list[inspect.FrameInfo],
request_number: int,
note: str,
) -> None:
@@ -566,7 +562,7 @@ def _format_stack_frame(frame_info: inspect.FrameInfo) -> str:
)
def _get_stack(skip_frames: int) -> List[inspect.FrameInfo]:
def _get_stack(skip_frames: int) -> list[inspect.FrameInfo]:
"""Captures the stack for a request.
Skips any twisted frames and stops at `JsonResource.wrapped_async_request_handler`.
@@ -622,6 +618,6 @@ def _get_stack_frame_method_name(frame_info: inspect.FrameInfo) -> str:
return method_name
def _hash_stack(stack: List[inspect.FrameInfo]) -> Tuple[str, ...]:
def _hash_stack(stack: list[inspect.FrameInfo]) -> tuple[str, ...]:
"""Turns a stack into a hashable value that can be put into a set."""
return tuple(_format_stack_frame(frame) for frame in stack)
+3 -3
View File
@@ -20,7 +20,7 @@
#
from io import BytesIO
from typing import Tuple, Union
from typing import Union
from unittest.mock import Mock
from netaddr import IPSet
@@ -59,7 +59,7 @@ class ReadMultipartResponseTests(TestCase):
def _build_multipart_response(
self, response_length: Union[int, str], max_length: int
) -> Tuple[
) -> tuple[
BytesIO,
"Deferred[MultipartResponse]",
_MultipartParserProtocol,
@@ -209,7 +209,7 @@ class ReadMultipartResponseTests(TestCase):
class ReadBodyWithMaxSizeTests(TestCase):
def _build_response(
self, length: Union[int, str] = UNKNOWN_LENGTH
) -> Tuple[
) -> tuple[
BytesIO,
"Deferred[int]",
_DiscardBodyWithMaxSizeProtocol,
+2 -2
View File
@@ -18,7 +18,7 @@
#
#
import io
from typing import Any, Dict, Generator
from typing import Any, Generator
from unittest.mock import ANY, Mock, create_autospec
from netaddr import IPSet
@@ -745,7 +745,7 @@ class FederationClientTests(HomeserverTestCase):
class FederationClientProxyTests(BaseMultiWorkerStreamTestCase):
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
conf = super().default_config()
conf["instance_map"] = {
"main": {"host": "testserv", "port": 8765},
+1 -2
View File
@@ -18,7 +18,6 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Set
from parameterized import parameterized
@@ -64,7 +63,7 @@ class ProxyTests(TestCase):
def test_parse_connection_header_value(
self,
connection_header_value: bytes,
expected_extra_headers_to_remove: Set[str],
expected_extra_headers_to_remove: set[str],
) -> None:
"""
Tests that the connection header value is parsed correctly
+2 -2
View File
@@ -21,7 +21,7 @@
import base64
import logging
import os
from typing import List, Optional
from typing import Optional
from unittest.mock import patch
import treq
@@ -252,7 +252,7 @@ class ProxyAgentTests(TestCase):
server_factory: IProtocolFactory,
ssl: bool = False,
expected_sni: Optional[bytes] = None,
tls_sanlist: Optional[List[bytes]] = None,
tls_sanlist: Optional[list[bytes]] = None,
) -> IProtocol:
"""Builds a test server, and completes the outgoing client connection
+3 -3
View File
@@ -21,7 +21,7 @@
import json
from http import HTTPStatus
from io import BytesIO
from typing import Tuple, Union
from typing import Union
from unittest.mock import Mock
from synapse.api.errors import Codes, SynapseError
@@ -108,11 +108,11 @@ class CancellableRestServlet(RestServlet):
self.clock = hs.get_clock()
@cancellable
async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
async def on_GET(self, request: SynapseRequest) -> tuple[int, JsonDict]:
await self.clock.sleep(1.0)
return HTTPStatus.OK, {"result": True}
async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
async def on_POST(self, request: SynapseRequest) -> tuple[int, JsonDict]:
await self.clock.sleep(1.0)
return HTTPStatus.OK, {"result": True}
+1 -2
View File
@@ -18,7 +18,6 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Tuple
from twisted.internet.protocol import Protocol
from twisted.internet.testing import AccumulatingProtocol, MemoryReactorClock
@@ -33,7 +32,7 @@ from tests.utils import checked_cast
def connect_logging_client(
reactor: MemoryReactorClock, client_id: int
) -> Tuple[Protocol, AccumulatingProtocol]:
) -> tuple[Protocol, AccumulatingProtocol]:
# This is essentially tests.server.connect_client, but disabling autoflush on
# the client transport. This is necessary to avoid an infinite loop due to
# sending of data via the logging transport causing additional logs to be
+18 -18
View File
@@ -23,7 +23,7 @@ import shutil
import tempfile
from binascii import unhexlify
from io import BytesIO
from typing import Any, BinaryIO, ClassVar, Dict, List, Literal, Optional, Tuple, Union
from typing import Any, BinaryIO, ClassVar, Literal, Optional, Union
from unittest.mock import MagicMock, Mock, patch
from urllib import parse
@@ -297,9 +297,9 @@ class MediaRepoTests(unittest.HomeserverTestCase):
user_id = "@test:user"
def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
self.fetches: List[
Tuple[
"Deferred[Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]]]]]",
self.fetches: list[
tuple[
"Deferred[tuple[bytes, tuple[int, dict[bytes, list[bytes]]]]]",
str,
str,
Optional[QueryParams],
@@ -317,12 +317,12 @@ class MediaRepoTests(unittest.HomeserverTestCase):
retry_on_dns_fail: bool = True,
ignore_backoff: bool = False,
follow_redirects: bool = False,
) -> "Deferred[Tuple[int, Dict[bytes, List[bytes]]]]":
) -> "Deferred[tuple[int, dict[bytes, list[bytes]]]]":
"""A mock for MatrixFederationHttpClient.get_file."""
def write_to(
r: Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]]]],
) -> Tuple[int, Dict[bytes, List[bytes]]]:
r: tuple[bytes, tuple[int, dict[bytes, list[bytes]]]],
) -> tuple[int, dict[bytes, list[bytes]]]:
data, response = r
output_stream.write(data)
return response
@@ -332,7 +332,7 @@ class MediaRepoTests(unittest.HomeserverTestCase):
output_stream.write(f.value.response)
return f
d: Deferred[Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]]]]] = Deferred()
d: Deferred[tuple[bytes, tuple[int, dict[bytes, list[bytes]]]]] = Deferred()
self.fetches.append((d, destination, path, args))
# Note that this callback changes the value held by d.
d_after_callback = d.addCallbacks(write_to, write_err)
@@ -370,7 +370,7 @@ class MediaRepoTests(unittest.HomeserverTestCase):
self.media_id = "example.com/12345"
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
@@ -860,12 +860,12 @@ class TestSpamCheckerLegacy:
Uses the legacy Spam-Checker API.
"""
def __init__(self, config: Dict[str, Any], api: ModuleApi) -> None:
def __init__(self, config: dict[str, Any], api: ModuleApi) -> None:
self.config = config
self.api = api
@staticmethod
def parse_config(config: Dict[str, Any]) -> Dict[str, Any]:
def parse_config(config: dict[str, Any]) -> dict[str, Any]:
return config
async def check_event_for_spam(self, event: EventBase) -> Union[bool, str]:
@@ -911,12 +911,12 @@ class SpamCheckerTestCaseLegacy(unittest.HomeserverTestCase):
load_legacy_spam_checkers(hs)
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = default_config("test")
config.update(
@@ -965,14 +965,14 @@ class SpamCheckerTestCase(unittest.HomeserverTestCase):
check_media_file_for_spam=self.check_media_file_for_spam
)
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
async def check_media_file_for_spam(
self, file_wrapper: ReadableFileWrapper, file_info: FileInfo
) -> Union[Codes, Literal["NOT_SPAM"], Tuple[Codes, JsonDict]]:
) -> Union[Codes, Literal["NOT_SPAM"], tuple[Codes, JsonDict]]:
buf = BytesIO()
await file_wrapper.write_chunks_to(buf.write)
@@ -1028,7 +1028,7 @@ class RemoteDownloadLimiterTestCase(unittest.HomeserverTestCase):
self.client = hs.get_federation_http_client()
self.store = hs.get_datastores().main
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
# We need to manually set the resource tree to include media, the
# default only does `/_matrix/client` APIs.
return {"/_matrix/media": self.hs.get_media_repository_resource()}
@@ -1280,7 +1280,7 @@ class MediaHashesTestCase(unittest.HomeserverTestCase):
self.store = hs.get_datastores().main
self.client = hs.get_federation_http_client()
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
@@ -1377,7 +1377,7 @@ class MediaRepoSizeModuleCallbackTestCase(unittest.HomeserverTestCase):
is_user_allowed_to_upload_media_of_size=self.is_user_allowed_to_upload_media_of_size,
)
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
+5 -5
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Dict, NoReturn, Protocol, Tuple
from typing import NoReturn, Protocol
from prometheus_client.core import Sample
@@ -35,7 +35,7 @@ from synapse.util.caches.deferred_cache import DeferredCache
from tests import unittest
def get_sample_labels_value(sample: Sample) -> Tuple[Dict[str, str], float]:
def get_sample_labels_value(sample: Sample) -> tuple[dict[str, str], float]:
"""Extract the labels and values of a sample.
prometheus_client 0.5 changed the sample type to a named tuple with more
@@ -54,7 +54,7 @@ def get_sample_labels_value(sample: Sample) -> Tuple[Dict[str, str], float]:
# Otherwise fall back to treating it as a plain 3 tuple.
else:
# In older versions of prometheus_client Sample was a 3-tuple.
labels: Dict[str, str]
labels: dict[str, str]
value: float
_, labels, value = sample # type: ignore[misc]
return labels, value
@@ -127,7 +127,7 @@ class TestMauLimit(unittest.TestCase):
def get_metrics_from_gauge(
self, gauge: InFlightGauge
) -> Dict[str, Dict[Tuple[str, ...], float]]:
) -> dict[str, dict[tuple[str, ...], float]]:
results = {}
for r in gauge.collect():
@@ -384,7 +384,7 @@ class LaterGaugeTests(unittest.HomeserverTestCase):
self.assertEqual(hs2_metric_value, "2.0")
def get_latest_metrics() -> Dict[str, str]:
def get_latest_metrics() -> dict[str, str]:
"""
Collect the latest metrics from the registry and parse them into an easy to use map.
The key includes the metric name and labels.
+2 -2
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, Dict, Optional
from typing import Any, Optional
from unittest.mock import AsyncMock, Mock
from twisted.internet import defer
@@ -839,7 +839,7 @@ class ModuleApiWorkerTestCase(BaseModuleApiTestCase, BaseMultiWorkerStreamTestCa
presence.register_servlets,
]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
conf = super().default_config()
conf["stream_writers"] = {"presence": ["presence_writer"]}
conf["instance_map"] = {
+4 -4
View File
@@ -21,7 +21,7 @@ import email.message
import importlib.resources as importlib_resources
import os
from http import HTTPStatus
from typing import Any, Dict, List, Sequence, Tuple
from typing import Any, Sequence
import attr
from parameterized import parameterized
@@ -83,8 +83,8 @@ class EmailPusherTests(HomeserverTestCase):
hs = self.setup_test_homeserver(config=config)
# List[Tuple[Deferred, args, kwargs]]
self.email_attempts: List[Tuple[Deferred, Sequence, Dict]] = []
# list[tuple[Deferred, args, kwargs]]
self.email_attempts: list[tuple[Deferred, Sequence, dict]] = []
def sendmail(*args: Any, **kwargs: Any) -> Deferred:
# This mocks out synapse.reactor.send_email._sendmail.
@@ -510,7 +510,7 @@ class EmailPusherTests(HomeserverTestCase):
)
self.assertEqual(len(pushers), 0)
def _check_for_mail(self) -> Tuple[Sequence, Dict]:
def _check_for_mail(self) -> tuple[Sequence, dict]:
"""
Assert that synapse sent off exactly one email notification.
+5 -5
View File
@@ -17,7 +17,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, Dict, List, Tuple
from typing import Any
from unittest.mock import Mock
from parameterized import parameterized
@@ -51,7 +51,7 @@ class HTTPPusherTests(HomeserverTestCase):
hijack_auth = False
def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
self.push_attempts: List[Tuple[Deferred, str, dict]] = []
self.push_attempts: list[tuple[Deferred, str, dict]] = []
m = Mock()
@@ -747,7 +747,7 @@ class HTTPPusherTests(HomeserverTestCase):
def _make_user_with_pusher(
self, username: str, enabled: bool = True
) -> Tuple[str, str]:
) -> tuple[str, str]:
"""Registers a user and creates a pusher for them.
Args:
@@ -925,7 +925,7 @@ class HTTPPusherTests(HomeserverTestCase):
ret = self.get_success(
self.hs.get_datastores().main.get_pushers_by({"user_name": user_id})
)
pushers: List[PusherConfig] = list(ret)
pushers: list[PusherConfig] = list(ret)
# Check that we still have one pusher, and that the device ID associated with
# it didn't change.
@@ -1118,7 +1118,7 @@ class HTTPPusherTests(HomeserverTestCase):
device_id = user_tuple.device_id
# Set the push data dict based on test input parameters
push_data: Dict[str, Any] = {
push_data: dict[str, Any] = {
"url": "http://example.com/_matrix/push/v1/notify",
}
if disable_badge_count:
+8 -8
View File
@@ -19,7 +19,7 @@
#
#
from typing import Iterable, List, Optional, Tuple, cast
from typing import Iterable, Optional, cast
from synapse.api.constants import EventTypes, Membership
from synapse.api.room_versions import RoomVersions
@@ -36,7 +36,7 @@ class MockDataStore:
(I.e. the state key is used as the event ID.)
"""
def __init__(self, events: Iterable[Tuple[StateKey, dict]]):
def __init__(self, events: Iterable[tuple[StateKey, dict]]):
"""
Args:
events: A state map to event contents.
@@ -63,7 +63,7 @@ class MockDataStore:
assert allow_none, "Mock not configured for allow_none = False"
# Decode the state key from the event ID.
state_key = cast(Tuple[str, str], tuple(event_id.split("|", 1)))
state_key = cast(tuple[str, str], tuple(event_id.split("|", 1)))
return self._events.get(state_key)
async def get_events(self, event_ids: Iterable[StateKey]) -> StateMap[EventBase]:
@@ -77,7 +77,7 @@ class PresentableNamesTestCase(unittest.HomeserverTestCase):
def _calculate_room_name(
self,
events: Iterable[Tuple[Tuple[str, str], dict]],
events: Iterable[tuple[tuple[str, str], dict]],
user_id: str = "",
fallback_to_members: bool = True,
fallback_to_single_member: bool = True,
@@ -97,7 +97,7 @@ class PresentableNamesTestCase(unittest.HomeserverTestCase):
def test_name(self) -> None:
"""A room name event should be used."""
events: List[Tuple[Tuple[str, str], dict]] = [
events: list[tuple[tuple[str, str], dict]] = [
((EventTypes.Name, ""), {"name": "test-name"}),
]
self.assertEqual("test-name", self._calculate_room_name(events))
@@ -111,7 +111,7 @@ class PresentableNamesTestCase(unittest.HomeserverTestCase):
def test_canonical_alias(self) -> None:
"""An canonical alias should be used."""
events: List[Tuple[Tuple[str, str], dict]] = [
events: list[tuple[tuple[str, str], dict]] = [
((EventTypes.CanonicalAlias, ""), {"alias": "#test-name:test"}),
]
self.assertEqual("#test-name:test", self._calculate_room_name(events))
@@ -125,7 +125,7 @@ class PresentableNamesTestCase(unittest.HomeserverTestCase):
def test_invite(self) -> None:
"""An invite has special behaviour."""
events: List[Tuple[Tuple[str, str], dict]] = [
events: list[tuple[tuple[str, str], dict]] = [
((EventTypes.Member, self.USER_ID), {"membership": Membership.INVITE}),
((EventTypes.Member, self.OTHER_USER_ID), {"displayname": "Other User"}),
]
@@ -151,7 +151,7 @@ class PresentableNamesTestCase(unittest.HomeserverTestCase):
def test_no_members(self) -> None:
"""Behaviour of an empty room."""
events: List[Tuple[Tuple[str, str], dict]] = []
events: list[tuple[tuple[str, str], dict]] = []
self.assertEqual("Empty Room", self._calculate_room_name(events))
# Note that events with invalid (or missing) membership are ignored.
+5 -5
View File
@@ -19,7 +19,7 @@
#
#
from typing import Any, Dict, List, Optional, Union, cast
from typing import Any, Optional, Union, cast
from twisted.internet.testing import MemoryReactor
@@ -60,7 +60,7 @@ class FlattenDictTestCase(unittest.TestCase):
def test_non_string(self) -> None:
"""String, booleans, ints, nulls and list of those should be kept while other items are dropped."""
input: Dict[str, Any] = {
input: dict[str, Any] = {
"woo": "woo",
"foo": True,
"bar": 1,
@@ -165,13 +165,13 @@ class PushRuleEvaluatorTestCase(unittest.TestCase):
)
room_member_count = 0
sender_power_level = 0
power_levels: Dict[str, Union[int, Dict[str, int]]] = {}
power_levels: dict[str, Union[int, dict[str, int]]] = {}
return PushRuleEvaluator(
_flatten_dict(event),
False,
room_member_count,
sender_power_level,
cast(Dict[str, int], power_levels.get("notifications", {})),
cast(dict[str, int], power_levels.get("notifications", {})),
{} if related_events is None else related_events,
related_event_match_enabled=True,
room_version_feature_flags=event.room_version.msc3931_push_features,
@@ -588,7 +588,7 @@ class PushRuleEvaluatorTestCase(unittest.TestCase):
This tests the behaviour of tweaks_for_actions.
"""
actions: List[Union[Dict[str, str], str]] = [
actions: list[Union[dict[str, str], str]] = [
{"set_tweak": "sound", "value": "default"},
{"set_tweak": "highlight"},
"notify",
+6 -6
View File
@@ -19,7 +19,7 @@
#
import logging
from collections import defaultdict
from typing import Any, Dict, List, Optional, Set, Tuple
from typing import Any, Optional
from twisted.internet.address import IPv4Address
from twisted.internet.protocol import Protocol, connectionDone
@@ -108,7 +108,7 @@ class BaseStreamTestCase(unittest.HomeserverTestCase):
self._client_transport: Optional[FakeTransport] = None
self._server_transport: Optional[FakeTransport] = None
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
d = super().create_resource_dict()
d["/_synapse/replication"] = ReplicationRestResource(self.hs)
return d
@@ -183,7 +183,7 @@ class BaseStreamTestCase(unittest.HomeserverTestCase):
# hook into the channel's request factory so that we can keep a record
# of the requests
requests: List[SynapseRequest] = []
requests: list[SynapseRequest] = []
real_request_factory = channel.requestFactory
def request_factory(*args: Any, **kwargs: Any) -> SynapseRequest:
@@ -256,7 +256,7 @@ class BaseMultiWorkerStreamTestCase(unittest.HomeserverTestCase):
# Redis replication only takes place on Postgres
skip = "Requires Postgres"
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
"""
Overrides the default config to enable Redis.
Even if the test only uses make_worker_hs, the main process needs Redis
@@ -491,7 +491,7 @@ class TestReplicationDataHandler(ReplicationDataHandler):
super().__init__(hs)
# list of received (stream_name, token, row) tuples
self.received_rdata_rows: List[Tuple[str, int, Any]] = []
self.received_rdata_rows: list[tuple[str, int, Any]] = []
async def on_rdata(
self, stream_name: str, instance_name: str, token: int, rows: list
@@ -505,7 +505,7 @@ class FakeRedisPubSubServer:
"""A fake Redis server for pub/sub."""
def __init__(self) -> None:
self._subscribers_by_channel: Dict[bytes, Set["FakeRedisPubSubProtocol"]] = (
self._subscribers_by_channel: dict[bytes, set["FakeRedisPubSubProtocol"]] = (
defaultdict(set)
)
+2 -3
View File
@@ -20,7 +20,6 @@
#
from http import HTTPStatus
from typing import Tuple
from twisted.web.server import Request
@@ -52,7 +51,7 @@ class CancellableReplicationEndpoint(ReplicationEndpoint):
@cancellable
async def _handle_request( # type: ignore[override]
self, request: Request, content: JsonDict
) -> Tuple[int, JsonDict]:
) -> tuple[int, JsonDict]:
await self.clock.sleep(1.0)
return HTTPStatus.OK, {"result": True}
@@ -73,7 +72,7 @@ class UncancellableReplicationEndpoint(ReplicationEndpoint):
async def _handle_request( # type: ignore[override]
self, request: Request, content: JsonDict
) -> Tuple[int, JsonDict]:
) -> tuple[int, JsonDict]:
await self.clock.sleep(1.0)
return HTTPStatus.OK, {"result": True}
+5 -5
View File
@@ -19,7 +19,7 @@
#
#
import logging
from typing import Any, Iterable, List, Optional, Tuple
from typing import Any, Iterable, Optional
from canonicaljson import encode_canonical_json
from parameterized import parameterized
@@ -244,13 +244,13 @@ class EventsWorkerStoreTestCase(BaseWorkerStoreTestCase):
key: Optional[str] = None,
internal: Optional[dict] = None,
depth: Optional[int] = None,
prev_events: Optional[List[Tuple[str, dict]]] = None,
auth_events: Optional[List[str]] = None,
prev_state: Optional[List[str]] = None,
prev_events: Optional[list[tuple[str, dict]]] = None,
auth_events: Optional[list[str]] = None,
prev_state: Optional[list[str]] = None,
redacts: Optional[str] = None,
push_actions: Iterable = frozenset(),
**content: object,
) -> Tuple[EventBase, EventContext]:
) -> tuple[EventBase, EventContext]:
prev_events = prev_events or []
auth_events = auth_events or []
prev_state = prev_state or []
+4 -4
View File
@@ -18,7 +18,7 @@
#
#
from typing import Any, List, Optional
from typing import Any, Optional
from parameterized import parameterized
@@ -299,7 +299,7 @@ class EventsStreamTestCase(BaseStreamTestCase):
self.assertEqual(row.data.event_id, pl_event.event_id)
# the state rows are unsorted
state_rows: List[EventsStreamCurrentStateRow] = []
state_rows: list[EventsStreamCurrentStateRow] = []
for stream_name, _, row in received_event_rows:
self.assertEqual("events", stream_name)
self.assertIsInstance(row, EventsStreamRow)
@@ -355,7 +355,7 @@ class EventsStreamTestCase(BaseStreamTestCase):
self.hs.get_datastores().main.get_latest_event_ids_in_room(self.room_id)
)
events: List[EventBase] = []
events: list[EventBase] = []
for user in user_ids:
events.extend(
self._inject_state_event(sender=user) for _ in range(STATES_PER_USER)
@@ -426,7 +426,7 @@ class EventsStreamTestCase(BaseStreamTestCase):
self.assertEqual(row.data.event_id, pl_events[i].event_id)
# the state rows are unsorted
state_rows: List[EventsStreamCurrentStateRow] = []
state_rows: list[EventsStreamCurrentStateRow] = []
for _ in range(STATES_PER_USER + 1):
stream_name, token, row = received_event_rows.pop(0)
self.assertEqual("events", stream_name)
+3 -3
View File
@@ -20,7 +20,7 @@
#
import logging
import os
from typing import Any, Optional, Tuple
from typing import Any, Optional
from twisted.internet.protocol import Factory
from twisted.internet.testing import MemoryReactor
@@ -78,7 +78,7 @@ class MediaRepoShardTestCase(BaseMultiWorkerStreamTestCase):
def _get_media_req(
self, hs: HomeServer, target: str, media_id: str
) -> Tuple[FakeChannel, Request]:
) -> tuple[FakeChannel, Request]:
"""Request some remote media from the given HS by calling the download
API.
@@ -293,7 +293,7 @@ class AuthenticatedMediaRepoShardTestCase(BaseMultiWorkerStreamTestCase):
def _get_media_req(
self, hs: HomeServer, target: str, media_id: str
) -> Tuple[FakeChannel, Request]:
) -> tuple[FakeChannel, Request]:
"""Request some remote media from the given HS by calling the download
API.
+2 -2
View File
@@ -20,7 +20,7 @@
#
import urllib.parse
from typing import Dict, cast
from typing import cast
from parameterized import parameterized
@@ -65,7 +65,7 @@ class QuarantineMediaTestCase(unittest.HomeserverTestCase):
room.register_servlets,
]
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
+1 -2
View File
@@ -18,7 +18,6 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List
from twisted.internet.testing import MemoryReactor
@@ -441,7 +440,7 @@ class EventReportsTestCase(unittest.HomeserverTestCase):
)
self.assertEqual(200, channel.code, msg=channel.json_body)
def _check_fields(self, content: List[JsonDict]) -> None:
def _check_fields(self, content: list[JsonDict]) -> None:
"""Checks that all attributes are present in an event report"""
for c in content:
self.assertIn("id", c)
+5 -5
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List, Optional
from typing import Optional
from parameterized import parameterized
@@ -272,7 +272,7 @@ class FederationTestCase(unittest.HomeserverTestCase):
"""Testing order list with parameter `order_by`"""
def _order_test(
expected_destination_list: List[str],
expected_destination_list: list[str],
order_by: Optional[str],
dir: Optional[str] = None,
) -> None:
@@ -521,7 +521,7 @@ class FederationTestCase(unittest.HomeserverTestCase):
dest = f"sub{i}.example.com"
self._create_destination(dest, 50, 50, 50, 100)
def _check_fields(self, content: List[JsonDict]) -> None:
def _check_fields(self, content: list[JsonDict]) -> None:
"""Checks that the expected destination attributes are present in content
Args:
@@ -820,7 +820,7 @@ class DestinationMembershipTestCase(unittest.HomeserverTestCase):
self,
number_rooms: int,
destination: Optional[str] = None,
) -> List[str]:
) -> list[str]:
"""
Create the given number of rooms. The given `destination` homeserver will
be recorded as a participant.
@@ -853,7 +853,7 @@ class DestinationMembershipTestCase(unittest.HomeserverTestCase):
return room_ids
def _check_fields(self, content: List[JsonDict]) -> None:
def _check_fields(self, content: list[JsonDict]) -> None:
"""Checks that the expected room attributes are present in content
Args:
+1 -2
View File
@@ -19,7 +19,6 @@
#
#
from typing import Dict
from twisted.web.resource import Resource
@@ -33,7 +32,7 @@ from tests.utils import HAS_AUTHLIB
class JWKSTestCase(HomeserverTestCase):
"""Test /_synapse/jwks JWKS data."""
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
d = super().create_resource_dict()
d.update(build_synapse_client_resource_tree(self.hs))
return d
+1 -2
View File
@@ -20,7 +20,6 @@
#
#
import os
from typing import Dict
from parameterized import parameterized
@@ -51,7 +50,7 @@ class _AdminMediaTests(unittest.HomeserverTestCase):
media.register_servlets,
]
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
+2 -2
View File
@@ -22,7 +22,7 @@ import json
import time
import urllib.parse
from http import HTTPStatus
from typing import List, Optional
from typing import Optional
from unittest.mock import AsyncMock, Mock
from parameterized import parameterized
@@ -1609,7 +1609,7 @@ class RoomTestCase(unittest.HomeserverTestCase):
def _order_test(
order_type: str,
expected_room_list: List[str],
expected_room_list: list[str],
reverse: bool = False,
) -> None:
"""Request the list of rooms in a certain order. Assert that order is what
+4 -4
View File
@@ -13,7 +13,7 @@
#
#
#
from typing import Mapping, Optional, Tuple
from typing import Mapping, Optional
from twisted.internet.testing import MemoryReactor
@@ -42,17 +42,17 @@ class ScheduledTasksAdminApiTestCase(unittest.HomeserverTestCase):
# create and schedule a few tasks
async def _test_task(
task: ScheduledTask,
) -> Tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
) -> tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
return TaskStatus.ACTIVE, None, None
async def _finished_test_task(
task: ScheduledTask,
) -> Tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
) -> tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
return TaskStatus.COMPLETE, None, None
async def _failed_test_task(
task: ScheduledTask,
) -> Tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
) -> tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
return TaskStatus.FAILED, None, "Everything failed"
self._task_scheduler.register_action(_test_task, "test_task")
+2 -2
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List, Sequence
from typing import Sequence
from twisted.internet.testing import MemoryReactor
@@ -729,7 +729,7 @@ class ServerNoticeTestCase(unittest.HomeserverTestCase):
return invited_rooms
def _sync_and_get_messages(self, room_id: str, token: str) -> List[JsonDict]:
def _sync_and_get_messages(self, room_id: str, token: str) -> list[JsonDict]:
"""
Do a sync and get messages of a room.
+4 -4
View File
@@ -19,7 +19,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Dict, List, Optional
from typing import Optional
from twisted.internet.testing import MemoryReactor
from twisted.web.resource import Resource
@@ -50,7 +50,7 @@ class UserMediaStatisticsTestCase(unittest.HomeserverTestCase):
self.url = "/_synapse/admin/v1/statistics/users/media"
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
@@ -485,7 +485,7 @@ class UserMediaStatisticsTestCase(unittest.HomeserverTestCase):
# Upload some media into the room
self.helper.upload_media(SMALL_PNG, tok=user_token, expect_code=200)
def _check_fields(self, content: List[JsonDict]) -> None:
def _check_fields(self, content: list[JsonDict]) -> None:
"""Checks that all attributes are present in content
Args:
content: List that is checked for content
@@ -497,7 +497,7 @@ class UserMediaStatisticsTestCase(unittest.HomeserverTestCase):
self.assertIn("media_length", c)
def _order_test(
self, order_type: str, expected_user_list: List[str], dir: Optional[str] = None
self, order_type: str, expected_user_list: list[str], dir: Optional[str] = None
) -> None:
"""Request the list of users in a certain order. Assert that order is what
we expect
+9 -9
View File
@@ -27,7 +27,7 @@ import time
import urllib.parse
from binascii import unhexlify
from http import HTTPStatus
from typing import Dict, List, Optional
from typing import Optional
from unittest.mock import AsyncMock, Mock, patch
from parameterized import parameterized, parameterized_class
@@ -1185,7 +1185,7 @@ class UsersListTestCase(unittest.HomeserverTestCase):
)
def test_user_type(
expected_user_ids: List[str], not_user_types: Optional[List[str]] = None
expected_user_ids: list[str], not_user_types: Optional[list[str]] = None
) -> None:
"""Runs a test for the not_user_types param
Args:
@@ -1262,7 +1262,7 @@ class UsersListTestCase(unittest.HomeserverTestCase):
)
def test_user_type(
expected_user_ids: List[str], not_user_types: Optional[List[str]] = None
expected_user_ids: list[str], not_user_types: Optional[list[str]] = None
) -> None:
"""Runs a test for the not_user_types param
Args:
@@ -1373,7 +1373,7 @@ class UsersListTestCase(unittest.HomeserverTestCase):
def _order_test(
self,
expected_user_list: List[str],
expected_user_list: list[str],
order_by: Optional[str],
dir: Optional[str] = None,
) -> None:
@@ -1403,7 +1403,7 @@ class UsersListTestCase(unittest.HomeserverTestCase):
self.assertEqual(expected_user_list, returned_order)
self._check_fields(channel.json_body["users"])
def _check_fields(self, content: List[JsonDict]) -> None:
def _check_fields(self, content: list[JsonDict]) -> None:
"""Checks that the expected user attributes are present in content
Args:
content: List that is checked for content
@@ -3690,7 +3690,7 @@ class UserMediaRestTestCase(unittest.HomeserverTestCase):
self.other_user
)
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
@@ -4138,7 +4138,7 @@ class UserMediaRestTestCase(unittest.HomeserverTestCase):
[media2] + sorted([media1, media3]), "safe_from_quarantine", "b"
)
def _create_media_for_user(self, user_token: str, number_media: int) -> List[str]:
def _create_media_for_user(self, user_token: str, number_media: int) -> list[str]:
"""
Create a number of media for a specific user
Args:
@@ -4195,7 +4195,7 @@ class UserMediaRestTestCase(unittest.HomeserverTestCase):
return media_id
def _check_fields(self, content: List[JsonDict]) -> None:
def _check_fields(self, content: list[JsonDict]) -> None:
"""Checks that the expected user attributes are present in content
Args:
content: List that is checked for content
@@ -4212,7 +4212,7 @@ class UserMediaRestTestCase(unittest.HomeserverTestCase):
def _order_test(
self,
expected_media_list: List[str],
expected_media_list: list[str],
order_by: Optional[str],
dir: Optional[str] = None,
) -> None:
@@ -13,7 +13,7 @@
#
import logging
from http import HTTPStatus
from typing import List, Optional, Tuple, cast
from typing import Optional, cast
from twisted.test.proto_helpers import MemoryReactor
@@ -358,7 +358,7 @@ class SlidingSyncThreadSubscriptionsExtensionTestCase(SlidingSyncBase):
using the companion /thread_subscriptions endpoint.
"""
thread_root_ids: List[str] = []
thread_root_ids: list[str] = []
def make_subscription() -> None:
thread_root_resp = self.helper.send(
@@ -455,7 +455,7 @@ class SlidingSyncThreadSubscriptionsExtensionTestCase(SlidingSyncBase):
def _do_backpaginate(
self, *, from_tok: str, to_tok: str, limit: int, access_token: str
) -> Tuple[JsonDict, Optional[str]]:
) -> tuple[JsonDict, Optional[str]]:
channel = self.make_request(
"GET",
"/_matrix/client/unstable/io.element.msc4308/thread_subscriptions"
@@ -12,7 +12,6 @@
# <https://www.gnu.org/licenses/agpl-3.0.html>.
#
import logging
from typing import List
from parameterized import parameterized_class
@@ -59,7 +58,7 @@ class SlidingSyncToDeviceExtensionTestCase(SlidingSyncBase):
super().prepare(reactor, clock, hs)
def _assert_to_device_response(
self, response_body: JsonDict, expected_messages: List[JsonDict]
self, response_body: JsonDict, expected_messages: list[JsonDict]
) -> str:
"""Assert the sliding sync response was successful and has the expected
to-device messages.
@@ -12,7 +12,7 @@
# <https://www.gnu.org/licenses/agpl-3.0.html>.
#
import logging
from typing import List, Optional
from typing import Optional
from parameterized import parameterized_class
@@ -75,14 +75,14 @@ class SlidingSyncRoomsTimelineTestCase(SlidingSyncBase):
if actual_items == expected_items:
return
expected_lines: List[str] = []
expected_lines: list[str] = []
for expected_item in expected_items:
is_expected_in_actual = expected_item in actual_items
expected_lines.append(
"{} {}".format(" " if is_expected_in_actual else "?", expected_item)
)
actual_lines: List[str] = []
actual_lines: list[str] = []
for actual_item in actual_items:
is_actual_in_expected = actual_item in expected_items
actual_lines.append(
@@ -101,8 +101,8 @@ class SlidingSyncRoomsTimelineTestCase(SlidingSyncBase):
self,
*,
room_id: str,
actual_event_ids: List[str],
expected_event_ids: List[str],
actual_event_ids: list[str],
expected_event_ids: list[str],
message: Optional[str] = None,
) -> None:
"""
@@ -12,7 +12,7 @@
# <https://www.gnu.org/licenses/agpl-3.0.html>.
#
import logging
from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple
from typing import Any, Iterable, Literal, Optional
from unittest.mock import AsyncMock
from parameterized import parameterized, parameterized_class
@@ -82,7 +82,7 @@ class SlidingSyncBase(unittest.HomeserverTestCase):
def do_sync(
self, sync_body: JsonDict, *, since: Optional[str] = None, tok: str
) -> Tuple[JsonDict, str]:
) -> tuple[JsonDict, str]:
"""Do a sliding sync request with given body.
Asserts the request was successful.
@@ -170,7 +170,7 @@ class SlidingSyncBase(unittest.HomeserverTestCase):
# Scrutinize the account data since it has no concrete type. We're just copying
# everything into a known type. It should be a mapping from user ID to a list of
# room IDs. Ignore anything else.
new_dm_map: Dict[str, List[str]] = {}
new_dm_map: dict[str, list[str]] = {}
if isinstance(existing_dm_map, dict):
for user_id, room_ids in existing_dm_map.items():
if isinstance(user_id, str) and isinstance(room_ids, list):
@@ -239,7 +239,7 @@ class SlidingSyncBase(unittest.HomeserverTestCase):
def _create_remote_invite_room_for_user(
self,
invitee_user_id: str,
unsigned_invite_room_state: Optional[List[StrippedStateEvent]],
unsigned_invite_room_state: Optional[list[StrippedStateEvent]],
invite_room_id: Optional[str] = None,
) -> str:
"""
+7 -7
View File
@@ -23,7 +23,7 @@ import os
import re
from email.parser import Parser
from http import HTTPStatus
from typing import Any, Dict, List, Optional, Union
from typing import Any, Optional, Union
from unittest.mock import Mock
from twisted.internet.interfaces import IReactorTCP
@@ -87,7 +87,7 @@ class PasswordResetTestCase(unittest.HomeserverTestCase):
) -> None:
self.email_attempts.append(msg_bytes)
self.email_attempts: List[bytes] = []
self.email_attempts: list[bytes] = []
hs.get_send_email_handler()._sendmail = sendmail
return hs
@@ -721,7 +721,7 @@ class WhoamiTestCase(unittest.HomeserverTestCase):
register.register_servlets,
]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["allow_guest_access"] = True
return config
@@ -827,7 +827,7 @@ class ThreepidEmailRestTestCase(unittest.HomeserverTestCase):
) -> None:
self.email_attempts.append(msg_bytes)
self.email_attempts: List[bytes] = []
self.email_attempts: list[bytes] = []
self.hs.get_send_email_handler()._sendmail = sendmail
return self.hs
@@ -1501,10 +1501,10 @@ class AccountStatusTestCase(unittest.HomeserverTestCase):
def _test_status(
self,
users: Optional[List[str]],
users: Optional[list[str]],
expected_status_code: int = HTTPStatus.OK,
expected_statuses: Optional[Dict[str, Dict[str, bool]]] = None,
expected_failures: Optional[List[str]] = None,
expected_statuses: Optional[dict[str, dict[str, bool]]] = None,
expected_failures: Optional[list[str]] = None,
expected_errcode: Optional[str] = None,
) -> None:
"""Send a request to the account status endpoint and check that the response
+10 -10
View File
@@ -20,7 +20,7 @@
#
import re
from http import HTTPStatus
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import Any, Optional, Union
from twisted.internet.defer import succeed
from twisted.internet.testing import MemoryReactor
@@ -47,7 +47,7 @@ from tests.unittest import override_config, skip_unless
class DummyRecaptchaChecker(UserInteractiveAuthChecker):
def __init__(self, hs: HomeServer) -> None:
super().__init__(hs)
self.recaptcha_attempts: List[Tuple[dict, str]] = []
self.recaptcha_attempts: list[tuple[dict, str]] = []
def is_enabled(self) -> bool:
return True
@@ -178,7 +178,7 @@ class UIAuthTests(unittest.HomeserverTestCase):
register.register_servlets,
]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
# public_baseurl uses an http:// scheme because FakeChannel.isSecure() returns
@@ -195,7 +195,7 @@ class UIAuthTests(unittest.HomeserverTestCase):
return config
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resource_dict = super().create_resource_dict()
resource_dict.update(build_synapse_client_resource_tree(self.hs))
return resource_dict
@@ -1091,7 +1091,7 @@ class RefreshAuthTests(unittest.HomeserverTestCase):
was very slow if a lot of refreshes had been performed for the session.
"""
def _refresh(refresh_token: str) -> Tuple[str, str]:
def _refresh(refresh_token: str) -> tuple[str, str]:
"""
Performs one refresh, returning the next refresh token and access token.
"""
@@ -1172,7 +1172,7 @@ class RefreshAuthTests(unittest.HomeserverTestCase):
def oidc_config(
id: str, with_localpart_template: bool, **kwargs: Any
) -> Dict[str, Any]:
) -> dict[str, Any]:
"""Sample OIDC provider config used in backchannel logout tests.
Args:
@@ -1185,7 +1185,7 @@ def oidc_config(
A dict suitable for the `oidc_config` or the `oidc_providers[]` parts of
the HS config
"""
config: Dict[str, Any] = {
config: dict[str, Any] = {
"idp_id": id,
"idp_name": id,
"issuer": TEST_OIDC_ISSUER,
@@ -1213,7 +1213,7 @@ class OidcBackchannelLogoutTests(unittest.HomeserverTestCase):
login.register_servlets,
]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
# public_baseurl uses an http:// scheme because FakeChannel.isSecure() returns
@@ -1223,7 +1223,7 @@ class OidcBackchannelLogoutTests(unittest.HomeserverTestCase):
return config
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resource_dict = super().create_resource_dict()
resource_dict.update(build_synapse_client_resource_tree(self.hs))
return resource_dict
@@ -1363,7 +1363,7 @@ class OidcBackchannelLogoutTests(unittest.HomeserverTestCase):
# We should have a user_mapping_session cookie
cookie_headers = channel.headers.getRawHeaders("Set-Cookie")
assert cookie_headers
cookies: Dict[str, str] = {}
cookies: dict[str, str] = {}
for h in cookie_headers:
key, value = h.split(";")[0].split("=", maxsplit=1)
cookies[key] = value
+1 -2
View File
@@ -15,7 +15,6 @@
"""Tests REST events for /delayed_events paths."""
from http import HTTPStatus
from typing import List
from parameterized import parameterized
@@ -574,7 +573,7 @@ class DelayedEventsTestCase(HomeserverTestCase):
)
self.assertEqual(setter_expected, content.get(setter_key), content)
def _get_delayed_events(self) -> List[JsonDict]:
def _get_delayed_events(self) -> list[JsonDict]:
channel = self.make_request(
"GET",
PATH_PREFIX,
+17 -20
View File
@@ -25,11 +25,8 @@ from typing import (
BinaryIO,
Callable,
Collection,
Dict,
List,
Literal,
Optional,
Tuple,
Union,
)
from unittest.mock import Mock
@@ -146,11 +143,11 @@ class TestSpamChecker:
user_id: str,
device_id: Optional[str],
initial_display_name: Optional[str],
request_info: Collection[Tuple[Optional[str], str]],
request_info: Collection[tuple[Optional[str], str]],
auth_provider_id: Optional[str] = None,
) -> Union[
Literal["NOT_SPAM"],
Tuple["synapse.module_api.errors.Codes", JsonDict],
tuple["synapse.module_api.errors.Codes", JsonDict],
]:
return "NOT_SPAM"
@@ -170,11 +167,11 @@ class DenyAllSpamChecker:
user_id: str,
device_id: Optional[str],
initial_display_name: Optional[str],
request_info: Collection[Tuple[Optional[str], str]],
request_info: Collection[tuple[Optional[str], str]],
auth_provider_id: Optional[str] = None,
) -> Union[
Literal["NOT_SPAM"],
Tuple["synapse.module_api.errors.Codes", JsonDict],
tuple["synapse.module_api.errors.Codes", JsonDict],
]:
# Return an odd set of values to ensure that they get correctly passed
# to the client.
@@ -633,7 +630,7 @@ class MultiSSOTestCase(unittest.HomeserverTestCase):
login.register_servlets,
]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["public_baseurl"] = PUBLIC_BASEURL
@@ -678,7 +675,7 @@ class MultiSSOTestCase(unittest.HomeserverTestCase):
def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
self.login_sso_redirect_url_builder = LoginSSORedirectURIBuilder(hs.config)
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
d = super().create_resource_dict()
d.update(build_synapse_client_resource_tree(self.hs))
return d
@@ -730,7 +727,7 @@ class MultiSSOTestCase(unittest.HomeserverTestCase):
p.close()
# there should be a link for each href
returned_idps: List[str] = []
returned_idps: list[str] = []
for link in p.links:
path, query = link.split("?", 1)
self.assertEqual(path, "pick_idp")
@@ -891,7 +888,7 @@ class MultiSSOTestCase(unittest.HomeserverTestCase):
# ... and should have set a cookie including the redirect url
cookie_headers = channel.headers.getRawHeaders("Set-Cookie")
assert cookie_headers
cookies: Dict[str, str] = {}
cookies: dict[str, str] = {}
for h in cookie_headers:
key, value = h.split(";")[0].split("=", maxsplit=1)
cookies[key] = value
@@ -1179,7 +1176,7 @@ class JWTTestCase(unittest.HomeserverTestCase):
"algorithm": jwt_algorithm,
}
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
# If jwt_config has been defined (eg via @override_config), don't replace it.
@@ -1188,7 +1185,7 @@ class JWTTestCase(unittest.HomeserverTestCase):
return config
def jwt_encode(self, payload: Dict[str, Any], secret: str = jwt_secret) -> str:
def jwt_encode(self, payload: dict[str, Any], secret: str = jwt_secret) -> str:
header = {"alg": self.jwt_algorithm}
result: bytes = jwt.encode(header, payload, secret)
return result.decode("ascii")
@@ -1426,7 +1423,7 @@ class JWTPubKeyTestCase(unittest.HomeserverTestCase):
]
)
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["jwt_config"] = {
"enabled": True,
@@ -1435,7 +1432,7 @@ class JWTPubKeyTestCase(unittest.HomeserverTestCase):
}
return config
def jwt_encode(self, payload: Dict[str, Any], secret: str = jwt_privatekey) -> str:
def jwt_encode(self, payload: dict[str, Any], secret: str = jwt_privatekey) -> str:
header = {"alg": "RS256"}
if secret.startswith("-----BEGIN RSA PRIVATE KEY-----"):
secret = JsonWebKey.import_key(secret, {"kty": "RSA"})
@@ -1630,7 +1627,7 @@ class UsernamePickerTestCase(HomeserverTestCase):
)
return hs
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["public_baseurl"] = PUBLIC_BASEURL
@@ -1649,7 +1646,7 @@ class UsernamePickerTestCase(HomeserverTestCase):
config["sso"] = {"client_whitelist": ["https://x"]}
return config
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
d = super().create_resource_dict()
d.update(build_synapse_client_resource_tree(self.hs))
return d
@@ -1660,7 +1657,7 @@ class UsernamePickerTestCase(HomeserverTestCase):
displayname: str,
email: str,
picture: str,
) -> Tuple[str, str]:
) -> tuple[str, str]:
# do the start of the login flow
channel, _ = self.helper.auth_via_oidc(
fake_oidc_server,
@@ -1681,7 +1678,7 @@ class UsernamePickerTestCase(HomeserverTestCase):
self.assertEqual(picker_url, "/_synapse/client/pick_username/account_details")
# ... with a username_mapping_session cookie
cookies: Dict[str, str] = {}
cookies: dict[str, str] = {}
channel.extract_cookies(cookies)
self.assertIn("username_mapping_session", cookies)
session_id = cookies["username_mapping_session"]
@@ -1894,5 +1891,5 @@ async def mock_get_file(
max_size: Optional[int] = None,
headers: Optional[RawHeaders] = None,
is_allowed_content_type: Optional[Callable[[str], bool]] = None,
) -> Tuple[int, Dict[bytes, List[bytes]], str, int]:
) -> tuple[int, dict[bytes, list[bytes]], str, int]:
return 0, {b"Content-Type": [b"image/png"]}, "", 200
+19 -19
View File
@@ -24,7 +24,7 @@ import json
import os
import re
import shutil
from typing import Any, BinaryIO, ClassVar, Dict, List, Optional, Sequence, Tuple, Type
from typing import Any, BinaryIO, ClassVar, Optional, Sequence
from unittest.mock import MagicMock, Mock, patch
from urllib import parse
from urllib.parse import quote, urlencode
@@ -265,7 +265,7 @@ class URLPreviewTests(unittest.HomeserverTestCase):
assert self.media_repo.url_previewer is not None
self.url_previewer = self.media_repo.url_previewer
self.lookups: Dict[str, Any] = {}
self.lookups: dict[str, Any] = {}
class Resolver:
def resolveHostName(
@@ -273,7 +273,7 @@ class URLPreviewTests(unittest.HomeserverTestCase):
resolutionReceiver: IResolutionReceiver,
hostName: str,
portNumber: int = 0,
addressTypes: Optional[Sequence[Type[IAddress]]] = None,
addressTypes: Optional[Sequence[type[IAddress]]] = None,
transportSemantics: str = "TCP",
) -> IResolutionReceiver:
resolution = HostResolution(hostName)
@@ -1357,7 +1357,7 @@ class URLPreviewTests(unittest.HomeserverTestCase):
self.assertEqual(body["og:title"], "Test")
self.assertNotIn("og:image", body)
def _download_image(self) -> Tuple[str, str]:
def _download_image(self) -> tuple[str, str]:
"""Downloads an image into the URL cache.
Returns:
A (host, media_id) tuple representing the MXC URI of the image.
@@ -1994,8 +1994,8 @@ class DownloadAndThumbnailTestCase(unittest.HomeserverTestCase):
]
def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
self.fetches: List[
Tuple[
self.fetches: list[
tuple[
"Deferred[Any]",
str,
str,
@@ -2014,12 +2014,12 @@ class DownloadAndThumbnailTestCase(unittest.HomeserverTestCase):
retry_on_dns_fail: bool = True,
ignore_backoff: bool = False,
follow_redirects: bool = False,
) -> "Deferred[Tuple[int, Dict[bytes, List[bytes]], bytes]]":
) -> "Deferred[tuple[int, dict[bytes, list[bytes]], bytes]]":
"""A mock for MatrixFederationHttpClient.federation_get_file."""
def write_to(
r: Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]], bytes]],
) -> Tuple[int, Dict[bytes, List[bytes]], bytes]:
r: tuple[bytes, tuple[int, dict[bytes, list[bytes]], bytes]],
) -> tuple[int, dict[bytes, list[bytes]], bytes]:
data, response = r
output_stream.write(data)
return response
@@ -2029,7 +2029,7 @@ class DownloadAndThumbnailTestCase(unittest.HomeserverTestCase):
output_stream.write(f.value.response)
return f
d: Deferred[Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]], bytes]]] = (
d: Deferred[tuple[bytes, tuple[int, dict[bytes, list[bytes]], bytes]]] = (
Deferred()
)
self.fetches.append((d, destination, path, args))
@@ -2048,12 +2048,12 @@ class DownloadAndThumbnailTestCase(unittest.HomeserverTestCase):
retry_on_dns_fail: bool = True,
ignore_backoff: bool = False,
follow_redirects: bool = False,
) -> "Deferred[Tuple[int, Dict[bytes, List[bytes]]]]":
) -> "Deferred[tuple[int, dict[bytes, list[bytes]]]]":
"""A mock for MatrixFederationHttpClient.get_file."""
def write_to(
r: Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]]]],
) -> Tuple[int, Dict[bytes, List[bytes]]]:
r: tuple[bytes, tuple[int, dict[bytes, list[bytes]]]],
) -> tuple[int, dict[bytes, list[bytes]]]:
data, response = r
output_stream.write(data)
return response
@@ -2063,7 +2063,7 @@ class DownloadAndThumbnailTestCase(unittest.HomeserverTestCase):
output_stream.write(f.value.response)
return f
d: Deferred[Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]]]]] = Deferred()
d: Deferred[tuple[bytes, tuple[int, dict[bytes, list[bytes]]]]] = Deferred()
self.fetches.append((d, destination, path, args))
# Note that this callback changes the value held by d.
d_after_callback = d.addCallbacks(write_to, write_err)
@@ -2538,7 +2538,7 @@ configs = [
@parameterized_class(configs)
class AuthenticatedMediaTestCase(unittest.HomeserverTestCase):
extra_config: Dict[str, Any]
extra_config: dict[str, Any]
servlets = [
media.register_servlets,
login.register_servlets,
@@ -2576,7 +2576,7 @@ class AuthenticatedMediaTestCase(unittest.HomeserverTestCase):
self.user = self.register_user("user", "pass")
self.tok = self.login("user", "pass")
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
@@ -2895,7 +2895,7 @@ class MediaUploadLimits(unittest.HomeserverTestCase):
self.user = self.register_user("user", "pass")
self.tok = self.login("user", "pass")
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
@@ -3012,7 +3012,7 @@ class MediaUploadLimitsModuleOverrides(unittest.HomeserverTestCase):
async def _get_media_upload_limits_for_user(
self,
user_id: str,
) -> Optional[List[MediaUploadLimit]]:
) -> Optional[list[MediaUploadLimit]]:
# user1 has custom limits
if user_id == self.user1:
# n.b. we return these in increasing duration order and Synapse will need to sort them correctly
@@ -3060,7 +3060,7 @@ class MediaUploadLimitsModuleOverrides(unittest.HomeserverTestCase):
on_media_upload_limit_exceeded=self._on_media_upload_limit_exceeded,
)
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
resources = super().create_resource_dict()
resources["/_matrix/media"] = self.hs.get_media_repository_resource()
return resources
+2 -2
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List, Optional, Tuple
from typing import Optional
from unittest.mock import AsyncMock, Mock
from twisted.internet.testing import MemoryReactor
@@ -156,7 +156,7 @@ class HTTPPusherTests(HomeserverTestCase):
def _request_notifications(
self, from_token: Optional[str], limit: int, expected_count: int
) -> Tuple[List[str], str]:
) -> tuple[list[str], str]:
"""
Make a request to /notifications to get the latest events to be notified about.
+2 -2
View File
@@ -24,7 +24,7 @@
import logging
import urllib.parse
from http import HTTPStatus
from typing import Any, Dict, Optional
from typing import Any, Optional
from canonicaljson import encode_canonical_json
@@ -778,7 +778,7 @@ class ProfileTestCase(unittest.HomeserverTestCase):
self.assertEqual(channel.code, 403, channel.result)
self.assertEqual(channel.json_body["errcode"], Codes.FORBIDDEN)
def _setup_local_files(self, names_and_props: Dict[str, Dict[str, Any]]) -> None:
def _setup_local_files(self, names_and_props: dict[str, dict[str, Any]]) -> None:
"""Stores metadata about files in the database.
Args:
+3 -3
View File
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List, Optional
from typing import Optional
from parameterized import parameterized
@@ -85,7 +85,7 @@ class RedactionsTestCase(HomeserverTestCase):
room_id: str,
event_id: str,
expect_code: int = 200,
with_relations: Optional[List[str]] = None,
with_relations: Optional[list[str]] = None,
content: Optional[JsonDict] = None,
) -> JsonDict:
"""Helper function to send a redaction event.
@@ -104,7 +104,7 @@ class RedactionsTestCase(HomeserverTestCase):
self.assertEqual(channel.code, expect_code)
return channel.json_body
def _sync_room_timeline(self, access_token: str, room_id: str) -> List[JsonDict]:
def _sync_room_timeline(self, access_token: str, room_id: str) -> list[JsonDict]:
channel = self.make_request("GET", "sync", access_token=access_token)
self.assertEqual(channel.code, 200)
room_sync = channel.json_body["rooms"]["join"][room_id]
+5 -5
View File
@@ -22,7 +22,7 @@
import datetime
import importlib.resources as importlib_resources
import os
from typing import Any, Dict, List, Tuple
from typing import Any
from unittest.mock import AsyncMock
from twisted.internet.testing import MemoryReactor
@@ -54,7 +54,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
]
url = b"/_matrix/client/r0/register"
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["allow_guest_access"] = True
return config
@@ -1032,7 +1032,7 @@ class AccountValidityRenewalByEmailTestCase(unittest.HomeserverTestCase):
async def sendmail(*args: Any, **kwargs: Any) -> None:
self.email_attempts.append((args, kwargs))
self.email_attempts: List[Tuple[Any, Any]] = []
self.email_attempts: list[tuple[Any, Any]] = []
self.hs.get_send_email_handler()._sendmail = sendmail
self.store = self.hs.get_datastores().main
@@ -1146,7 +1146,7 @@ class AccountValidityRenewalByEmailTestCase(unittest.HomeserverTestCase):
self.assertEqual(len(self.email_attempts), 0)
def create_user(self) -> Tuple[str, str]:
def create_user(self) -> tuple[str, str]:
user_id = self.register_user("kermit", "monkey")
tok = self.login("kermit", "monkey")
# We need to manually add an email address otherwise the handler will do
@@ -1250,7 +1250,7 @@ class RegistrationTokenValidityRestServletTestCase(unittest.HomeserverTestCase):
servlets = [register.register_servlets]
url = "/_matrix/client/v1/register/m.login.registration_token/validity"
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
config["registration_requires_token"] = True
return config
+11 -11
View File
@@ -20,7 +20,7 @@
#
import urllib.parse
from typing import Any, Callable, Dict, List, Optional, Tuple
from typing import Any, Callable, Optional
from unittest.mock import AsyncMock, patch
from twisted.internet.testing import MemoryReactor
@@ -48,7 +48,7 @@ class BaseRelationsTestCase(unittest.HomeserverTestCase):
]
hijack_auth = False
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
# We need to enable msc1849 support for aggregations
config = super().default_config()
@@ -69,7 +69,7 @@ class BaseRelationsTestCase(unittest.HomeserverTestCase):
res = self.helper.send(self.room, body="Hi!", tok=self.user_token)
self.parent_id = res["event_id"]
def _create_user(self, localpart: str) -> Tuple[str, str]:
def _create_user(self, localpart: str) -> tuple[str, str]:
user_id = self.register_user(localpart, "abc123")
access_token = self.login(localpart, "abc123")
@@ -123,7 +123,7 @@ class BaseRelationsTestCase(unittest.HomeserverTestCase):
self.assertEqual(expected_response_code, channel.code, channel.json_body)
return channel
def _get_related_events(self) -> List[str]:
def _get_related_events(self) -> list[str]:
"""
Requests /relations on the parent ID and returns a list of event IDs.
"""
@@ -149,7 +149,7 @@ class BaseRelationsTestCase(unittest.HomeserverTestCase):
self.assertEqual(200, channel.code, channel.json_body)
return channel.json_body["unsigned"].get("m.relations", {})
def _find_event_in_chunk(self, events: List[JsonDict]) -> JsonDict:
def _find_event_in_chunk(self, events: list[JsonDict]) -> JsonDict:
"""
Find the parent event in a chunk of events and assert that it has the proper bundled aggregations.
"""
@@ -846,7 +846,7 @@ class RelationPaginationTestCase(BaseRelationsTestCase):
expected_event_ids.append(channel.json_body["event_id"])
prev_token: Optional[str] = ""
found_event_ids: List[str] = []
found_event_ids: list[str] = []
for _ in range(20):
from_token = ""
if prev_token:
@@ -1484,9 +1484,9 @@ class RelationIgnoredUserTestCase(BaseRelationsTestCase):
def _test_ignored_user(
self,
relation_type: str,
allowed_event_ids: List[str],
ignored_event_ids: List[str],
) -> Tuple[JsonDict, JsonDict]:
allowed_event_ids: list[str],
ignored_event_ids: list[str],
) -> tuple[JsonDict, JsonDict]:
"""
Fetch the relations and ensure they're all there, then ignore user2, and
repeat.
@@ -1600,7 +1600,7 @@ class RelationRedactionTestCase(BaseRelationsTestCase):
)
self.assertEqual(200, channel.code, channel.json_body)
def _get_threads(self) -> List[Tuple[str, str]]:
def _get_threads(self) -> list[tuple[str, str]]:
"""Request the threads in the room and returns a list of thread ID and latest event ID."""
# Request the threads in the room.
channel = self.make_request(
@@ -1793,7 +1793,7 @@ class RelationRedactionTestCase(BaseRelationsTestCase):
class ThreadsTestCase(BaseRelationsTestCase):
def _get_threads(self, body: JsonDict) -> List[Tuple[str, str]]:
def _get_threads(self, body: JsonDict) -> list[tuple[str, str]]:
return [
(
ev["event_id"],
+1 -2
View File
@@ -19,7 +19,6 @@
#
#
from typing import Dict
from urllib.parse import urlparse
from twisted.internet.testing import MemoryReactor
@@ -46,7 +45,7 @@ class RendezvousServletTestCase(unittest.HomeserverTestCase):
self.hs = self.setup_test_homeserver()
return self.hs
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
return {
**super().create_resource_dict(),
"/_synapse/client/rendezvous": MSC4108RendezvousSessionResource(self.hs),
+2 -2
View File
@@ -17,7 +17,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Any, Dict
from typing import Any
from unittest.mock import Mock
from twisted.internet.testing import MemoryReactor
@@ -265,7 +265,7 @@ class RetentionNoDefaultPolicyTestCase(unittest.HomeserverTestCase):
room.register_servlets,
]
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
retention_config = {
+15 -15
View File
@@ -25,7 +25,7 @@
import json
from http import HTTPStatus
from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, Union
from typing import Any, Iterable, Literal, Optional, Union
from unittest.mock import AsyncMock, Mock, call, patch
from urllib import parse as urlparse
@@ -989,7 +989,7 @@ class RoomsCreateTestCase(RoomBase):
mxid: str,
room_id: str,
is_invite: bool,
) -> Tuple[Codes, dict]:
) -> tuple[Codes, dict]:
return Codes.INCOMPATIBLE_ROOM_VERSION, {}
join_mock.side_effect = user_may_join_room_tuple
@@ -1002,7 +1002,7 @@ class RoomsCreateTestCase(RoomBase):
self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
self.assertEqual(join_mock.call_count, 0)
def _create_basic_room(self) -> Tuple[int, object]:
def _create_basic_room(self) -> tuple[int, object]:
"""
Tries to create a basic room and returns the response code.
"""
@@ -1351,7 +1351,7 @@ class RoomJoinTestCase(RoomBase):
"""
# Register a dummy callback. Make it allow all room joins for now.
return_value: Union[Literal["NOT_SPAM"], Tuple[Codes, dict], Codes] = (
return_value: Union[Literal["NOT_SPAM"], tuple[Codes, dict], Codes] = (
synapse.module_api.NOT_SPAM
)
@@ -1359,7 +1359,7 @@ class RoomJoinTestCase(RoomBase):
userid: str,
room_id: str,
is_invited: bool,
) -> Union[Literal["NOT_SPAM"], Tuple[Codes, dict], Codes]:
) -> Union[Literal["NOT_SPAM"], tuple[Codes, dict], Codes]:
return return_value
# `spec` argument is needed for this function mock to have `__qualname__`, which
@@ -1848,12 +1848,12 @@ class RoomMessagesTestCase(RoomBase):
def test_spam_checker_check_event_for_spam(
self,
name: str,
value: Union[str, bool, Codes, Tuple[Codes, JsonDict]],
value: Union[str, bool, Codes, tuple[Codes, JsonDict]],
expected_code: int,
expected_fields: dict,
) -> None:
class SpamCheck:
mock_return_value: Union[str, bool, Codes, Tuple[Codes, JsonDict], bool] = (
mock_return_value: Union[str, bool, Codes, tuple[Codes, JsonDict], bool] = (
"NOT_SPAM"
)
mock_content: Optional[JsonDict] = None
@@ -1861,7 +1861,7 @@ class RoomMessagesTestCase(RoomBase):
async def check_event_for_spam(
self,
event: synapse.events.EventBase,
) -> Union[str, Codes, Tuple[Codes, JsonDict], bool]:
) -> Union[str, Codes, tuple[Codes, JsonDict], bool]:
self.mock_content = event.content
return self.mock_return_value
@@ -1915,7 +1915,7 @@ class RoomPowerLevelOverridesTestCase(RoomBase):
self.admin_user_id = self.register_user("admin", "pass")
self.admin_access_token = self.login("admin", "pass")
def power_levels(self, room_id: str) -> Dict[str, Any]:
def power_levels(self, room_id: str) -> dict[str, Any]:
return self.helper.get_state(
room_id, "m.room.power_levels", self.admin_access_token
)
@@ -2076,7 +2076,7 @@ class RoomPowerLevelOverridesInPracticeTestCase(RoomBase):
# Given the server has config allowing normal users to post my event type
# And I am a normal member of a room
# But the room was created with special permissions
extra_content: Dict[str, Any] = {
extra_content: dict[str, Any] = {
"power_level_content_override": {"events": {}},
}
room_id = self.helper.create_room_as(
@@ -2707,9 +2707,9 @@ class PublicRoomsRoomTypeFilterTestCase(unittest.HomeserverTestCase):
def make_public_rooms_request(
self,
room_types: Optional[List[Union[str, None]]],
room_types: Optional[list[Union[str, None]]],
instance_id: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
) -> tuple[list[dict[str, Any]], int]:
body: JsonDict = {"filter": {PublicRoomsFilterFields.ROOM_TYPES: room_types}}
if instance_id:
body["third_party_instance_id"] = "test|test"
@@ -3470,7 +3470,7 @@ class LabelsTestCase(unittest.HomeserverTestCase):
class RelationsTestCase(PaginationTestCase):
def _filter_messages(self, filter: JsonDict) -> List[str]:
def _filter_messages(self, filter: JsonDict) -> list[str]:
"""Make a request to /messages with a filter, returns the chunk of events."""
from_token = self.get_success(
self.from_token.to_string(self.hs.get_datastores().main)
@@ -4529,8 +4529,8 @@ class MSC4293RedactOnBanKickTestCase(unittest.FederatingHomeserverTestCase):
def _check_redactions(
self,
original_events: List[EventBase],
pulled_events: List[JsonDict],
original_events: list[EventBase],
pulled_events: list[JsonDict],
expect_redaction: bool,
reason: Optional[str] = None,
) -> None:
+1 -2
View File
@@ -20,7 +20,6 @@
#
import json
import logging
from typing import List
from parameterized import parameterized
@@ -131,7 +130,7 @@ class SyncFilterTestCase(unittest.HomeserverTestCase):
self.assertEqual(len(events), 1, [event["content"] for event in events])
self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0])
def _test_sync_filter_labels(self, sync_filter: str) -> List[JsonDict]:
def _test_sync_filter_labels(self, sync_filter: str) -> list[JsonDict]:
user_id = self.register_user("kermit", "test")
tok = self.login("kermit", "test")
+11 -11
View File
@@ -19,7 +19,7 @@
#
#
import threading
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
from typing import TYPE_CHECKING, Any, Optional, Union
from unittest.mock import AsyncMock, Mock
from twisted.internet.testing import MemoryReactor
@@ -48,7 +48,7 @@ thread_local = threading.local()
class LegacyThirdPartyRulesTestModule:
def __init__(self, config: Dict, module_api: "ModuleApi") -> None:
def __init__(self, config: dict, module_api: "ModuleApi") -> None:
# keep a record of the "current" rules module, so that the test can patch
# it if desired.
thread_local.rules_module = self
@@ -65,12 +65,12 @@ class LegacyThirdPartyRulesTestModule:
return True
@staticmethod
def parse_config(config: Dict[str, Any]) -> Dict[str, Any]:
def parse_config(config: dict[str, Any]) -> dict[str, Any]:
return config
class LegacyDenyNewRooms(LegacyThirdPartyRulesTestModule):
def __init__(self, config: Dict, module_api: "ModuleApi") -> None:
def __init__(self, config: dict, module_api: "ModuleApi") -> None:
super().__init__(config, module_api)
async def on_create_room(
@@ -80,7 +80,7 @@ class LegacyDenyNewRooms(LegacyThirdPartyRulesTestModule):
class LegacyChangeEvents(LegacyThirdPartyRulesTestModule):
def __init__(self, config: Dict, module_api: "ModuleApi") -> None:
def __init__(self, config: dict, module_api: "ModuleApi") -> None:
super().__init__(config, module_api)
async def check_event_allowed(
@@ -150,7 +150,7 @@ class ThirdPartyRulesTestCase(unittest.FederatingHomeserverTestCase):
# types
async def check(
ev: EventBase, state: StateMap[EventBase]
) -> Tuple[bool, Optional[JsonDict]]:
) -> tuple[bool, Optional[JsonDict]]:
return ev.type != "foo.bar.forbidden", None
callback = Mock(spec=[], side_effect=check)
@@ -207,7 +207,7 @@ class ThirdPartyRulesTestCase(unittest.FederatingHomeserverTestCase):
# add a callback that will raise our hacky exception
async def check(
ev: EventBase, state: StateMap[EventBase]
) -> Tuple[bool, Optional[JsonDict]]:
) -> tuple[bool, Optional[JsonDict]]:
raise NastyHackException(429, "message")
self.hs.get_module_api_callbacks().third_party_event_rules._check_event_allowed_callbacks = [
@@ -235,7 +235,7 @@ class ThirdPartyRulesTestCase(unittest.FederatingHomeserverTestCase):
# first patch the event checker so that it will try to modify the event
async def check(
ev: EventBase, state: StateMap[EventBase]
) -> Tuple[bool, Optional[JsonDict]]:
) -> tuple[bool, Optional[JsonDict]]:
ev.content = {"x": "y"}
return True, None
@@ -260,7 +260,7 @@ class ThirdPartyRulesTestCase(unittest.FederatingHomeserverTestCase):
# first patch the event checker so that it will modify the event
async def check(
ev: EventBase, state: StateMap[EventBase]
) -> Tuple[bool, Optional[JsonDict]]:
) -> tuple[bool, Optional[JsonDict]]:
d = ev.get_dict()
d["content"] = {"x": "y"}
return True, d
@@ -295,7 +295,7 @@ class ThirdPartyRulesTestCase(unittest.FederatingHomeserverTestCase):
# first patch the event checker so that it will modify the event
async def check(
ev: EventBase, state: StateMap[EventBase]
) -> Tuple[bool, Optional[JsonDict]]:
) -> tuple[bool, Optional[JsonDict]]:
d = ev.get_dict()
d["content"] = {
"msgtype": "m.text",
@@ -443,7 +443,7 @@ class ThirdPartyRulesTestCase(unittest.FederatingHomeserverTestCase):
# Define a callback that sends a custom event on power levels update.
async def test_fn(
event: EventBase, state_events: StateMap[EventBase]
) -> Tuple[bool, Optional[JsonDict]]:
) -> tuple[bool, Optional[JsonDict]]:
if event.is_state() and event.type == EventTypes.PowerLevels:
await api.create_and_send_event_into_room(
{
+4 -4
View File
@@ -20,7 +20,7 @@
#
from http import HTTPStatus
from typing import Any, Generator, Tuple, cast
from typing import Any, Generator, cast
from unittest.mock import AsyncMock, Mock, call
from twisted.internet import defer, reactor as _reactor
@@ -92,7 +92,7 @@ class HttpTransactionCacheTestCase(unittest.TestCase):
self,
) -> Generator["defer.Deferred[Any]", object, None]:
@defer.inlineCallbacks
def cb() -> Generator["defer.Deferred[object]", object, Tuple[int, JsonDict]]:
def cb() -> Generator["defer.Deferred[object]", object, tuple[int, JsonDict]]:
# Ignore `multiple-internal-clocks` linter error here since we are creating a `Clock`
# for testing purposes.
yield defer.ensureDeferred(
@@ -124,7 +124,7 @@ class HttpTransactionCacheTestCase(unittest.TestCase):
"""
called = [False]
def cb() -> "defer.Deferred[Tuple[int, JsonDict]]":
def cb() -> "defer.Deferred[tuple[int, JsonDict]]":
if called[0]:
# return a valid result the second time
return defer.succeed(self.mock_http_response)
@@ -156,7 +156,7 @@ class HttpTransactionCacheTestCase(unittest.TestCase):
"""
called = [False]
def cb() -> "defer.Deferred[Tuple[int, JsonDict]]":
def cb() -> "defer.Deferred[tuple[int, JsonDict]]":
if called[0]:
# return a valid result the second time
return defer.succeed(self.mock_http_response)
+15 -17
View File
@@ -30,14 +30,12 @@ from typing import (
Any,
AnyStr,
Callable,
Dict,
Iterable,
Literal,
Mapping,
MutableMapping,
Optional,
Sequence,
Tuple,
overload,
)
from urllib.parse import urlencode
@@ -87,8 +85,8 @@ class RestHelper:
room_version: Optional[str] = ...,
tok: Optional[str] = ...,
expect_code: Literal[200] = ...,
extra_content: Optional[Dict] = ...,
custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = ...,
extra_content: Optional[dict] = ...,
custom_headers: Optional[Iterable[tuple[AnyStr, AnyStr]]] = ...,
) -> str: ...
@overload
@@ -99,8 +97,8 @@ class RestHelper:
room_version: Optional[str] = ...,
tok: Optional[str] = ...,
expect_code: int = ...,
extra_content: Optional[Dict] = ...,
custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = ...,
extra_content: Optional[dict] = ...,
custom_headers: Optional[Iterable[tuple[AnyStr, AnyStr]]] = ...,
) -> Optional[str]: ...
def create_room_as(
@@ -110,8 +108,8 @@ class RestHelper:
room_version: Optional[str] = None,
tok: Optional[str] = None,
expect_code: int = HTTPStatus.OK,
extra_content: Optional[Dict] = None,
custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
extra_content: Optional[dict] = None,
custom_headers: Optional[Iterable[tuple[AnyStr, AnyStr]]] = None,
) -> Optional[str]:
"""
Create a room.
@@ -310,7 +308,7 @@ class RestHelper:
self.auth_user_id = src
path = f"/_matrix/client/r0/rooms/{room}/state/m.room.member/{targ}"
url_params: Dict[str, str] = {}
url_params: dict[str, str] = {}
if tok:
url_params["access_token"] = tok
@@ -378,7 +376,7 @@ class RestHelper:
txn_id: Optional[str] = None,
tok: Optional[str] = None,
expect_code: int = HTTPStatus.OK,
custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
custom_headers: Optional[Iterable[tuple[AnyStr, AnyStr]]] = None,
type: str = "m.room.message",
) -> JsonDict:
if body is None:
@@ -430,7 +428,7 @@ class RestHelper:
txn_id: Optional[str] = None,
tok: Optional[str] = None,
expect_code: int = HTTPStatus.OK,
custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
custom_headers: Optional[Iterable[tuple[AnyStr, AnyStr]]] = None,
) -> JsonDict:
if txn_id is None:
txn_id = "m%s" % (str(time.time()))
@@ -497,7 +495,7 @@ class RestHelper:
self,
room_id: str,
event_type: str,
body: Optional[Dict[str, Any]],
body: Optional[dict[str, Any]],
tok: Optional[str],
expect_code: int = HTTPStatus.OK,
state_key: str = "",
@@ -575,7 +573,7 @@ class RestHelper:
self,
room_id: str,
event_type: str,
body: Dict[str, Any],
body: dict[str, Any],
tok: Optional[str] = None,
expect_code: int = HTTPStatus.OK,
state_key: str = "",
@@ -684,7 +682,7 @@ class RestHelper:
with_sid: bool = False,
idp_id: Optional[str] = None,
expected_status: int = 200,
) -> Tuple[JsonDict, FakeAuthorizationGrant]:
) -> tuple[JsonDict, FakeAuthorizationGrant]:
"""Log in (as a new user) via OIDC
Returns the result of the final token login and the fake authorization grant.
@@ -757,7 +755,7 @@ class RestHelper:
ui_auth_session_id: Optional[str] = None,
with_sid: bool = False,
idp_id: Optional[str] = None,
) -> Tuple[FakeChannel, FakeAuthorizationGrant]:
) -> tuple[FakeChannel, FakeAuthorizationGrant]:
"""Perform an OIDC authentication flow via a mock OIDC provider.
This can be used for either login or user-interactive auth.
@@ -790,7 +788,7 @@ class RestHelper:
went.
"""
cookies: Dict[str, str] = {}
cookies: dict[str, str] = {}
with fake_server.patch_homeserver(hs=self.hs):
# if we're doing a ui auth, hit the ui auth redirect endpoint
@@ -824,7 +822,7 @@ class RestHelper:
cookies: Mapping[str, str],
user_info_dict: JsonDict,
with_sid: bool = False,
) -> Tuple[FakeChannel, FakeAuthorizationGrant]:
) -> tuple[FakeChannel, FakeAuthorizationGrant]:
"""Mock out an OIDC authentication flow
Assumes that an OIDC auth has been initiated by one of initiate_sso_login or
@@ -19,7 +19,7 @@
#
#
from io import BytesIO, StringIO
from typing import Any, Dict, Optional, Union
from typing import Any, Optional, Union
from unittest.mock import Mock
import signedjson.key
@@ -156,7 +156,7 @@ class EndToEndPerspectivesTests(BaseRemoteKeyResourceTestCase):
endpoint, to check that the two implementations are compatible.
"""
def default_config(self) -> Dict[str, Any]:
def default_config(self) -> dict[str, Any]:
config = super().default_config()
# replace the signing key with our own
+1 -2
View File
@@ -18,7 +18,6 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Dict
from twisted.internet.testing import MemoryReactor
from twisted.web.resource import Resource
@@ -65,7 +64,7 @@ class MediaDomainBlockingTests(unittest.HomeserverTestCase):
)
)
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
# We need to manually set the resource tree to include media, the
# default only does `/_matrix/client` APIs.
return {"/_matrix/media": self.hs.get_media_repository_resource()}
+5 -5
View File
@@ -22,7 +22,7 @@ import base64
import json
import os
import re
from typing import Any, Dict, Optional, Sequence, Tuple, Type
from typing import Any, Optional, Sequence
from urllib.parse import quote, urlencode
from twisted.internet._resolver import HostResolution
@@ -127,7 +127,7 @@ class URLPreviewTests(unittest.HomeserverTestCase):
assert self.media_repo.url_previewer is not None
self.url_previewer = self.media_repo.url_previewer
self.lookups: Dict[str, Any] = {}
self.lookups: dict[str, Any] = {}
class Resolver:
def resolveHostName(
@@ -135,7 +135,7 @@ class URLPreviewTests(unittest.HomeserverTestCase):
resolutionReceiver: IResolutionReceiver,
hostName: str,
portNumber: int = 0,
addressTypes: Optional[Sequence[Type[IAddress]]] = None,
addressTypes: Optional[Sequence[type[IAddress]]] = None,
transportSemantics: str = "TCP",
) -> IResolutionReceiver:
resolution = HostResolution(hostName)
@@ -150,7 +150,7 @@ class URLPreviewTests(unittest.HomeserverTestCase):
self.reactor.nameResolver = Resolver() # type: ignore[assignment]
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
"""Create a resource tree for the test server
A resource tree is a mapping from path to twisted.web.resource.
@@ -1227,7 +1227,7 @@ class URLPreviewTests(unittest.HomeserverTestCase):
self.assertEqual(body["og:title"], "Test")
self.assertNotIn("og:image", body)
def _download_image(self) -> Tuple[str, str]:
def _download_image(self) -> tuple[str, str]:
"""Downloads an image into the URL cache.
Returns:
A (host, media_id) tuple representing the MXC URI of the image.
@@ -11,7 +11,6 @@
# See the GNU Affero General Public License for more details:
# <https://www.gnu.org/licenses/agpl-3.0.html>.
from typing import Dict
from twisted.web.resource import Resource
@@ -28,7 +27,7 @@ class FederationWhitelistTests(unittest.HomeserverTestCase):
login.register_servlets,
]
def create_resource_dict(self) -> Dict[str, Resource]:
def create_resource_dict(self) -> dict[str, Resource]:
base = super().create_resource_dict()
base.update(build_synapse_client_resource_tree(self.hs))
return base
+7 -7
View File
@@ -18,7 +18,7 @@
#
#
from typing import List, Optional
from typing import Optional
from unittest.mock import Mock, patch
from synapse._scripts.register_new_matrix_user import request_registration
@@ -60,8 +60,8 @@ class RegisterTestCase(TestCase):
requests.post = post
# The fake stdout will be written here
out: List[str] = []
err_code: List[int] = []
out: list[str] = []
err_code: list[int] = []
with patch("synapse._scripts.register_new_matrix_user.requests", requests):
request_registration(
@@ -96,8 +96,8 @@ class RegisterTestCase(TestCase):
requests.get = get
# The fake stdout will be written here
out: List[str] = []
err_code: List[int] = []
out: list[str] = []
err_code: list[int] = []
with patch("synapse._scripts.register_new_matrix_user.requests", requests):
request_registration(
@@ -151,8 +151,8 @@ class RegisterTestCase(TestCase):
requests.post = post
# The fake stdout will be written here
out: List[str] = []
err_code: List[int] = []
out: list[str] = []
err_code: list[int] = []
with patch("synapse._scripts.register_new_matrix_user.requests", requests):
request_registration(
+12 -17
View File
@@ -35,15 +35,10 @@ from typing import (
Any,
Awaitable,
Callable,
Deque,
Dict,
Iterable,
List,
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
cast,
@@ -124,7 +119,7 @@ R = TypeVar("R")
P = ParamSpec("P")
# the type of thing that can be passed into `make_request` in the headers list
CustomHeaderType = Tuple[Union[str, bytes], Union[str, bytes]]
CustomHeaderType = tuple[Union[str, bytes], Union[str, bytes]]
# A pre-prepared SQLite DB that is used as a template when creating new SQLite
# DB each test run. This dramatically speeds up test set up when using SQLite.
@@ -172,7 +167,7 @@ class FakeChannel:
return body
@property
def json_list(self) -> List[JsonDict]:
def json_list(self) -> list[JsonDict]:
body = json.loads(self.text_body)
assert isinstance(body, list)
return body
@@ -211,7 +206,7 @@ class FakeChannel:
version: bytes,
code: bytes,
reason: bytes,
headers: Union[Headers, List[Tuple[bytes, bytes]]],
headers: Union[Headers, list[tuple[bytes, bytes]]],
) -> None:
self.result["version"] = version
self.result["code"] = code
@@ -367,7 +362,7 @@ def make_request(
path: Union[bytes, str],
content: Union[bytes, str, JsonDict] = b"",
access_token: Optional[str] = None,
request: Type[Request] = SynapseRequest,
request: type[Request] = SynapseRequest,
shorthand: bool = True,
federation_auth_origin: Optional[bytes] = None,
content_type: Optional[bytes] = None,
@@ -492,10 +487,10 @@ class ThreadedMemoryReactorClock(MemoryReactorClock):
def __init__(self) -> None:
self.threadpool = ThreadPool(self)
self._tcp_callbacks: Dict[Tuple[str, int], Callable] = {}
self._udp: List[udp.Port] = []
self.lookups: Dict[str, str] = {}
self._thread_callbacks: Deque[Callable[..., R]] = deque()
self._tcp_callbacks: dict[tuple[str, int], Callable] = {}
self._udp: list[udp.Port] = []
self.lookups: dict[str, str] = {}
self._thread_callbacks: deque[Callable[..., R]] = deque()
lookups = self.lookups
@@ -622,7 +617,7 @@ class ThreadedMemoryReactorClock(MemoryReactorClock):
port: int,
factory: ClientFactory,
timeout: float = 30,
bindAddress: Optional[Tuple[str, int]] = None,
bindAddress: Optional[tuple[str, int]] = None,
) -> IConnector:
"""Fake L{IReactorTCP.connectTCP}."""
@@ -814,7 +809,7 @@ class ThreadPool:
return d
def get_clock() -> Tuple[ThreadedMemoryReactorClock, Clock]:
def get_clock() -> tuple[ThreadedMemoryReactorClock, Clock]:
# Ignore the linter error since this is an expected usage of creating a `Clock` for
# testing purposes.
reactor = ThreadedMemoryReactorClock()
@@ -1041,7 +1036,7 @@ class FakeTransport:
def connect_client(
reactor: ThreadedMemoryReactorClock, client_id: int
) -> Tuple[IProtocol, AccumulatingProtocol]:
) -> tuple[IProtocol, AccumulatingProtocol]:
"""
Connect a client to a fake TCP transport.
@@ -1068,7 +1063,7 @@ def setup_test_homeserver(
server_name: str = "test",
config: Optional[HomeServerConfig] = None,
reactor: Optional[ISynapseReactor] = None,
homeserver_to_use: Type[HomeServer] = TestHomeServer,
homeserver_to_use: type[HomeServer] = TestHomeServer,
db_txn_limit: Optional[int] = None,
**extra_homeserver_attributes: Any,
) -> HomeServer:
@@ -17,7 +17,6 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import Tuple
from unittest.mock import AsyncMock, Mock
from twisted.internet.testing import MemoryReactor
@@ -363,7 +362,7 @@ class TestResourceLimitsServerNoticesWithRealRooms(unittest.HomeserverTestCase):
self.assertTrue(notice_in_room, "No server notice in room")
def _trigger_notice_and_join(self) -> Tuple[str, str, str]:
def _trigger_notice_and_join(self) -> tuple[str, str, str]:
"""Creates enough active users to hit the MAU limit and trigger a system notice
about it, then joins the system notices room with one of the users created.
+16 -20
View File
@@ -21,13 +21,9 @@
import itertools
from typing import (
Collection,
Dict,
Iterable,
List,
Mapping,
Optional,
Set,
Tuple,
TypeVar,
)
@@ -94,7 +90,7 @@ class FakeEvent:
self.content = content
self.room_id = ROOM_ID
def to_event(self, auth_events: List[str], prev_events: List[str]) -> EventBase:
def to_event(self, auth_events: list[str], prev_events: list[str]) -> EventBase:
"""Given the auth_events and prev_events, convert to a Frozen Event
Args:
@@ -461,9 +457,9 @@ class StateTestCase(unittest.TestCase):
def do_check(
self,
events: List[FakeEvent],
edges: List[List[str]],
expected_state_ids: List[str],
events: list[FakeEvent],
edges: list[list[str]],
expected_state_ids: list[str],
) -> None:
"""Take a list of events and edges and calculate the state of the
graph at END, and asserts it matches `expected_state_ids`
@@ -476,9 +472,9 @@ class StateTestCase(unittest.TestCase):
the keys that haven't changed since START).
"""
# We want to sort the events into topological order for processing.
graph: Dict[str, Set[str]] = {}
graph: dict[str, set[str]] = {}
fake_event_map: Dict[str, FakeEvent] = {}
fake_event_map: dict[str, FakeEvent] = {}
for ev in itertools.chain(INITIAL_EVENTS, events):
graph[ev.node_id] = set()
@@ -491,8 +487,8 @@ class StateTestCase(unittest.TestCase):
for a, b in pairwise(edge_list):
graph[a].add(b)
event_map: Dict[str, EventBase] = {}
state_at_event: Dict[str, StateMap[str]] = {}
event_map: dict[str, EventBase] = {}
state_at_event: dict[str, StateMap[str]] = {}
# We copy the map as the sort consumes the graph
graph_copy = {k: set(v) for k, v in graph.items()}
@@ -568,7 +564,7 @@ class StateTestCase(unittest.TestCase):
class LexicographicalTestCase(unittest.TestCase):
def test_simple(self) -> None:
graph: Dict[str, Set[str]] = {
graph: dict[str, set[str]] = {
"l": {"o"},
"m": {"n", "o"},
"n": {"o"},
@@ -1020,7 +1016,7 @@ class AuthChainDifferenceTestCase(unittest.TestCase):
T = TypeVar("T")
def pairwise(iterable: Iterable[T]) -> Iterable[Tuple[T, T]]:
def pairwise(iterable: Iterable[T]) -> Iterable[tuple[T, T]]:
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
@@ -1029,11 +1025,11 @@ def pairwise(iterable: Iterable[T]) -> Iterable[Tuple[T, T]]:
@attr.s
class TestStateResolutionStore:
event_map: Dict[str, EventBase] = attr.ib()
event_map: dict[str, EventBase] = attr.ib()
def get_events(
self, event_ids: Collection[str], allow_rejected: bool = False
) -> "defer.Deferred[Dict[str, EventBase]]":
) -> "defer.Deferred[dict[str, EventBase]]":
"""Get events from the database
Args:
@@ -1048,7 +1044,7 @@ class TestStateResolutionStore:
{eid: self.event_map[eid] for eid in event_ids if eid in self.event_map}
)
def _get_auth_chain(self, event_ids: Iterable[str]) -> List[str]:
def _get_auth_chain(self, event_ids: Iterable[str]) -> list[str]:
"""Gets the full auth chain for a set of events (including rejected
events).
@@ -1085,9 +1081,9 @@ class TestStateResolutionStore:
def get_auth_chain_difference(
self,
room_id: str,
auth_sets: List[Set[str]],
conflicted_state: Optional[Set[str]],
additional_backwards_reachable_conflicted_events: Optional[Set[str]],
auth_sets: list[set[str]],
conflicted_state: Optional[set[str]],
additional_backwards_reachable_conflicted_events: Optional[set[str]],
) -> "defer.Deferred[StateDifference]":
chains = [frozenset(self._get_auth_chain(a)) for a in auth_sets]
+8 -8
View File
@@ -18,7 +18,7 @@
#
#
import itertools
from typing import Dict, List, Optional, Sequence, Set
from typing import Optional, Sequence
from twisted.internet import defer
from twisted.test.proto_helpers import MemoryReactor
@@ -357,11 +357,11 @@ class StateResV21TestCase(unittest.HomeserverTestCase):
self,
room_id: str,
state_maps: Sequence[StateMap[str]],
event_map: Optional[Dict[str, EventBase]],
event_map: Optional[dict[str, EventBase]],
state_res_store: StateResolutionStoreInterface,
) -> Set[str]:
) -> set[str]:
_, conflicted_state = _seperate(state_maps)
conflicted_set: Optional[Set[str]] = set(
conflicted_set: Optional[set[str]] = set(
itertools.chain.from_iterable(conflicted_state.values())
)
if event_map is None:
@@ -377,7 +377,7 @@ class StateResV21TestCase(unittest.HomeserverTestCase):
def get_resolution_and_verify_expected(
self,
state_maps: Sequence[StateMap[str]],
events: List[EventBase],
events: list[EventBase],
expected: StateMap[str],
) -> None:
room_id = events[0].room_id
@@ -475,9 +475,9 @@ class StateResV21TestCase(unittest.HomeserverTestCase):
event_type: str,
state_key: Optional[str],
sender: str,
content: Dict,
auth_events: List[str],
prev_events: Optional[List[str]] = None,
content: dict,
auth_events: list[str],
prev_events: Optional[list[str]] = None,
room_id: Optional[str] = None,
) -> EventBase:
"""Short-hand for event_from_pdu_json for fields we typically care about.
@@ -18,7 +18,7 @@
# [This file includes modifications made by New Vector Limited]
#
#
from typing import List, Optional, Tuple
from typing import Optional
from twisted.internet.testing import MemoryReactor
@@ -99,7 +99,7 @@ class EndToEndKeyWorkerStoreTestCase(HomeserverTestCase):
def check_timestamp_column(
txn: LoggingTransaction,
) -> List[Tuple[JsonDict, Optional[int]]]:
) -> list[tuple[JsonDict, Optional[int]]]:
"""Fetch all rows for Alice's keys."""
txn.execute(
"""
@@ -20,7 +20,7 @@
#
import json
from contextlib import contextmanager
from typing import Generator, List, Set, Tuple
from typing import Generator
from unittest import mock
from twisted.enterprise.adbapi import ConnectionPool
@@ -60,7 +60,7 @@ class HaveSeenEventsTestCase(unittest.HomeserverTestCase):
self.token = self.login(self.user, "pass")
self.room_id = self.helper.create_room_as(self.user, tok=self.token)
self.event_ids: List[str] = []
self.event_ids: list[str] = []
for i in range(3):
event = self.get_success(
inject_event(
@@ -316,7 +316,7 @@ class GetEventsTestCase(unittest.HomeserverTestCase):
room_id = self.helper.create_room_as(user_id, tok=user_tok)
event_ids: Set[str] = set()
event_ids: set[str] = set()
for i in range(num_events):
event = self.get_success(
inject_event(
@@ -371,7 +371,7 @@ class DatabaseOutageTestCase(unittest.HomeserverTestCase):
)
)
self.event_ids: List[str] = []
self.event_ids: list[str] = []
for idx in range(1, 21): # Stream ordering starts at 1.
event_json = {
"type": f"test {idx}",
@@ -504,7 +504,7 @@ class GetEventCancellationTestCase(unittest.HomeserverTestCase):
def blocking_get_event_calls(
self,
) -> Generator[
Tuple["Deferred[None]", "Deferred[None]", "Deferred[None]"], None, None
tuple["Deferred[None]", "Deferred[None]", "Deferred[None]"], None, None
]:
"""Starts two concurrent `get_event` calls for the same event.

Some files were not shown because too many files have changed in this diff Show More