Skip to content

Commit 88b4ca9

Browse files
fix http tests
1 parent 88ac535 commit 88b4ca9

File tree

2 files changed

+243
-121
lines changed

2 files changed

+243
-121
lines changed

tests/functional/event_handler/_pydantic/test_http_resolver_pydantic.py

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import asyncio
66
import json
7-
from typing import Annotated
7+
from typing import Annotated, Any
88

99
import pytest
1010
from pydantic import BaseModel, Field
@@ -17,6 +17,35 @@
1717
pytestmark = pytest.mark.filterwarnings("ignore:HttpResolverAlpha is an alpha feature")
1818

1919

20+
# =============================================================================
21+
# ASGI Test Helpers
22+
# =============================================================================
23+
24+
25+
def make_asgi_receive(body: bytes = b""):
26+
"""Create an ASGI receive callable."""
27+
28+
async def receive() -> dict[str, Any]:
29+
await asyncio.sleep(0)
30+
return {"type": "http.request", "body": body, "more_body": False}
31+
32+
return receive
33+
34+
35+
def make_asgi_send():
36+
"""Create an ASGI send callable that captures response."""
37+
captured: dict[str, Any] = {"status_code": None, "body": b""}
38+
39+
async def send(message: dict[str, Any]) -> None:
40+
await asyncio.sleep(0)
41+
if message["type"] == "http.response.start":
42+
captured["status_code"] = message["status"]
43+
elif message["type"] == "http.response.body":
44+
captured["body"] = message["body"]
45+
46+
return send, captured
47+
48+
2049
class UserModel(BaseModel):
2150
name: str = Field(min_length=1, max_length=100)
2251
age: int = Field(ge=0, le=150)
@@ -198,26 +227,15 @@ async def create_user(user: UserModel) -> UserResponse:
198227
"headers": [(b"content-type", b"application/json")],
199228
}
200229

201-
request_body = b'{"name": "AsyncUser", "age": 25}'
202-
response_body = b""
203-
status_code = None
204-
205-
async def receive():
206-
return {"type": "http.request", "body": request_body, "more_body": False}
207-
208-
async def send(message):
209-
nonlocal response_body, status_code
210-
if message["type"] == "http.response.start":
211-
status_code = message["status"]
212-
elif message["type"] == "http.response.body":
213-
response_body = message["body"]
230+
receive = make_asgi_receive(b'{"name": "AsyncUser", "age": 25}')
231+
send, captured = make_asgi_send()
214232

215233
# WHEN called via ASGI interface
216234
await app(scope, receive, send)
217235

218236
# THEN validation works with async handler
219-
assert status_code == 200
220-
body = json.loads(response_body)
237+
assert captured["status_code"] == 200
238+
body = json.loads(captured["body"])
221239
assert body["id"] == "async-123"
222240
assert body["user"]["name"] == "AsyncUser"
223241

0 commit comments

Comments
 (0)