Skip to content

Commit 4a503d8

Browse files
authored
Change ruff rules (#2251)
* Change ruff rules * fix type checker
1 parent 0d4747e commit 4a503d8

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+358
-815
lines changed

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ path = "uvicorn/__init__.py"
6161
include = ["/uvicorn"]
6262

6363
[tool.ruff]
64-
select = ["E", "F", "I"]
64+
line-length = 120
65+
select = ["E", "F", "I", "FA", "UP"]
6566
ignore = ["B904", "B028"]
6667

6768
[tool.ruff.lint.isort]

tests/conftest.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import contextlib
24
import importlib.util
35
import os
@@ -9,6 +11,7 @@
911
from tempfile import TemporaryDirectory
1012
from threading import Thread
1113
from time import sleep
14+
from typing import Any
1215
from uuid import uuid4
1316

1417
import pytest
@@ -38,14 +41,14 @@
3841

3942

4043
@pytest.fixture
41-
def tls_certificate_authority() -> "trustme.CA":
44+
def tls_certificate_authority() -> trustme.CA:
4245
if not HAVE_TRUSTME:
4346
pytest.skip("trustme not installed") # pragma: no cover
4447
return trustme.CA()
4548

4649

4750
@pytest.fixture
48-
def tls_certificate(tls_certificate_authority: "trustme.CA") -> "trustme.LeafCert":
51+
def tls_certificate(tls_certificate_authority: trustme.CA) -> trustme.LeafCert:
4952
return tls_certificate_authority.issue_cert(
5053
"localhost",
5154
"127.0.0.1",
@@ -54,13 +57,13 @@ def tls_certificate(tls_certificate_authority: "trustme.CA") -> "trustme.LeafCer
5457

5558

5659
@pytest.fixture
57-
def tls_ca_certificate_pem_path(tls_certificate_authority: "trustme.CA"):
60+
def tls_ca_certificate_pem_path(tls_certificate_authority: trustme.CA):
5861
with tls_certificate_authority.cert_pem.tempfile() as ca_cert_pem:
5962
yield ca_cert_pem
6063

6164

6265
@pytest.fixture
63-
def tls_ca_certificate_private_key_path(tls_certificate_authority: "trustme.CA"):
66+
def tls_ca_certificate_private_key_path(tls_certificate_authority: trustme.CA):
6467
with tls_certificate_authority.private_key_pem.tempfile() as private_key:
6568
yield private_key
6669

@@ -82,25 +85,25 @@ def tls_certificate_private_key_encrypted_path(tls_certificate):
8285

8386

8487
@pytest.fixture
85-
def tls_certificate_private_key_path(tls_certificate: "trustme.CA"):
88+
def tls_certificate_private_key_path(tls_certificate: trustme.CA):
8689
with tls_certificate.private_key_pem.tempfile() as private_key:
8790
yield private_key
8891

8992

9093
@pytest.fixture
91-
def tls_certificate_key_and_chain_path(tls_certificate: "trustme.LeafCert"):
94+
def tls_certificate_key_and_chain_path(tls_certificate: trustme.LeafCert):
9295
with tls_certificate.private_key_and_cert_chain_pem.tempfile() as cert_pem:
9396
yield cert_pem
9497

9598

9699
@pytest.fixture
97-
def tls_certificate_server_cert_path(tls_certificate: "trustme.LeafCert"):
100+
def tls_certificate_server_cert_path(tls_certificate: trustme.LeafCert):
98101
with tls_certificate.cert_chain_pems[0].tempfile() as cert_pem:
99102
yield cert_pem
100103

101104

102105
@pytest.fixture
103-
def tls_ca_ssl_context(tls_certificate_authority: "trustme.CA") -> ssl.SSLContext:
106+
def tls_ca_ssl_context(tls_certificate_authority: trustme.CA) -> ssl.SSLContext:
104107
ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
105108
tls_certificate_authority.configure_trust(ssl_ctx)
106109
return ssl_ctx
@@ -172,7 +175,7 @@ def anyio_backend() -> str:
172175

173176

174177
@pytest.fixture(scope="function")
175-
def logging_config() -> dict:
178+
def logging_config() -> dict[str, Any]:
176179
return deepcopy(LOGGING_CONFIG)
177180

178181

@@ -250,9 +253,7 @@ def unused_tcp_port() -> int:
250253
params=[
251254
pytest.param(
252255
"uvicorn.protocols.websockets.wsproto_impl:WSProtocol",
253-
marks=pytest.mark.skipif(
254-
not importlib.util.find_spec("wsproto"), reason="wsproto not installed."
255-
),
256+
marks=pytest.mark.skipif(not importlib.util.find_spec("wsproto"), reason="wsproto not installed."),
256257
id="wsproto",
257258
),
258259
pytest.param(

tests/middleware/test_logging.py

Lines changed: 12 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,7 @@ async def test_trace_logging(caplog, logging_config, unused_tcp_port: int):
6060
async with httpx.AsyncClient() as client:
6161
response = await client.get(f"http://127.0.0.1:{unused_tcp_port}")
6262
assert response.status_code == 204
63-
messages = [
64-
record.message for record in caplog.records if record.name == "uvicorn.asgi"
65-
]
63+
messages = [record.message for record in caplog.records if record.name == "uvicorn.asgi"]
6664
assert "ASGI [1] Started scope=" in messages.pop(0)
6765
assert "ASGI [1] Raised exception" in messages.pop(0)
6866
assert "ASGI [2] Started scope=" in messages.pop(0)
@@ -72,9 +70,7 @@ async def test_trace_logging(caplog, logging_config, unused_tcp_port: int):
7270

7371

7472
@pytest.mark.anyio
75-
async def test_trace_logging_on_http_protocol(
76-
http_protocol_cls, caplog, logging_config, unused_tcp_port: int
77-
):
73+
async def test_trace_logging_on_http_protocol(http_protocol_cls, caplog, logging_config, unused_tcp_port: int):
7874
config = Config(
7975
app=app,
8076
log_level="trace",
@@ -87,11 +83,7 @@ async def test_trace_logging_on_http_protocol(
8783
async with httpx.AsyncClient() as client:
8884
response = await client.get(f"http://127.0.0.1:{unused_tcp_port}")
8985
assert response.status_code == 204
90-
messages = [
91-
record.message
92-
for record in caplog.records
93-
if record.name == "uvicorn.error"
94-
]
86+
messages = [record.message for record in caplog.records if record.name == "uvicorn.error"]
9587
assert any(" - HTTP connection made" in message for message in messages)
9688
assert any(" - HTTP connection lost" in message for message in messages)
9789

@@ -127,11 +119,7 @@ async def open_connection(url):
127119
async with run_server(config):
128120
is_open = await open_connection(f"ws://127.0.0.1:{unused_tcp_port}")
129121
assert is_open
130-
messages = [
131-
record.message
132-
for record in caplog.records
133-
if record.name == "uvicorn.error"
134-
]
122+
messages = [record.message for record in caplog.records if record.name == "uvicorn.error"]
135123
assert any(" - Upgrading to WebSocket" in message for message in messages)
136124
assert any(" - WebSocket connection made" in message for message in messages)
137125
assert any(" - WebSocket connection lost" in message for message in messages)
@@ -140,39 +128,27 @@ async def open_connection(url):
140128
@pytest.mark.anyio
141129
@pytest.mark.parametrize("use_colors", [(True), (False), (None)])
142130
async def test_access_logging(use_colors, caplog, logging_config, unused_tcp_port: int):
143-
config = Config(
144-
app=app, use_colors=use_colors, log_config=logging_config, port=unused_tcp_port
145-
)
131+
config = Config(app=app, use_colors=use_colors, log_config=logging_config, port=unused_tcp_port)
146132
with caplog_for_logger(caplog, "uvicorn.access"):
147133
async with run_server(config):
148134
async with httpx.AsyncClient() as client:
149135
response = await client.get(f"http://127.0.0.1:{unused_tcp_port}")
150136

151137
assert response.status_code == 204
152-
messages = [
153-
record.message
154-
for record in caplog.records
155-
if record.name == "uvicorn.access"
156-
]
138+
messages = [record.message for record in caplog.records if record.name == "uvicorn.access"]
157139
assert '"GET / HTTP/1.1" 204' in messages.pop()
158140

159141

160142
@pytest.mark.anyio
161143
@pytest.mark.parametrize("use_colors", [(True), (False)])
162-
async def test_default_logging(
163-
use_colors, caplog, logging_config, unused_tcp_port: int
164-
):
165-
config = Config(
166-
app=app, use_colors=use_colors, log_config=logging_config, port=unused_tcp_port
167-
)
144+
async def test_default_logging(use_colors, caplog, logging_config, unused_tcp_port: int):
145+
config = Config(app=app, use_colors=use_colors, log_config=logging_config, port=unused_tcp_port)
168146
with caplog_for_logger(caplog, "uvicorn.access"):
169147
async with run_server(config):
170148
async with httpx.AsyncClient() as client:
171149
response = await client.get(f"http://127.0.0.1:{unused_tcp_port}")
172150
assert response.status_code == 204
173-
messages = [
174-
record.message for record in caplog.records if "uvicorn" in record.name
175-
]
151+
messages = [record.message for record in caplog.records if "uvicorn" in record.name]
176152
assert "Started server process" in messages.pop(0)
177153
assert "Waiting for application startup" in messages.pop(0)
178154
assert "ASGI 'lifespan' protocol appears unsupported" in messages.pop(0)
@@ -184,19 +160,14 @@ async def test_default_logging(
184160

185161
@pytest.mark.anyio
186162
@pytest.mark.skipif(sys.platform == "win32", reason="require unix-like system")
187-
async def test_running_log_using_uds(
188-
caplog, short_socket_name, unused_tcp_port: int
189-
): # pragma: py-win32
163+
async def test_running_log_using_uds(caplog, short_socket_name, unused_tcp_port: int): # pragma: py-win32
190164
config = Config(app=app, uds=short_socket_name, port=unused_tcp_port)
191165
with caplog_for_logger(caplog, "uvicorn.access"):
192166
async with run_server(config):
193167
...
194168

195169
messages = [record.message for record in caplog.records if "uvicorn" in record.name]
196-
assert (
197-
f"Uvicorn running on unix socket {short_socket_name} (Press CTRL+C to quit)"
198-
in messages
199-
)
170+
assert f"Uvicorn running on unix socket {short_socket_name} (Press CTRL+C to quit)" in messages
200171

201172

202173
@pytest.mark.anyio
@@ -227,11 +198,7 @@ async def app(scope, receive, send):
227198
response = await client.get(f"http://127.0.0.1:{unused_tcp_port}")
228199

229200
assert response.status_code == 599
230-
messages = [
231-
record.message
232-
for record in caplog.records
233-
if record.name == "uvicorn.access"
234-
]
201+
messages = [record.message for record in caplog.records if record.name == "uvicorn.access"]
235202
assert '"GET / HTTP/1.1" 599' in messages.pop()
236203

237204

tests/middleware/test_message_logger.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@ async def app(scope, receive, send):
2626
assert sum(["ASGI [1] Send" in message for message in messages]) == 2
2727
assert sum(["ASGI [1] Receive" in message for message in messages]) == 1
2828
assert sum(["ASGI [1] Completed" in message for message in messages]) == 1
29-
assert (
30-
sum(["ASGI [1] Raised exception" in message for message in messages]) == 0
31-
)
29+
assert sum(["ASGI [1] Raised exception" in message for message in messages]) == 0
3230

3331

3432
@pytest.mark.anyio
@@ -48,6 +46,4 @@ async def app(scope, receive, send):
4846
assert sum(["ASGI [1] Send" in message for message in messages]) == 0
4947
assert sum(["ASGI [1] Receive" in message for message in messages]) == 0
5048
assert sum(["ASGI [1] Completed" in message for message in messages]) == 0
51-
assert (
52-
sum(["ASGI [1] Raised exception" in message for message in messages]) == 1
53-
)
49+
assert sum(["ASGI [1] Raised exception" in message for message in messages]) == 1

tests/middleware/test_proxy_headers.py

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
from typing import TYPE_CHECKING, List, Type, Union
1+
from __future__ import annotations
2+
3+
from typing import TYPE_CHECKING
24

35
import httpx
46
import pytest
@@ -45,13 +47,9 @@ async def app(
4547
("192.168.0.1", "Remote: http://127.0.0.1:123"),
4648
],
4749
)
48-
async def test_proxy_headers_trusted_hosts(
49-
trusted_hosts: Union[List[str], str], response_text: str
50-
) -> None:
50+
async def test_proxy_headers_trusted_hosts(trusted_hosts: list[str] | str, response_text: str) -> None:
5151
app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts)
52-
async with httpx.AsyncClient(
53-
app=app_with_middleware, base_url="http://testserver"
54-
) as client:
52+
async with httpx.AsyncClient(app=app_with_middleware, base_url="http://testserver") as client:
5553
headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"}
5654
response = await client.get("/", headers=headers)
5755

@@ -79,13 +77,9 @@ async def test_proxy_headers_trusted_hosts(
7977
(["192.168.0.2", "127.0.0.1"], "Remote: https://10.0.2.1:0"),
8078
],
8179
)
82-
async def test_proxy_headers_multiple_proxies(
83-
trusted_hosts: Union[List[str], str], response_text: str
84-
) -> None:
80+
async def test_proxy_headers_multiple_proxies(trusted_hosts: list[str] | str, response_text: str) -> None:
8581
app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts)
86-
async with httpx.AsyncClient(
87-
app=app_with_middleware, base_url="http://testserver"
88-
) as client:
82+
async with httpx.AsyncClient(app=app_with_middleware, base_url="http://testserver") as client:
8983
headers = {
9084
"X-Forwarded-Proto": "https",
9185
"X-Forwarded-For": "1.2.3.4, 10.0.2.1, 192.168.0.2",
@@ -99,9 +93,7 @@ async def test_proxy_headers_multiple_proxies(
9993
@pytest.mark.anyio
10094
async def test_proxy_headers_invalid_x_forwarded_for() -> None:
10195
app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts="*")
102-
async with httpx.AsyncClient(
103-
app=app_with_middleware, base_url="http://testserver"
104-
) as client:
96+
async with httpx.AsyncClient(app=app_with_middleware, base_url="http://testserver") as client:
10597
headers = httpx.Headers(
10698
{
10799
"X-Forwarded-Proto": "https",
@@ -127,12 +119,14 @@ async def test_proxy_headers_invalid_x_forwarded_for() -> None:
127119
async def test_proxy_headers_websocket_x_forwarded_proto(
128120
x_forwarded_proto: str,
129121
addr: str,
130-
ws_protocol_cls: "Type[WSProtocol | WebSocketProtocol]",
131-
http_protocol_cls: "Type[H11Protocol | HttpToolsProtocol]",
122+
ws_protocol_cls: type[WSProtocol | WebSocketProtocol],
123+
http_protocol_cls: type[H11Protocol | HttpToolsProtocol],
132124
unused_tcp_port: int,
133125
) -> None:
134-
async def websocket_app(scope, receive, send):
126+
async def websocket_app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
127+
assert scope["type"] == "websocket"
135128
scheme = scope["scheme"]
129+
assert scope["client"] is not None
136130
host, port = scope["client"]
137131
addr = "%s://%s:%d" % (scheme, host, port)
138132
await send({"type": "websocket.accept"})

tests/middleware/test_wsgi.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from __future__ import annotations
2+
13
import io
24
import sys
3-
from typing import AsyncGenerator, Callable, List
5+
from typing import AsyncGenerator, Callable
46

57
import a2wsgi
68
import httpx
@@ -10,7 +12,7 @@
1012
from uvicorn.middleware import wsgi
1113

1214

13-
def hello_world(environ: Environ, start_response: StartResponse) -> List[bytes]:
15+
def hello_world(environ: Environ, start_response: StartResponse) -> list[bytes]:
1416
status = "200 OK"
1517
output = b"Hello World!\n"
1618
headers = [
@@ -21,7 +23,7 @@ def hello_world(environ: Environ, start_response: StartResponse) -> List[bytes]:
2123
return [output]
2224

2325

24-
def echo_body(environ: Environ, start_response: StartResponse) -> List[bytes]:
26+
def echo_body(environ: Environ, start_response: StartResponse) -> list[bytes]:
2527
status = "200 OK"
2628
output = environ["wsgi.input"].read()
2729
headers = [
@@ -32,11 +34,11 @@ def echo_body(environ: Environ, start_response: StartResponse) -> List[bytes]:
3234
return [output]
3335

3436

35-
def raise_exception(environ: Environ, start_response: StartResponse) -> List[bytes]:
37+
def raise_exception(environ: Environ, start_response: StartResponse) -> list[bytes]:
3638
raise RuntimeError("Something went wrong")
3739

3840

39-
def return_exc_info(environ: Environ, start_response: StartResponse) -> List[bytes]:
41+
def return_exc_info(environ: Environ, start_response: StartResponse) -> list[bytes]:
4042
try:
4143
raise RuntimeError("Something went wrong")
4244
except RuntimeError:
@@ -110,16 +112,14 @@ async def test_wsgi_exc_info(wsgi_middleware: Callable) -> None:
110112
app=app,
111113
raise_app_exceptions=False,
112114
)
113-
async with httpx.AsyncClient(
114-
transport=transport, base_url="http://testserver"
115-
) as client:
115+
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
116116
response = await client.get("/")
117117
assert response.status_code == 500
118118
assert response.text == "Internal Server Error"
119119

120120

121121
def test_build_environ_encoding() -> None:
122-
scope: "HTTPScope" = {
122+
scope: HTTPScope = {
123123
"asgi": {"version": "3.0", "spec_version": "2.0"},
124124
"scheme": "http",
125125
"raw_path": b"/\xe6\x96\x87%2Fall",
@@ -134,12 +134,12 @@ def test_build_environ_encoding() -> None:
134134
"headers": [(b"key", b"value1"), (b"key", b"value2")],
135135
"extensions": {},
136136
}
137-
message: "HTTPRequestEvent" = {
137+
message: HTTPRequestEvent = {
138138
"type": "http.request",
139139
"body": b"",
140140
"more_body": False,
141141
}
142142
environ = wsgi.build_environ(scope, message, io.BytesIO(b""))
143-
assert environ["SCRIPT_NAME"] == "/文".encode("utf8").decode("latin-1")
144-
assert environ["PATH_INFO"] == "/all".encode("utf8").decode("latin-1")
143+
assert environ["SCRIPT_NAME"] == "/文".encode().decode("latin-1")
144+
assert environ["PATH_INFO"] == b"/all".decode("latin-1")
145145
assert environ["HTTP_KEY"] == "value1,value2"

0 commit comments

Comments
 (0)