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

Commit 2dff930

Browse files
author
David Robertson
authored
Typecheck tests.rest.media.v1.test_media_storage (#15008)
* Fix MediaStorage type hint * Typecheck tests.rest.media.v1.test_media_storage * Changelog * Remove assert and make the comment succinct * Fix syntax for olddeps
1 parent 4dd2b61 commit 2dff930

File tree

4 files changed

+35
-23
lines changed

4 files changed

+35
-23
lines changed

changelog.d/15008.misc

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

mypy.ini

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ exclude = (?x)
3333
|synapse/storage/schema/
3434

3535
|tests/module_api/test_api.py
36-
|tests/rest/media/v1/test_media_storage.py
3736
|tests/server.py
3837
)$
3938

synapse/rest/media/v1/media_storage.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,9 @@
4646
from .filepath import MediaFilePaths
4747

4848
if TYPE_CHECKING:
49+
from synapse.rest.media.v1.storage_provider import StorageProvider
4950
from synapse.server import HomeServer
5051

51-
from .storage_provider import StorageProviderWrapper
52-
5352
logger = logging.getLogger(__name__)
5453

5554

@@ -68,7 +67,7 @@ def __init__(
6867
hs: "HomeServer",
6968
local_media_directory: str,
7069
filepaths: MediaFilePaths,
71-
storage_providers: Sequence["StorageProviderWrapper"],
70+
storage_providers: Sequence["StorageProvider"],
7271
):
7372
self.hs = hs
7473
self.reactor = hs.get_reactor()
@@ -360,7 +359,7 @@ class ReadableFileWrapper:
360359
clock: Clock
361360
path: str
362361

363-
async def write_chunks_to(self, callback: Callable[[bytes], None]) -> None:
362+
async def write_chunks_to(self, callback: Callable[[bytes], object]) -> None:
364363
"""Reads the file in chunks and calls the callback with each chunk."""
365364

366365
with open(self.path, "rb") as file:

tests/rest/media/v1/test_media_storage.py

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import tempfile
1717
from binascii import unhexlify
1818
from io import BytesIO
19-
from typing import Any, BinaryIO, Dict, List, Optional, Union
19+
from typing import Any, BinaryIO, ClassVar, Dict, List, Optional, Tuple, Union
2020
from unittest.mock import Mock
2121
from urllib import parse
2222

@@ -32,6 +32,7 @@
3232
from synapse.api.errors import Codes
3333
from synapse.events import EventBase
3434
from synapse.events.spamcheck import load_legacy_spam_checkers
35+
from synapse.http.types import QueryParams
3536
from synapse.logging.context import make_deferred_yieldable
3637
from synapse.module_api import ModuleApi
3738
from synapse.rest import admin
@@ -41,7 +42,7 @@
4142
from synapse.rest.media.v1.media_storage import MediaStorage, ReadableFileWrapper
4243
from synapse.rest.media.v1.storage_provider import FileStorageProviderBackend
4344
from synapse.server import HomeServer
44-
from synapse.types import RoomAlias
45+
from synapse.types import JsonDict, RoomAlias
4546
from synapse.util import Clock
4647

4748
from tests import unittest
@@ -201,36 +202,46 @@ class _TestImage:
201202
],
202203
)
203204
class MediaRepoTests(unittest.HomeserverTestCase):
204-
205+
test_image: ClassVar[_TestImage]
205206
hijack_auth = True
206207
user_id = "@test:user"
207208

208209
def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
209210

210-
self.fetches = []
211+
self.fetches: List[
212+
Tuple[
213+
"Deferred[Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]]]]]",
214+
str,
215+
str,
216+
Optional[QueryParams],
217+
]
218+
] = []
211219

212220
def get_file(
213221
destination: str,
214222
path: str,
215223
output_stream: BinaryIO,
216-
args: Optional[Dict[str, Union[str, List[str]]]] = None,
224+
args: Optional[QueryParams] = None,
225+
retry_on_dns_fail: bool = True,
217226
max_size: Optional[int] = None,
218-
) -> Deferred:
219-
"""
220-
Returns tuple[int,dict,str,int] of file length, response headers,
221-
absolute URI, and response code.
222-
"""
227+
ignore_backoff: bool = False,
228+
) -> "Deferred[Tuple[int, Dict[bytes, List[bytes]]]]":
229+
"""A mock for MatrixFederationHttpClient.get_file."""
223230

224-
def write_to(r):
231+
def write_to(
232+
r: Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]]]]
233+
) -> Tuple[int, Dict[bytes, List[bytes]]]:
225234
data, response = r
226235
output_stream.write(data)
227236
return response
228237

229-
d = Deferred()
230-
d.addCallback(write_to)
238+
d: Deferred[Tuple[bytes, Tuple[int, Dict[bytes, List[bytes]]]]] = Deferred()
231239
self.fetches.append((d, destination, path, args))
232-
return make_deferred_yieldable(d)
240+
# Note that this callback changes the value held by d.
241+
d_after_callback = d.addCallback(write_to)
242+
return make_deferred_yieldable(d_after_callback)
233243

244+
# Mock out the homeserver's MatrixFederationHttpClient
234245
client = Mock()
235246
client.get_file = get_file
236247

@@ -461,6 +472,7 @@ def test_thumbnail_repeated_thumbnail(self) -> None:
461472
# Synapse should regenerate missing thumbnails.
462473
origin, media_id = self.media_id.split("/")
463474
info = self.get_success(self.store.get_cached_remote_media(origin, media_id))
475+
assert info is not None
464476
file_id = info["filesystem_id"]
465477

466478
thumbnail_dir = self.media_repo.filepaths.remote_media_thumbnail_dir(
@@ -581,18 +593,18 @@ def test_same_quality(self, method: str, desired_size: int) -> None:
581593
"thumbnail_method": method,
582594
"thumbnail_type": self.test_image.content_type,
583595
"thumbnail_length": 256,
584-
"filesystem_id": f"thumbnail1{self.test_image.extension}",
596+
"filesystem_id": f"thumbnail1{self.test_image.extension.decode()}",
585597
},
586598
{
587599
"thumbnail_width": 32,
588600
"thumbnail_height": 32,
589601
"thumbnail_method": method,
590602
"thumbnail_type": self.test_image.content_type,
591603
"thumbnail_length": 256,
592-
"filesystem_id": f"thumbnail2{self.test_image.extension}",
604+
"filesystem_id": f"thumbnail2{self.test_image.extension.decode()}",
593605
},
594606
],
595-
file_id=f"image{self.test_image.extension}",
607+
file_id=f"image{self.test_image.extension.decode()}",
596608
url_cache=None,
597609
server_name=None,
598610
)
@@ -637,6 +649,7 @@ def __init__(self, config: Dict[str, Any], api: ModuleApi) -> None:
637649
self.config = config
638650
self.api = api
639651

652+
@staticmethod
640653
def parse_config(config: Dict[str, Any]) -> Dict[str, Any]:
641654
return config
642655

@@ -748,7 +761,7 @@ def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
748761

749762
async def check_media_file_for_spam(
750763
self, file_wrapper: ReadableFileWrapper, file_info: FileInfo
751-
) -> Union[Codes, Literal["NOT_SPAM"]]:
764+
) -> Union[Codes, Literal["NOT_SPAM"], Tuple[Codes, JsonDict]]:
752765
buf = BytesIO()
753766
await file_wrapper.write_chunks_to(buf.write)
754767

0 commit comments

Comments
 (0)