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

Add type hints to tests/rest #12146

Merged
merged 3 commits into from
Mar 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/12146.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add type hints to `tests/rest`.
7 changes: 1 addition & 6 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,6 @@ exclude = (?x)
|tests/push/test_presentable_names.py
|tests/push/test_push_rule_evaluator.py
|tests/rest/client/test_transactions.py
|tests/rest/key/v2/test_remote_key_resource.py
|tests/rest/media/v1/test_base.py
|tests/rest/media/v1/test_media_storage.py
|tests/rest/media/v1/test_url_preview.py
|tests/scripts/test_new_matrix_user.py
Expand Down Expand Up @@ -254,10 +252,7 @@ disallow_untyped_defs = True
[mypy-tests.storage.test_user_directory]
disallow_untyped_defs = True

[mypy-tests.rest.admin.*]
disallow_untyped_defs = True

[mypy-tests.rest.client.*]
[mypy-tests.rest.*]
disallow_untyped_defs = True

[mypy-tests.federation.transport.test_client]
Expand Down
44 changes: 29 additions & 15 deletions tests/rest/key/v2/test_remote_key_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,24 @@
# limitations under the License.
import urllib.parse
from io import BytesIO, StringIO
from typing import Any, Dict, Optional, Union
from unittest.mock import Mock

import signedjson.key
from canonicaljson import encode_canonical_json
from nacl.signing import SigningKey
from signedjson.sign import sign_json
from signedjson.types import SigningKey

from twisted.web.resource import NoResource
from twisted.test.proto_helpers import MemoryReactor
from twisted.web.resource import NoResource, Resource

from synapse.crypto.keyring import PerspectivesKeyFetcher
from synapse.http.site import SynapseRequest
from synapse.rest.key.v2 import KeyApiV2Resource
from synapse.server import HomeServer
from synapse.storage.keys import FetchKeyResult
from synapse.types import JsonDict
from synapse.util import Clock
from synapse.util.httpresourcetree import create_resource_tree
from synapse.util.stringutils import random_string

Expand All @@ -35,11 +40,11 @@


class BaseRemoteKeyResourceTestCase(unittest.HomeserverTestCase):
def make_homeserver(self, reactor, clock):
def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
self.http_client = Mock()
return self.setup_test_homeserver(federation_http_client=self.http_client)

def create_test_resource(self):
def create_test_resource(self) -> Resource:
return create_resource_tree(
{"/_matrix/key/v2": KeyApiV2Resource(self.hs)}, root_resource=NoResource()
)
Expand All @@ -51,7 +56,12 @@ def expect_outgoing_key_request(
Tell the mock http client to expect an outgoing GET request for the given key
"""

async def get_json(destination, path, ignore_backoff=False, **kwargs):
async def get_json(
destination: str,
path: str,
ignore_backoff: bool = False,
**kwargs: Any,
) -> Union[JsonDict, list]:
self.assertTrue(ignore_backoff)
self.assertEqual(destination, server_name)
key_id = "%s:%s" % (signing_key.alg, signing_key.version)
Expand Down Expand Up @@ -84,7 +94,8 @@ def make_notary_request(self, server_name: str, key_id: str) -> dict:
Checks that the response is a 200 and returns the decoded json body.
"""
channel = FakeChannel(self.site, self.reactor)
req = SynapseRequest(channel, self.site)
# channel is a `FakeChannel` but `HTTPChannel` is expected
req = SynapseRequest(channel, self.site) # type: ignore[arg-type]
req.content = BytesIO(b"")
req.requestReceived(
b"GET",
Expand All @@ -97,7 +108,7 @@ def make_notary_request(self, server_name: str, key_id: str) -> dict:
resp = channel.json_body
return resp

def test_get_key(self):
def test_get_key(self) -> None:
"""Fetch a remote key"""
SERVER_NAME = "remote.server"
testkey = signedjson.key.generate_signing_key("ver1")
Expand All @@ -114,7 +125,7 @@ def test_get_key(self):
self.assertIn(SERVER_NAME, keys[0]["signatures"])
self.assertIn(self.hs.hostname, keys[0]["signatures"])

def test_get_own_key(self):
def test_get_own_key(self) -> None:
"""Fetch our own key"""
testkey = signedjson.key.generate_signing_key("ver1")
self.expect_outgoing_key_request(self.hs.hostname, testkey)
Expand All @@ -141,7 +152,7 @@ class EndToEndPerspectivesTests(BaseRemoteKeyResourceTestCase):
endpoint, to check that the two implementations are compatible.
"""

def default_config(self):
def default_config(self) -> Dict[str, Any]:
config = super().default_config()

# replace the signing key with our own
Expand All @@ -152,7 +163,7 @@ def default_config(self):

return config

def prepare(self, reactor, clock, homeserver):
def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
# make a second homeserver, configured to use the first one as a key notary
self.http_client2 = Mock()
config = default_config(name="keyclient")
Expand All @@ -175,15 +186,18 @@ def prepare(self, reactor, clock, homeserver):

# wire up outbound POST /key/v2/query requests from hs2 so that they
# will be forwarded to hs1
async def post_json(destination, path, data):
async def post_json(
destination: str, path: str, data: Optional[JsonDict] = None
) -> Union[JsonDict, list]:
self.assertEqual(destination, self.hs.hostname)
self.assertEqual(
path,
"/_matrix/key/v2/query",
)

channel = FakeChannel(self.site, self.reactor)
req = SynapseRequest(channel, self.site)
# channel is a `FakeChannel` but `HTTPChannel` is expected
req = SynapseRequest(channel, self.site) # type: ignore[arg-type]
req.content = BytesIO(encode_canonical_json(data))

req.requestReceived(
Expand All @@ -198,7 +212,7 @@ async def post_json(destination, path, data):

self.http_client2.post_json.side_effect = post_json

def test_get_key(self):
def test_get_key(self) -> None:
"""Fetch a key belonging to a random server"""
# make up a key to be fetched.
testkey = signedjson.key.generate_signing_key("abc")
Expand All @@ -218,7 +232,7 @@ def test_get_key(self):
signedjson.key.encode_verify_key_base64(testkey.verify_key),
)

def test_get_notary_key(self):
def test_get_notary_key(self) -> None:
"""Fetch a key belonging to the notary server"""
# make up a key to be fetched. We randomise the keyid to try to get it to
# appear before the key server signing key sometimes (otherwise we bail out
Expand All @@ -240,7 +254,7 @@ def test_get_notary_key(self):
signedjson.key.encode_verify_key_base64(testkey.verify_key),
)

def test_get_notary_keyserver_key(self):
def test_get_notary_keyserver_key(self) -> None:
"""Fetch the notary's keyserver key"""
# we expect hs1 to make a regular key request to itself
self.expect_outgoing_key_request(self.hs.hostname, self.hs_signing_key)
Expand Down
4 changes: 2 additions & 2 deletions tests/rest/media/v1/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ class GetFileNameFromHeadersTests(unittest.TestCase):
b"inline; filename*=utf-8''foo%C2%A3bar": "foo£bar",
}

def tests(self):
def tests(self) -> None:
for hdr, expected in self.TEST_CASES.items():
res = get_filename_from_headers({b"Content-Disposition": [hdr]})
self.assertEqual(
res,
expected,
"expected output for %s to be %s but was %s" % (hdr, expected, res),
f"expected output for {hdr!r} to be {expected} but was {res}",
)
48 changes: 24 additions & 24 deletions tests/rest/media/v1/test_filepath.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@


class MediaFilePathsTestCase(unittest.TestCase):
def setUp(self):
def setUp(self) -> None:
super().setUp()

self.filepaths = MediaFilePaths("/media_store")

def test_local_media_filepath(self):
def test_local_media_filepath(self) -> None:
"""Test local media paths"""
self.assertEqual(
self.filepaths.local_media_filepath_rel("GerZNDnDZVjsOtardLuwfIBg"),
Expand All @@ -37,7 +37,7 @@ def test_local_media_filepath(self):
"/media_store/local_content/Ge/rZ/NDnDZVjsOtardLuwfIBg",
)

def test_local_media_thumbnail(self):
def test_local_media_thumbnail(self) -> None:
"""Test local media thumbnail paths"""
self.assertEqual(
self.filepaths.local_media_thumbnail_rel(
Expand All @@ -52,14 +52,14 @@ def test_local_media_thumbnail(self):
"/media_store/local_thumbnails/Ge/rZ/NDnDZVjsOtardLuwfIBg/800-600-image-jpeg-scale",
)

def test_local_media_thumbnail_dir(self):
def test_local_media_thumbnail_dir(self) -> None:
"""Test local media thumbnail directory paths"""
self.assertEqual(
self.filepaths.local_media_thumbnail_dir("GerZNDnDZVjsOtardLuwfIBg"),
"/media_store/local_thumbnails/Ge/rZ/NDnDZVjsOtardLuwfIBg",
)

def test_remote_media_filepath(self):
def test_remote_media_filepath(self) -> None:
"""Test remote media paths"""
self.assertEqual(
self.filepaths.remote_media_filepath_rel(
Expand All @@ -74,7 +74,7 @@ def test_remote_media_filepath(self):
"/media_store/remote_content/example.com/Ge/rZ/NDnDZVjsOtardLuwfIBg",
)

def test_remote_media_thumbnail(self):
def test_remote_media_thumbnail(self) -> None:
"""Test remote media thumbnail paths"""
self.assertEqual(
self.filepaths.remote_media_thumbnail_rel(
Expand All @@ -99,7 +99,7 @@ def test_remote_media_thumbnail(self):
"/media_store/remote_thumbnail/example.com/Ge/rZ/NDnDZVjsOtardLuwfIBg/800-600-image-jpeg-scale",
)

def test_remote_media_thumbnail_legacy(self):
def test_remote_media_thumbnail_legacy(self) -> None:
"""Test old-style remote media thumbnail paths"""
self.assertEqual(
self.filepaths.remote_media_thumbnail_rel_legacy(
Expand All @@ -108,7 +108,7 @@ def test_remote_media_thumbnail_legacy(self):
"remote_thumbnail/example.com/Ge/rZ/NDnDZVjsOtardLuwfIBg/800-600-image-jpeg",
)

def test_remote_media_thumbnail_dir(self):
def test_remote_media_thumbnail_dir(self) -> None:
"""Test remote media thumbnail directory paths"""
self.assertEqual(
self.filepaths.remote_media_thumbnail_dir(
Expand All @@ -117,7 +117,7 @@ def test_remote_media_thumbnail_dir(self):
"/media_store/remote_thumbnail/example.com/Ge/rZ/NDnDZVjsOtardLuwfIBg",
)

def test_url_cache_filepath(self):
def test_url_cache_filepath(self) -> None:
"""Test URL cache paths"""
self.assertEqual(
self.filepaths.url_cache_filepath_rel("2020-01-02_GerZNDnDZVjsOtar"),
Expand All @@ -128,7 +128,7 @@ def test_url_cache_filepath(self):
"/media_store/url_cache/2020-01-02/GerZNDnDZVjsOtar",
)

def test_url_cache_filepath_legacy(self):
def test_url_cache_filepath_legacy(self) -> None:
"""Test old-style URL cache paths"""
self.assertEqual(
self.filepaths.url_cache_filepath_rel("GerZNDnDZVjsOtardLuwfIBg"),
Expand All @@ -139,7 +139,7 @@ def test_url_cache_filepath_legacy(self):
"/media_store/url_cache/Ge/rZ/NDnDZVjsOtardLuwfIBg",
)

def test_url_cache_filepath_dirs_to_delete(self):
def test_url_cache_filepath_dirs_to_delete(self) -> None:
"""Test URL cache cleanup paths"""
self.assertEqual(
self.filepaths.url_cache_filepath_dirs_to_delete(
Expand All @@ -148,7 +148,7 @@ def test_url_cache_filepath_dirs_to_delete(self):
["/media_store/url_cache/2020-01-02"],
)

def test_url_cache_filepath_dirs_to_delete_legacy(self):
def test_url_cache_filepath_dirs_to_delete_legacy(self) -> None:
"""Test old-style URL cache cleanup paths"""
self.assertEqual(
self.filepaths.url_cache_filepath_dirs_to_delete(
Expand All @@ -160,7 +160,7 @@ def test_url_cache_filepath_dirs_to_delete_legacy(self):
],
)

def test_url_cache_thumbnail(self):
def test_url_cache_thumbnail(self) -> None:
"""Test URL cache thumbnail paths"""
self.assertEqual(
self.filepaths.url_cache_thumbnail_rel(
Expand All @@ -175,7 +175,7 @@ def test_url_cache_thumbnail(self):
"/media_store/url_cache_thumbnails/2020-01-02/GerZNDnDZVjsOtar/800-600-image-jpeg-scale",
)

def test_url_cache_thumbnail_legacy(self):
def test_url_cache_thumbnail_legacy(self) -> None:
"""Test old-style URL cache thumbnail paths"""
self.assertEqual(
self.filepaths.url_cache_thumbnail_rel(
Expand All @@ -190,7 +190,7 @@ def test_url_cache_thumbnail_legacy(self):
"/media_store/url_cache_thumbnails/Ge/rZ/NDnDZVjsOtardLuwfIBg/800-600-image-jpeg-scale",
)

def test_url_cache_thumbnail_directory(self):
def test_url_cache_thumbnail_directory(self) -> None:
"""Test URL cache thumbnail directory paths"""
self.assertEqual(
self.filepaths.url_cache_thumbnail_directory_rel(
Expand All @@ -203,7 +203,7 @@ def test_url_cache_thumbnail_directory(self):
"/media_store/url_cache_thumbnails/2020-01-02/GerZNDnDZVjsOtar",
)

def test_url_cache_thumbnail_directory_legacy(self):
def test_url_cache_thumbnail_directory_legacy(self) -> None:
"""Test old-style URL cache thumbnail directory paths"""
self.assertEqual(
self.filepaths.url_cache_thumbnail_directory_rel(
Expand All @@ -216,7 +216,7 @@ def test_url_cache_thumbnail_directory_legacy(self):
"/media_store/url_cache_thumbnails/Ge/rZ/NDnDZVjsOtardLuwfIBg",
)

def test_url_cache_thumbnail_dirs_to_delete(self):
def test_url_cache_thumbnail_dirs_to_delete(self) -> None:
"""Test URL cache thumbnail cleanup paths"""
self.assertEqual(
self.filepaths.url_cache_thumbnail_dirs_to_delete(
Expand All @@ -228,7 +228,7 @@ def test_url_cache_thumbnail_dirs_to_delete(self):
],
)

def test_url_cache_thumbnail_dirs_to_delete_legacy(self):
def test_url_cache_thumbnail_dirs_to_delete_legacy(self) -> None:
"""Test old-style URL cache thumbnail cleanup paths"""
self.assertEqual(
self.filepaths.url_cache_thumbnail_dirs_to_delete(
Expand All @@ -241,7 +241,7 @@ def test_url_cache_thumbnail_dirs_to_delete_legacy(self):
],
)

def test_server_name_validation(self):
def test_server_name_validation(self) -> None:
"""Test validation of server names"""
self._test_path_validation(
[
Expand Down Expand Up @@ -274,7 +274,7 @@ def test_server_name_validation(self):
],
)

def test_file_id_validation(self):
def test_file_id_validation(self) -> None:
"""Test validation of local, remote and legacy URL cache file / media IDs"""
# File / media IDs get split into three parts to form paths, consisting of the
# first two characters, next two characters and rest of the ID.
Expand Down Expand Up @@ -357,7 +357,7 @@ def test_file_id_validation(self):
invalid_values=invalid_file_ids,
)

def test_url_cache_media_id_validation(self):
def test_url_cache_media_id_validation(self) -> None:
"""Test validation of URL cache media IDs"""
self._test_path_validation(
[
Expand Down Expand Up @@ -387,7 +387,7 @@ def test_url_cache_media_id_validation(self):
],
)

def test_content_type_validation(self):
def test_content_type_validation(self) -> None:
"""Test validation of thumbnail content types"""
self._test_path_validation(
[
Expand All @@ -410,7 +410,7 @@ def test_content_type_validation(self):
],
)

def test_thumbnail_method_validation(self):
def test_thumbnail_method_validation(self) -> None:
"""Test validation of thumbnail methods"""
self._test_path_validation(
[
Expand Down Expand Up @@ -440,7 +440,7 @@ def _test_path_validation(
parameter: str,
valid_values: Iterable[str],
invalid_values: Iterable[str],
):
) -> None:
"""Test that the specified methods validate the named parameter as expected

Args:
Expand Down
Loading