-
Notifications
You must be signed in to change notification settings - Fork 481
Expand file tree
/
Copy pathtest_depends.py
More file actions
509 lines (355 loc) · 15.5 KB
/
Copy pathtest_depends.py
File metadata and controls
509 lines (355 loc) · 15.5 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
"""Tests for the Depends() dependency injection feature using Annotated."""
import json
import pytest
from typing_extensions import Annotated
from aws_lambda_powertools.event_handler import APIGatewayHttpResolver
from aws_lambda_powertools.event_handler.depends import DependencyResolutionError, Depends
from aws_lambda_powertools.event_handler.request import Request
from tests.functional.utils import load_event
API_GW_V2_EVENT = load_event("apiGatewayProxyV2Event.json")
def test_depends_simple():
"""A simple dependency is resolved and injected into the handler."""
app = APIGatewayHttpResolver()
def get_greeting() -> str:
return "hello"
@app.post("/my/path")
def handler(greeting: Annotated[str, Depends(get_greeting)]):
return {"greeting": greeting}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"greeting": "hello"}
def test_depends_nested():
"""Dependencies can depend on other dependencies."""
app = APIGatewayHttpResolver()
def get_prefix() -> str:
return "Hello"
def get_greeting(prefix: Annotated[str, Depends(get_prefix)]) -> str:
return f"{prefix}, world!"
@app.post("/my/path")
def handler(greeting: Annotated[str, Depends(get_greeting)]):
return {"greeting": greeting}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"greeting": "Hello, world!"}
def test_depends_cache_per_invocation():
"""Same dependency used twice in one invocation is only resolved once (use_cache=True)."""
app = APIGatewayHttpResolver()
call_count = 0
def get_config() -> dict:
nonlocal call_count
call_count += 1
return {"key": "value"}
def get_a(config: Annotated[dict, Depends(get_config)]) -> str:
return config["key"]
def get_b(config: Annotated[dict, Depends(get_config)]) -> str:
return config["key"]
@app.post("/my/path")
def handler(a: Annotated[str, Depends(get_a)], b: Annotated[str, Depends(get_b)]):
return {"a": a, "b": b}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert call_count == 1 # get_config called once despite being used by both get_a and get_b
def test_depends_no_cache():
"""use_cache=False resolves every time."""
app = APIGatewayHttpResolver()
call_count = 0
def get_value() -> int:
nonlocal call_count
call_count += 1
return call_count
@app.post("/my/path")
def handler(
a: Annotated[int, Depends(get_value, use_cache=False)],
b: Annotated[int, Depends(get_value, use_cache=False)],
):
return {"a": a, "b": b}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert call_count == 2
def test_depends_with_request():
"""A dependency can receive the Request object."""
app = APIGatewayHttpResolver()
def get_method(request: Request) -> str:
return request.method
@app.post("/my/path")
def handler(method: Annotated[str, Depends(get_method)]):
return {"method": method}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"method": "POST"}
def test_depends_override():
"""dependency_overrides replaces a dependency callable for testing."""
app = APIGatewayHttpResolver()
def get_tenant() -> str:
return "real-tenant"
@app.post("/my/path")
def handler(tenant: Annotated[str, Depends(get_tenant)]):
return {"tenant": tenant}
app.dependency_overrides[get_tenant] = lambda: "test-tenant"
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"tenant": "test-tenant"}
app.dependency_overrides.clear()
def test_depends_override_nested():
"""dependency_overrides works for nested dependencies too."""
app = APIGatewayHttpResolver()
def get_db_client():
return "real-db"
def get_table(db: Annotated[str, Depends(get_db_client)]) -> str:
return f"table-from-{db}"
@app.post("/my/path")
def handler(table: Annotated[str, Depends(get_table)]):
return {"table": table}
app.dependency_overrides[get_db_client] = lambda: "mock-db"
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"table": "table-from-mock-db"}
app.dependency_overrides.clear()
def test_depends_multiple_handlers():
"""Dependencies work across different route handlers."""
app = APIGatewayHttpResolver()
def get_user() -> str:
return "user-123"
@app.get("/my/path")
def get_handler(user: Annotated[str, Depends(get_user)]):
return {"user": user, "action": "get"}
@app.post("/my/path")
def post_handler(user: Annotated[str, Depends(get_user)]):
return {"user": user, "action": "post"}
# Test POST (matches the event)
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"user": "user-123", "action": "post"}
def test_depends_reusable_type_alias():
"""Annotated type aliases can be reused across handlers."""
app = APIGatewayHttpResolver()
def get_tenant() -> str:
return "tenant-abc"
TenantId = Annotated[str, Depends(get_tenant)]
@app.post("/my/path")
def handler(tenant: TenantId):
return {"tenant": tenant}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"tenant": "tenant-abc"}
def test_handler_without_depends_works_normally():
"""A plain handler with no Depends() params is not affected by DI."""
app = APIGatewayHttpResolver()
@app.post("/my/path")
def handler():
return {"ok": True}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"ok": True}
def test_depends_not_cached_across_invocations():
"""Each app() call resolves dependencies fresh — no cross-request leakage."""
app = APIGatewayHttpResolver()
call_count = 0
def get_counter() -> int:
nonlocal call_count
call_count += 1
return call_count
@app.post("/my/path")
def handler(c: Annotated[int, Depends(get_counter)]):
return {"c": c}
result1 = app(API_GW_V2_EVENT, {})
result2 = app(API_GW_V2_EVENT, {})
assert json.loads(result1["body"]) == {"c": 1}
assert json.loads(result2["body"]) == {"c": 2}
assert call_count == 2
def test_depends_deeply_nested():
"""Three-level dependency chain resolves correctly."""
app = APIGatewayHttpResolver()
def get_url() -> str:
return "postgres://localhost"
def get_conn(url: Annotated[str, Depends(get_url)]) -> str:
return f"conn({url})"
def get_session(conn: Annotated[str, Depends(get_conn)]) -> str:
return f"session({conn})"
@app.post("/my/path")
def handler(session: Annotated[str, Depends(get_session)]):
return {"session": session}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"session": "session(conn(postgres://localhost))"}
def test_depends_with_request_reads_headers():
"""A dependency using Request can read actual request headers."""
app = APIGatewayHttpResolver()
def get_user_agent(request: Request) -> str:
return request.headers.get("user-agent", "unknown")
@app.post("/my/path")
def handler(ua: Annotated[str, Depends(get_user_agent)]):
return {"ua": ua}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert isinstance(json.loads(result["body"])["ua"], str)
def test_depends_returning_none():
"""A dependency can return None without breaking."""
app = APIGatewayHttpResolver()
def get_nothing() -> None:
return None
@app.post("/my/path")
def handler(val: Annotated[None, Depends(get_nothing)]):
return {"val": val}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"val": None}
def test_depends_exception_raises_dependency_resolution_error():
"""If a dependency raises, a DependencyResolutionError wraps the original exception."""
app = APIGatewayHttpResolver()
def broken() -> str:
raise ValueError("boom")
@app.post("/my/path")
def handler(val: Annotated[str, Depends(broken)]):
return {"val": val}
with pytest.raises(DependencyResolutionError, match="broken.*boom"):
app(API_GW_V2_EVENT, {})
def test_depends_non_callable_raises_dependency_resolution_error():
"""Passing a non-callable to Depends() raises DependencyResolutionError immediately."""
with pytest.raises(DependencyResolutionError, match="requires a callable"):
Depends("not_a_function") # type: ignore
with pytest.raises(DependencyResolutionError, match="requires a callable"):
Depends(42) # type: ignore
with pytest.raises(DependencyResolutionError, match="requires a callable"):
Depends(None) # type: ignore
def test_depends_accepts_lambda():
"""Depends() works with a lambda as the dependency."""
app = APIGatewayHttpResolver()
@app.post("/my/path")
def handler(val: Annotated[str, Depends(lambda: "from-lambda")]):
return {"val": val}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"val": "from-lambda"}
def test_depends_accepts_class_with_call():
"""Depends() works with a class that implements __call__."""
app = APIGatewayHttpResolver()
class TenantProvider:
def __call__(self) -> str:
return "tenant-from-class"
@app.post("/my/path")
def handler(tenant: Annotated[str, Depends(TenantProvider())]):
return {"tenant": tenant}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"tenant": "tenant-from-class"}
def test_depends_accepts_class_as_factory():
"""Depends() works with a class itself (constructor as callable)."""
app = APIGatewayHttpResolver()
class Config:
def __init__(self):
self.region = "us-east-1"
@app.post("/my/path")
def handler(config: Annotated[Config, Depends(Config)]):
return {"region": config.region}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"region": "us-east-1"}
def test_depends_with_unresolvable_annotations_is_ignored():
"""A handler whose annotations cannot be resolved by get_type_hints is treated as having no deps."""
app = APIGatewayHttpResolver()
# Build a function with broken annotations that get_type_hints cannot resolve.
# The param has a default so the handler can still be called without it.
def make_handler():
def handler(x: "CompletelyBogusType" = None): # noqa: F821
return {"ok": True}
return handler
app.post("/my/path")(make_handler())
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"ok": True}
def test_depends_without_request_does_not_inject():
"""A dependency that does NOT declare Request still works when request is available."""
app = APIGatewayHttpResolver()
def get_static() -> str:
return "no-request-needed"
@app.post("/my/path")
def handler(val: Annotated[str, Depends(get_static)]):
return {"val": val}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"val": "no-request-needed"}
def test_depends_with_broken_type_hints_on_dependency():
"""A dependency callable with broken annotations still resolves (get_type_hints fails gracefully)."""
app = APIGatewayHttpResolver()
# Create a callable whose annotations reference a nonexistent type
# so get_type_hints() will raise inside solve_dependencies
broken_dep = type(
"BrokenDep",
(),
{
"__call__": lambda self: "it-works",
"__annotations__": {"x": "NonExistentType"},
"__module__": __name__,
},
)()
@app.post("/my/path")
def handler(val: Annotated[str, Depends(broken_dep)]):
return {"val": val}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"val": "it-works"}
# ---------------------------------------------------------------------------
# request.context — bridge between middleware and Depends()
# ---------------------------------------------------------------------------
def test_depends_request_context_writable():
"""Dependencies can write to request.context and handlers can read it."""
app = APIGatewayHttpResolver()
def set_tenant(request: Request) -> str:
tenant = request.headers.get("x-tenant-id", "default")
request.context["tenant"] = tenant
return tenant
@app.post("/my/path")
def handler(tenant: Annotated[str, Depends(set_tenant)], request: Request):
return {"tenant": tenant, "from_context": request.context.get("tenant")}
event = {**API_GW_V2_EVENT, "headers": {**API_GW_V2_EVENT.get("headers", {}), "x-tenant-id": "acme-corp"}}
result = app(event, {})
assert result["statusCode"] == 200
body = json.loads(result["body"])
assert body["tenant"] == "acme-corp"
assert body["from_context"] == "acme-corp"
def test_depends_request_context_bridges_middleware():
"""Middleware writes to app.context, Depends() reads via request.context."""
app = APIGatewayHttpResolver()
def auth_middleware(app, next_middleware):
app.append_context(user="admin-user")
return next_middleware(app)
app.use(middlewares=[auth_middleware])
def get_current_user(request: Request) -> str:
return request.context["user"]
@app.post("/my/path")
def handler(user: Annotated[str, Depends(get_current_user)]):
return {"user": user}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"user": "admin-user"}
def test_depends_request_context_with_router():
"""request.context works when routes come from an included Router."""
from aws_lambda_powertools.event_handler.api_gateway import Router
app = APIGatewayHttpResolver()
router = Router()
def mw(app, next_middleware):
app.append_context(role="admin")
return next_middleware(app)
app.use(middlewares=[mw])
def get_role(request: Request) -> str:
return request.context["role"]
@router.post("/my/path")
def handler(role: Annotated[str, Depends(get_role)]):
return {"role": role}
app.include_router(router)
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"role": "admin"}
def test_depends_request_resolved_event():
"""Dependencies can access the full event via request.resolved_event."""
app = APIGatewayHttpResolver()
def get_path(request: Request) -> str:
return request.resolved_event.path
@app.post("/my/path")
def handler(path: Annotated[str, Depends(get_path)]):
return {"path": path}
result = app(API_GW_V2_EVENT, {})
assert result["statusCode"] == 200
body = json.loads(result["body"])
assert body["path"] == "/my/path"