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

Commit fc35e06

Browse files
authored
Add missing type hints in tests (#14879)
* FIx-up type hints in tests.logging. * Add missing type hints to test_transactions.
1 parent 345576b commit fc35e06

File tree

8 files changed

+75
-42
lines changed

8 files changed

+75
-42
lines changed

changelog.d/14879.misc

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

mypy.ini

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,7 @@ exclude = (?x)
4040
|tests/http/federation/test_matrix_federation_agent.py
4141
|tests/http/federation/test_srv_resolver.py
4242
|tests/http/test_proxyagent.py
43-
|tests/logging/__init__.py
44-
|tests/logging/test_terse_json.py
4543
|tests/module_api/test_api.py
46-
|tests/rest/client/test_transactions.py
4744
|tests/rest/media/v1/test_media_storage.py
4845
|tests/server.py
4946
|tests/test_state.py
@@ -92,6 +89,9 @@ disallow_untyped_defs = True
9289
[mypy-tests.handlers.*]
9390
disallow_untyped_defs = True
9491

92+
[mypy-tests.logging.*]
93+
disallow_untyped_defs = True
94+
9595
[mypy-tests.metrics.*]
9696
disallow_untyped_defs = True
9797

synapse/rest/client/transactions.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
from typing_extensions import ParamSpec
2121

22+
from twisted.internet.defer import Deferred
2223
from twisted.python.failure import Failure
2324
from twisted.web.server import Request
2425

@@ -90,7 +91,7 @@ def fetch_or_execute(
9091
fn: Callable[P, Awaitable[Tuple[int, JsonDict]]],
9192
*args: P.args,
9293
**kwargs: P.kwargs,
93-
) -> Awaitable[Tuple[int, JsonDict]]:
94+
) -> "Deferred[Tuple[int, JsonDict]]":
9495
"""Fetches the response for this transaction, or executes the given function
9596
to produce a response for this transaction.
9697

tests/logging/__init__.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@
1313
# limitations under the License.
1414
import logging
1515

16+
from tests.unittest import TestCase
1617

17-
class LoggerCleanupMixin:
18-
def get_logger(self, handler):
18+
19+
class LoggerCleanupMixin(TestCase):
20+
def get_logger(self, handler: logging.Handler) -> logging.Logger:
1921
"""
2022
Attach a handler to a logger and add clean-ups to remove revert this.
2123
"""

tests/logging/test_opentracing.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def test_overlapping_spans(self) -> None:
153153

154154
scopes = []
155155

156-
async def task(i: int):
156+
async def task(i: int) -> None:
157157
scope = start_active_span(
158158
f"task{i}",
159159
tracer=self._tracer,
@@ -165,7 +165,7 @@ async def task(i: int):
165165
self.assertEqual(self._tracer.active_span, scope.span)
166166
scope.close()
167167

168-
async def root():
168+
async def root() -> None:
169169
with start_active_span("root span", tracer=self._tracer) as root_scope:
170170
self.assertEqual(self._tracer.active_span, root_scope.span)
171171
scopes.append(root_scope)

tests/logging/test_remote_handler.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14-
from twisted.test.proto_helpers import AccumulatingProtocol
14+
from typing import Tuple
15+
16+
from twisted.internet.protocol import Protocol
17+
from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactorClock
1518

1619
from synapse.logging import RemoteHandler
1720

@@ -20,7 +23,9 @@
2023
from tests.unittest import TestCase
2124

2225

23-
def connect_logging_client(reactor, client_id):
26+
def connect_logging_client(
27+
reactor: MemoryReactorClock, client_id: int
28+
) -> Tuple[Protocol, AccumulatingProtocol]:
2429
# This is essentially tests.server.connect_client, but disabling autoflush on
2530
# the client transport. This is necessary to avoid an infinite loop due to
2631
# sending of data via the logging transport causing additional logs to be
@@ -35,10 +40,10 @@ def connect_logging_client(reactor, client_id):
3540

3641

3742
class RemoteHandlerTestCase(LoggerCleanupMixin, TestCase):
38-
def setUp(self):
43+
def setUp(self) -> None:
3944
self.reactor, _ = get_clock()
4045

41-
def test_log_output(self):
46+
def test_log_output(self) -> None:
4247
"""
4348
The remote handler delivers logs over TCP.
4449
"""
@@ -51,6 +56,7 @@ def test_log_output(self):
5156
client, server = connect_logging_client(self.reactor, 0)
5257

5358
# Trigger data being sent
59+
assert isinstance(client.transport, FakeTransport)
5460
client.transport.flush()
5561

5662
# One log message, with a single trailing newline
@@ -61,7 +67,7 @@ def test_log_output(self):
6167
# Ensure the data passed through properly.
6268
self.assertEqual(logs[0], "Hello there, wally!")
6369

64-
def test_log_backpressure_debug(self):
70+
def test_log_backpressure_debug(self) -> None:
6571
"""
6672
When backpressure is hit, DEBUG logs will be shed.
6773
"""
@@ -83,14 +89,15 @@ def test_log_backpressure_debug(self):
8389

8490
# Allow the reconnection
8591
client, server = connect_logging_client(self.reactor, 0)
92+
assert isinstance(client.transport, FakeTransport)
8693
client.transport.flush()
8794

8895
# Only the 7 infos made it through, the debugs were elided
8996
logs = server.data.splitlines()
9097
self.assertEqual(len(logs), 7)
9198
self.assertNotIn(b"debug", server.data)
9299

93-
def test_log_backpressure_info(self):
100+
def test_log_backpressure_info(self) -> None:
94101
"""
95102
When backpressure is hit, DEBUG and INFO logs will be shed.
96103
"""
@@ -116,6 +123,7 @@ def test_log_backpressure_info(self):
116123

117124
# Allow the reconnection
118125
client, server = connect_logging_client(self.reactor, 0)
126+
assert isinstance(client.transport, FakeTransport)
119127
client.transport.flush()
120128

121129
# The 10 warnings made it through, the debugs and infos were elided
@@ -124,7 +132,7 @@ def test_log_backpressure_info(self):
124132
self.assertNotIn(b"debug", server.data)
125133
self.assertNotIn(b"info", server.data)
126134

127-
def test_log_backpressure_cut_middle(self):
135+
def test_log_backpressure_cut_middle(self) -> None:
128136
"""
129137
When backpressure is hit, and no more DEBUG and INFOs cannot be culled,
130138
it will cut the middle messages out.
@@ -140,6 +148,7 @@ def test_log_backpressure_cut_middle(self):
140148

141149
# Allow the reconnection
142150
client, server = connect_logging_client(self.reactor, 0)
151+
assert isinstance(client.transport, FakeTransport)
143152
client.transport.flush()
144153

145154
# The first five and last five warnings made it through, the debugs and
@@ -151,7 +160,7 @@ def test_log_backpressure_cut_middle(self):
151160
logs,
152161
)
153162

154-
def test_cancel_connection(self):
163+
def test_cancel_connection(self) -> None:
155164
"""
156165
Gracefully handle the connection being cancelled.
157166
"""

tests/logging/test_terse_json.py

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,32 +14,36 @@
1414
import json
1515
import logging
1616
from io import BytesIO, StringIO
17+
from typing import cast
1718
from unittest.mock import Mock, patch
1819

20+
from twisted.web.http import HTTPChannel
1921
from twisted.web.server import Request
2022

2123
from synapse.http.site import SynapseRequest
2224
from synapse.logging._terse_json import JsonFormatter, TerseJsonFormatter
2325
from synapse.logging.context import LoggingContext, LoggingContextFilter
26+
from synapse.types import JsonDict
2427

2528
from tests.logging import LoggerCleanupMixin
26-
from tests.server import FakeChannel
29+
from tests.server import FakeChannel, get_clock
2730
from tests.unittest import TestCase
2831

2932

3033
class TerseJsonTestCase(LoggerCleanupMixin, TestCase):
31-
def setUp(self):
34+
def setUp(self) -> None:
3235
self.output = StringIO()
36+
self.reactor, _ = get_clock()
3337

34-
def get_log_line(self):
38+
def get_log_line(self) -> JsonDict:
3539
# One log message, with a single trailing newline.
3640
data = self.output.getvalue()
3741
logs = data.splitlines()
3842
self.assertEqual(len(logs), 1)
3943
self.assertEqual(data.count("\n"), 1)
4044
return json.loads(logs[0])
4145

42-
def test_terse_json_output(self):
46+
def test_terse_json_output(self) -> None:
4347
"""
4448
The Terse JSON formatter converts log messages to JSON.
4549
"""
@@ -61,7 +65,7 @@ def test_terse_json_output(self):
6165
self.assertCountEqual(log.keys(), expected_log_keys)
6266
self.assertEqual(log["log"], "Hello there, wally!")
6367

64-
def test_extra_data(self):
68+
def test_extra_data(self) -> None:
6569
"""
6670
Additional information can be included in the structured logging.
6771
"""
@@ -93,7 +97,7 @@ def test_extra_data(self):
9397
self.assertEqual(log["int"], 3)
9498
self.assertIs(log["bool"], True)
9599

96-
def test_json_output(self):
100+
def test_json_output(self) -> None:
97101
"""
98102
The Terse JSON formatter converts log messages to JSON.
99103
"""
@@ -114,7 +118,7 @@ def test_json_output(self):
114118
self.assertCountEqual(log.keys(), expected_log_keys)
115119
self.assertEqual(log["log"], "Hello there, wally!")
116120

117-
def test_with_context(self):
121+
def test_with_context(self) -> None:
118122
"""
119123
The logging context should be added to the JSON response.
120124
"""
@@ -139,7 +143,7 @@ def test_with_context(self):
139143
self.assertEqual(log["log"], "Hello there, wally!")
140144
self.assertEqual(log["request"], "name")
141145

142-
def test_with_request_context(self):
146+
def test_with_request_context(self) -> None:
143147
"""
144148
Information from the logging context request should be added to the JSON response.
145149
"""
@@ -154,11 +158,13 @@ def test_with_request_context(self):
154158
site.server_version_string = "Server v1"
155159
site.reactor = Mock()
156160
site.experimental_cors_msc3886 = False
157-
request = SynapseRequest(FakeChannel(site, None), site)
161+
request = SynapseRequest(
162+
cast(HTTPChannel, FakeChannel(site, self.reactor)), site
163+
)
158164
# Call requestReceived to finish instantiating the object.
159165
request.content = BytesIO()
160-
# Partially skip some of the internal processing of SynapseRequest.
161-
request._started_processing = Mock()
166+
# Partially skip some internal processing of SynapseRequest.
167+
request._started_processing = Mock() # type: ignore[assignment]
162168
request.request_metrics = Mock(spec=["name"])
163169
with patch.object(Request, "render"):
164170
request.requestReceived(b"POST", b"/_matrix/client/versions", b"1.1")
@@ -200,7 +206,7 @@ def test_with_request_context(self):
200206
self.assertEqual(log["protocol"], "1.1")
201207
self.assertEqual(log["user_agent"], "")
202208

203-
def test_with_exception(self):
209+
def test_with_exception(self) -> None:
204210
"""
205211
The logging exception type & value should be added to the JSON response.
206212
"""

0 commit comments

Comments
 (0)