-
Notifications
You must be signed in to change notification settings - Fork 474
Expand file tree
/
Copy pathtest_http_resolver_pydantic.py
More file actions
371 lines (275 loc) · 11 KB
/
test_http_resolver_pydantic.py
File metadata and controls
371 lines (275 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
"""Tests for HttpResolverLocal with Pydantic validation."""
from __future__ import annotations
import asyncio
import json
from typing import Annotated, Any
import pytest
from pydantic import BaseModel, Field
from aws_lambda_powertools.event_handler import HttpResolverLocal
from aws_lambda_powertools.event_handler.http_resolver import MockLambdaContext
from aws_lambda_powertools.event_handler.openapi.params import Query
# Suppress warning for all tests
pytestmark = pytest.mark.filterwarnings("ignore:HttpResolverLocal is intended for local development")
# =============================================================================
# ASGI Test Helpers
# =============================================================================
def make_asgi_receive(body: bytes = b""):
"""Create an ASGI receive callable."""
async def receive() -> dict[str, Any]:
await asyncio.sleep(0)
return {"type": "http.request", "body": body, "more_body": False}
return receive
def make_asgi_send():
"""Create an ASGI send callable that captures response."""
captured: dict[str, Any] = {"status_code": None, "body": b""}
async def send(message: dict[str, Any]) -> None:
await asyncio.sleep(0)
if message["type"] == "http.response.start":
captured["status_code"] = message["status"]
elif message["type"] == "http.response.body":
captured["body"] = message["body"]
return send, captured
class UserModel(BaseModel):
name: str = Field(min_length=1, max_length=100)
age: int = Field(ge=0, le=150)
email: str | None = None
class UserResponse(BaseModel):
id: str
user: UserModel
created: bool = True
# =============================================================================
# Body Validation Tests
# =============================================================================
def test_valid_body_validation():
# GIVEN an app with validation enabled and a route expecting UserModel
app = HttpResolverLocal(enable_validation=True)
@app.post("/users")
def create_user(user: UserModel) -> UserResponse:
return UserResponse(id="user-123", user=user)
event = {
"httpMethod": "POST",
"path": "/users",
"headers": {"content-type": "application/json"},
"queryStringParameters": {},
"multiValueQueryStringParameters": {},
"body": '{"name": "John", "age": 30}',
}
# WHEN sending a valid body
result = app.resolve(event, MockLambdaContext())
# THEN it returns 200 with validated data
assert result["statusCode"] == 200
body = json.loads(result["body"])
assert body["id"] == "user-123"
assert body["user"]["name"] == "John"
def test_invalid_body_validation():
# GIVEN an app with validation enabled
app = HttpResolverLocal(enable_validation=True)
@app.post("/users")
def create_user(user: UserModel) -> UserResponse:
return UserResponse(id="user-123", user=user)
event = {
"httpMethod": "POST",
"path": "/users",
"headers": {"content-type": "application/json"},
"queryStringParameters": {},
"multiValueQueryStringParameters": {},
"body": '{"name": "", "age": 30}', # Empty name - invalid
}
# WHEN sending an invalid body
result = app.resolve(event, MockLambdaContext())
# THEN it returns 422 with validation error
assert result["statusCode"] == 422
body = json.loads(result["body"])
assert "detail" in body
def test_missing_required_field():
# GIVEN an app with validation enabled
app = HttpResolverLocal(enable_validation=True)
@app.post("/users")
def create_user(user: UserModel) -> UserResponse:
return UserResponse(id="user-123", user=user)
event = {
"httpMethod": "POST",
"path": "/users",
"headers": {"content-type": "application/json"},
"queryStringParameters": {},
"multiValueQueryStringParameters": {},
"body": '{"age": 30}', # Missing name
}
# WHEN sending body with missing required field
result = app.resolve(event, MockLambdaContext())
# THEN it returns 422
assert result["statusCode"] == 422
# =============================================================================
# Query Parameter Validation Tests
# =============================================================================
def test_query_param_validation():
# GIVEN an app with validated query parameters
app = HttpResolverLocal(enable_validation=True)
@app.get("/search")
def search(
q: Annotated[str, Query(description="Search query")],
page: Annotated[int, Query(ge=1)] = 1,
limit: Annotated[int, Query(ge=1, le=100)] = 10,
) -> dict:
return {"query": q, "page": page, "limit": limit}
event = {
"httpMethod": "GET",
"path": "/search",
"headers": {},
"queryStringParameters": {"q": "python", "page": "2", "limit": "50"},
"multiValueQueryStringParameters": {"q": ["python"], "page": ["2"], "limit": ["50"]},
"body": None,
}
# WHEN sending valid query params
result = app.resolve(event, MockLambdaContext())
# THEN it returns 200 with parsed values
assert result["statusCode"] == 200
body = json.loads(result["body"])
assert body["query"] == "python"
assert body["page"] == 2
assert body["limit"] == 50
def test_invalid_query_param():
# GIVEN an app with validated query parameters
app = HttpResolverLocal(enable_validation=True)
@app.get("/search")
def search(
q: Annotated[str, Query()],
limit: Annotated[int, Query(ge=1, le=100)] = 10,
) -> dict:
return {"query": q, "limit": limit}
event = {
"httpMethod": "GET",
"path": "/search",
"headers": {},
"queryStringParameters": {"q": "test", "limit": "200"}, # limit > 100
"multiValueQueryStringParameters": {"q": ["test"], "limit": ["200"]},
"body": None,
}
# WHEN sending invalid query param
result = app.resolve(event, MockLambdaContext())
# THEN it returns 422
assert result["statusCode"] == 422
# =============================================================================
# Async Handler with Validation Tests
# =============================================================================
@pytest.mark.asyncio
async def test_async_handler_with_validation():
# GIVEN an app with async handler and validation
app = HttpResolverLocal(enable_validation=True)
@app.post("/users")
async def create_user(user: UserModel) -> UserResponse:
await asyncio.sleep(0.001)
return UserResponse(id="async-123", user=user)
scope = {
"type": "http",
"method": "POST",
"path": "/users",
"query_string": b"",
"headers": [(b"content-type", b"application/json")],
}
receive = make_asgi_receive(b'{"name": "AsyncUser", "age": 25}')
send, captured = make_asgi_send()
# WHEN called via ASGI interface
await app(scope, receive, send)
# THEN validation works with async handler
assert captured["status_code"] == 200
body = json.loads(captured["body"])
assert body["id"] == "async-123"
assert body["user"]["name"] == "AsyncUser"
@pytest.mark.asyncio
async def test_async_handler_invalid_response_returns_422():
# GIVEN an app with async handler and validation
app = HttpResolverLocal(enable_validation=True)
@app.get("/user")
async def get_user() -> UserResponse:
await asyncio.sleep(0.001)
return {"name": "John"} # type: ignore # Missing required fields
scope = {
"type": "http",
"method": "GET",
"path": "/user",
"query_string": b"",
"headers": [(b"content-type", b"application/json")],
}
receive = make_asgi_receive()
send, captured = make_asgi_send()
# WHEN called via ASGI interface
await app(scope, receive, send)
# THEN it returns 422 for invalid response
assert captured["status_code"] == 422
@pytest.mark.asyncio
async def test_sync_handler_with_validation_via_asgi():
# GIVEN an app with a sync handler and validation, called via ASGI
app = HttpResolverLocal(enable_validation=True)
@app.post("/users")
def create_user(user: UserModel) -> UserResponse:
return UserResponse(id="sync-123", user=user)
scope = {
"type": "http",
"method": "POST",
"path": "/users",
"query_string": b"",
"headers": [(b"content-type", b"application/json")],
}
receive = make_asgi_receive(b'{"name": "SyncUser", "age": 30}')
send, captured = make_asgi_send()
# WHEN called via ASGI interface
await app(scope, receive, send)
# THEN validation works with sync handler
assert captured["status_code"] == 200
body = json.loads(captured["body"])
assert body["id"] == "sync-123"
assert body["user"]["name"] == "SyncUser"
@pytest.mark.asyncio
async def test_sync_handler_invalid_response_returns_422_via_asgi():
# GIVEN an app with a sync handler and validation, called via ASGI
app = HttpResolverLocal(enable_validation=True)
@app.get("/user")
def get_user() -> UserResponse:
return {"name": "John"} # type: ignore # Missing required fields
scope = {
"type": "http",
"method": "GET",
"path": "/user",
"query_string": b"",
"headers": [(b"content-type", b"application/json")],
}
receive = make_asgi_receive()
send, captured = make_asgi_send()
# WHEN called via ASGI interface
await app(scope, receive, send)
# THEN it returns 422 for invalid response
assert captured["status_code"] == 422
# =============================================================================
# OpenAPI Tests
# =============================================================================
def test_openapi_schema_generation():
# GIVEN an app with validation and multiple routes
app = HttpResolverLocal(enable_validation=True)
@app.get("/users/<user_id>")
def get_user(user_id: str) -> dict:
return {"user_id": user_id}
@app.post("/users")
def create_user(user: UserModel) -> UserResponse:
return UserResponse(id="123", user=user)
# WHEN generating OpenAPI schema
schema = app.get_openapi_schema(
title="Test API",
version="1.0.0",
)
# THEN schema contains all routes
assert schema.info.title == "Test API"
assert schema.info.version == "1.0.0"
assert "/users/{user_id}" in schema.paths
assert "/users" in schema.paths
def test_openapi_schema_includes_validation_errors():
# GIVEN an app with validation
app = HttpResolverLocal(enable_validation=True)
@app.post("/users")
def create_user(user: UserModel) -> UserResponse:
return UserResponse(id="123", user=user)
# WHEN generating OpenAPI schema
schema = app.get_openapi_schema(title="Test API", version="1.0.0")
# THEN schema includes 422 response
post_operation = schema.paths["/users"].post
assert 422 in post_operation.responses