Debian Codegraph @

tests/test_router_include_context.py

raw
1 import threading
2 from collections.abc import Sequence
3 from typing import Annotated, cast
4
5 import pytest
6 from fastapi import APIRouter, Body, Depends, FastAPI, Request, Security
7 from fastapi.exceptions import FastAPIError
8 from fastapi.openapi.utils import get_openapi
9 from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
10 from fastapi.routing import (
11 APIRoute,
12 RouteContext,
13 _IncludedRouter,
14 _iter_included_route_candidates,
15 _restore_fastapi_scope_key,
16 iter_route_contexts,
17 )
18 from fastapi.security import HTTPBearer
19 from fastapi.testclient import TestClient
20 from pydantic import BaseModel
21 from starlette.routing import BaseRoute, Host, Match, Mount, NoMatchFound, Route, Router
22
23
24 def dependency_a():
25 return "a"
26
27
28 def dependency_b():
29 return "b"
30
31
32 def dependency_c():
33 return "c"
34
35
36 def unique_id_b(route: APIRoute) -> str:
37 return f"b_{route.name}"
38
39
40 def test_iter_route_contexts_returns_direct_route_context():
41 router = APIRouter()
42
43 @router.get("/items/{item_id}")
44 def read_item(item_id: str): # pragma: no cover
45 return {"item_id": item_id}
46
47 contexts = list(iter_route_contexts(router.routes))
48
49 assert len(contexts) == 1
50 assert isinstance(contexts[0], RouteContext)
51 assert contexts[0].original_route is router.routes[0]
52 assert contexts[0].path == "/items/{item_id}"
53 assert contexts[0].path_format == "/items/{item_id}"
54 assert contexts[0].methods == {"GET"}
55 assert contexts[0].endpoint is read_item
56
57
58 def test_iter_route_contexts_supports_nested_conflict_detection():
59 existing_router = APIRouter()
60 nested_router = APIRouter()
61
62 @nested_router.get("/{username}")
63 def read_user(username: str): # pragma: no cover
64 return {"username": username}
65
66 existing_router.include_router(nested_router, prefix="/auth/user")
67
68 new_router = APIRouter()
69
70 @new_router.get("/auth/user/{username}")
71 def read_user_again(username: str): # pragma: no cover
72 return {"username": username}
73
74 existing_paths = {
75 context.path for context in iter_route_contexts(existing_router.routes)
76 }
77 new_paths = {context.path for context in iter_route_contexts(new_router.routes)}
78
79 assert existing_paths & new_paths == {"/auth/user/{username}"}
80
81
82 def test_get_openapi_accepts_filtered_route_contexts_with_effective_paths():
83 router = APIRouter()
84 bearer_scheme = HTTPBearer()
85
86 @router.get("/public", tags=["public"])
87 def read_public(token: Annotated[str, Security(bearer_scheme)]): # pragma: no cover
88 return {"public": True}
89
90 @router.get("/private", tags=["private"])
91 def read_private(): # pragma: no cover
92 return {"private": True}
93
94 app = FastAPI()
95 app.include_router(router, prefix="/api")
96
97 public_routes = [
98 context
99 for context in iter_route_contexts(app.routes)
100 if "public" in getattr(context, "tags", [])
101 ]
102 schema = get_openapi(
103 title="Public API",
104 version="1.0.0",
105 routes=public_routes,
106 )
107
108 assert set(schema["paths"]) == {"/api/public"}
109 assert "HTTPBearer" in schema["components"]["securitySchemes"]
110
111
112 def test_get_openapi_accepts_webhook_route_contexts():
113 app = FastAPI()
114 bearer_scheme = HTTPBearer()
115
116 class Subscription(BaseModel):
117 username: str
118
119 @app.webhooks.post("new-subscription")
120 def new_subscription(
121 body: Subscription, token: Annotated[str, Security(bearer_scheme)]
122 ): # pragma: no cover
123 return None
124
125 webhook_contexts = list(iter_route_contexts(app.webhooks.routes))
126 schema = get_openapi(
127 title="Webhook API",
128 version="1.0.0",
129 routes=[],
130 webhooks=webhook_contexts,
131 )
132
133 assert set(schema["webhooks"]) == {"new-subscription"}
134 assert "HTTPBearer" in schema["components"]["securitySchemes"]
135 assert "Subscription" in schema["components"]["schemas"]
136
137
138 def test_router_include_context_matches_flattened_include_metadata():
139 callback_router = APIRouter()
140
141 @callback_router.post("/callback")
142 def callback(): # pragma: no cover
143 return {"ok": True}
144
145 callback_route = callback_router.routes[0]
146
147 parent_router = APIRouter()
148 included_router = APIRouter(
149 prefix="/items",
150 tags=["router"],
151 dependencies=[Depends(dependency_a)],
152 responses={401: {"description": "Unauthorized"}},
153 callbacks=[callback_route],
154 default_response_class=HTMLResponse,
155 strict_content_type=False,
156 )
157
158 @included_router.get(
159 "/{item_id}",
160 tags=["route"],
161 dependencies=[Depends(dependency_b)],
162 responses={404: {"description": "Missing"}},
163 callbacks=[callback_route],
164 generate_unique_id_function=unique_id_b,
165 )
166 def read_item(item_id: str, request: Request):
167 context = request.scope["fastapi"]["effective_route_context"]
168 return JSONResponse(
169 {
170 "path": context.path,
171 "tags": context.tags,
172 "dependency_count": len(context.dependencies),
173 "response_codes": sorted(context.responses),
174 "callback_count": len(context.callbacks or []),
175 "deprecated": context.deprecated,
176 "include_in_schema": context.include_in_schema,
177 "response_class": context.response_class.__name__,
178 "generate_unique_id": context.generate_unique_id_function(context),
179 "strict_content_type": context.strict_content_type,
180 "has_dependency_overrides_provider": (
181 context.dependency_overrides_provider
182 is app.router.dependency_overrides_provider
183 ),
184 }
185 )
186
187 parent_router.include_router(
188 included_router,
189 prefix="/api",
190 tags=["include"],
191 dependencies=[Depends(dependency_c)],
192 responses={400: {"description": "Bad request"}},
193 callbacks=[callback_route],
194 deprecated=True,
195 include_in_schema=False,
196 )
197
198 app = FastAPI()
199 app.include_router(parent_router)
200 response = TestClient(app).get("/api/items/foo")
201
202 assert response.status_code == 200
203 assert response.json() == {
204 "path": "/api/items/{item_id}",
205 "tags": ["include", "router", "route"],
206 "dependency_count": 3,
207 "response_codes": [400, 401, 404],
208 "callback_count": 3,
209 "deprecated": True,
210 "include_in_schema": False,
211 "response_class": "HTMLResponse",
212 "generate_unique_id": "b_read_item",
213 "strict_content_type": False,
214 "has_dependency_overrides_provider": True,
215 }
216
217
218 def test_live_route_addition_uses_include_metadata_for_runtime_and_openapi():
219 calls: list[str] = []
220
221 def included_dependency():
222 calls.append("dependency")
223
224 router = APIRouter()
225 app = FastAPI()
226 app.include_router(
227 router,
228 prefix="/api",
229 tags=["included"],
230 dependencies=[Depends(included_dependency)],
231 responses={418: {"description": "Teapot"}},
232 )
233
234 @router.get("/later")
235 def read_later():
236 return {"later": True}
237
238 client = TestClient(app)
239 response = client.get("/api/later")
240
241 assert response.status_code == 200
242 assert response.json() == {"later": True}
243 assert calls == ["dependency"]
244 operation = client.get("/openapi.json").json()["paths"]["/api/later"]["get"]
245 assert operation["tags"] == ["included"]
246 assert operation["responses"]["418"] == {"description": "Teapot"}
247
248
249 def test_openapi_cache_updates_after_live_route_addition():
250 router = APIRouter()
251 app = FastAPI()
252 app.include_router(router, prefix="/api")
253 client = TestClient(app)
254
255 first_schema = client.get("/openapi.json").json()
256 assert "/api/later" not in first_schema["paths"]
257
258 @router.get("/later")
259 def read_later(): # pragma: no cover
260 return {"later": True}
261
262 second_schema = client.get("/openapi.json").json()
263 assert "/api/later" in second_schema["paths"]
264
265
266 def test_nested_router_added_after_parent_inclusion_is_live():
267 parent_router = APIRouter()
268 child_router = APIRouter()
269 app = FastAPI()
270 app.include_router(parent_router, prefix="/api")
271 parent_router.include_router(child_router, prefix="/child", tags=["child"])
272
273 @child_router.get("/items")
274 def read_items():
275 return ["item"]
276
277 client = TestClient(app)
278 response = client.get("/api/child/items")
279
280 assert response.status_code == 200
281 assert response.json() == ["item"]
282 operation = client.get("/openapi.json").json()["paths"]["/api/child/items"]["get"]
283 assert operation["tags"] == ["child"]
284
285
286 def test_repeated_deep_inclusions_handle_all_concrete_paths():
287 shared_router = APIRouter()
288
289 @shared_router.get("/items")
290 def read_items():
291 return []
292
293 parent_router = APIRouter()
294 parent_router.include_router(shared_router, prefix="/a")
295 parent_router.include_router(shared_router, prefix="/b")
296
297 app = FastAPI()
298 app.include_router(parent_router, prefix="/v1")
299 app.include_router(parent_router, prefix="/v2")
300
301 client = TestClient(app)
302 paths = ["/v1/a/items", "/v1/b/items", "/v2/a/items", "/v2/b/items"]
303 for path in paths:
304 response = client.get(path)
305 assert response.status_code == 200
306 assert response.json() == []
307 assert set(client.get("/openapi.json").json()["paths"]) == set(paths)
308
309
310 def test_url_path_for_uses_effective_context_for_live_included_route():
311 router = APIRouter()
312 app = FastAPI()
313 app.include_router(router, prefix="/api")
314
315 @router.get("/items/{item_id}", name="read_item")
316 def read_item(item_id: str): # pragma: no cover
317 return {"item_id": item_id}
318
319 assert app.url_path_for("read_item", item_id="abc") == "/api/items/abc"
320
321
322 def test_url_path_for_uses_distinct_repeated_inclusion_contexts():
323 router = APIRouter()
324
325 @router.get("/items/{item_id}", name="read_item")
326 def read_item(item_id: str): # pragma: no cover
327 return {"item_id": item_id}
328
329 parent_router = APIRouter()
330 parent_router.include_router(router, prefix="/v1")
331 parent_router.include_router(router, prefix="/v2")
332
333 assert parent_router.url_path_for("read_item", item_id="abc") == "/v1/items/abc"
334 assert (
335 parent_router.routes[1].url_path_for("read_item", item_id="abc")
336 == "/v2/items/abc"
337 )
338
339
340 def test_indirect_router_inclusion_cycles_are_rejected():
341 parent_router = APIRouter()
342 child_router = APIRouter()
343
344 parent_router.include_router(child_router, prefix="/child")
345
346 with pytest.raises(AssertionError, match="already includes this router"):
347 child_router.include_router(parent_router, prefix="/parent")
348
349 parent_router = APIRouter()
350 child_router = APIRouter()
351 grandchild_router = APIRouter()
352
353 parent_router.include_router(child_router, prefix="/child")
354 child_router.include_router(grandchild_router, prefix="/grandchild")
355
356 with pytest.raises(AssertionError, match="already includes this router"):
357 grandchild_router.include_router(parent_router, prefix="/parent")
358
359
360 def test_original_api_route_subclass_instance_is_called_after_inclusion():
361 class TrackingRoute(APIRoute):
362 calls = 0
363
364 async def handle(self, scope, receive, send):
365 self.calls += 1
366 await super().handle(scope, receive, send)
367
368 router = APIRouter(route_class=TrackingRoute)
369
370 @router.get("/items")
371 def read_items():
372 return []
373
374 original_route = router.routes[0]
375 assert isinstance(original_route, TrackingRoute)
376
377 app = FastAPI()
378 app.include_router(router, prefix="/api")
379
380 response = TestClient(app).get("/api/items")
381
382 assert response.status_code == 200
383 assert original_route.calls == 1
384
385
386 def test_original_api_route_get_route_handler_is_called_after_inclusion():
387 class TrackingRoute(APIRoute):
388 calls = 0
389
390 def get_route_handler(self):
391 handler = super().get_route_handler()
392
393 async def custom_handler(request):
394 self.calls += 1
395 return await handler(request)
396
397 return custom_handler
398
399 router = APIRouter(route_class=TrackingRoute)
400
401 @router.get("/items")
402 def read_items():
403 return []
404
405 original_route = router.routes[0]
406 assert isinstance(original_route, TrackingRoute)
407 original_route.calls = 0
408
409 app = FastAPI()
410 app.include_router(router, prefix="/api")
411
412 response = TestClient(app).get("/api/items")
413
414 assert response.status_code == 200
415 assert original_route.calls == 1
416
417
418 def test_original_api_route_matches_is_called_after_inclusion():
419 class HeaderRoute(APIRoute):
420 calls = 0
421
422 def matches(self, scope):
423 self.calls += 1
424 headers = dict(scope.get("headers", []))
425 if headers.get(b"x-match") != b"yes":
426 return Match.NONE, {}
427 return super().matches(scope)
428
429 router = APIRouter(route_class=HeaderRoute)
430
431 @router.get("/items")
432 def read_items():
433 return []
434
435 original_route = router.routes[0]
436 assert isinstance(original_route, HeaderRoute)
437 original_route.calls = 0
438
439 app = FastAPI()
440 app.include_router(router, prefix="/api")
441 client = TestClient(app)
442
443 assert client.get("/api/items").status_code == 404
444 assert client.get("/api/items", headers={"x-match": "yes"}).status_code == 200
445 assert original_route.calls >= 2
446
447
448 def test_effective_route_context_is_available_in_scope_during_request():
449 router = APIRouter()
450
451 @router.get("/items")
452 def read_items(request: Request):
453 fastapi_scope = request.scope.get("fastapi")
454 assert isinstance(fastapi_scope, dict)
455 return {
456 "has_context": "effective_route_context" in fastapi_scope,
457 "path": fastapi_scope["effective_route_context"].path,
458 }
459
460 app = FastAPI()
461 app.include_router(router, prefix="/api")
462
463 response = TestClient(app).get("/api/items")
464
465 assert response.status_code == 200
466 assert response.json() == {"has_context": True, "path": "/api/items"}
467
468
469 def test_original_api_router_matches_is_called_after_inclusion():
470 class HeaderRouter(APIRouter):
471 calls = 0
472
473 def matches(self, scope):
474 self.calls += 1
475 headers = dict(scope.get("headers", []))
476 if headers.get(b"x-router-match") != b"yes":
477 return Match.NONE, {}
478 return super().matches(scope)
479
480 router = HeaderRouter()
481
482 @router.get("/items")
483 def read_items():
484 return []
485
486 app = FastAPI()
487 app.include_router(router, prefix="/api")
488 client = TestClient(app)
489
490 assert client.get("/api/items").status_code == 404
491 assert (
492 client.get("/api/items", headers={"x-router-match": "yes"}).status_code == 200
493 )
494 assert router.calls >= 2
495
496
497 def test_original_nested_api_router_subclasses_are_called_after_inclusion():
498 class TrackingRouter(APIRouter):
499 calls = 0
500
501 async def handle(self, scope, receive, send):
502 self.calls += 1
503 await super().handle(scope, receive, send)
504
505 parent_router = TrackingRouter()
506 child_router = TrackingRouter()
507
508 @child_router.get("/items")
509 def read_items():
510 return []
511
512 parent_router.include_router(child_router, prefix="/child")
513 app = FastAPI()
514 app.include_router(parent_router, prefix="/api")
515
516 response = TestClient(app).get("/api/child/items")
517
518 assert response.status_code == 200
519 assert parent_router.calls == 1
520 assert child_router.calls == 1
521
522
523 def test_router_and_include_prefix_path_params_reach_endpoint_and_openapi():
524 router = APIRouter(prefix="/tenants/{tenant_id}")
525
526 @router.get("/items/{item_id}")
527 def read_item(version: int, tenant_id: int, item_id: int):
528 return {"version": version, "tenant_id": tenant_id, "item_id": item_id}
529
530 app = FastAPI()
531 app.include_router(router, prefix="/api/{version}")
532
533 client = TestClient(app)
534 response = client.get("/api/1/tenants/2/items/3")
535
536 assert response.status_code == 200
537 assert response.json() == {"version": 1, "tenant_id": 2, "item_id": 3}
538
539 operation = client.get("/openapi.json").json()["paths"][
540 "/api/{version}/tenants/{tenant_id}/items/{item_id}"
541 ]["get"]
542 assert {parameter["name"] for parameter in operation["parameters"]} == {
543 "version",
544 "tenant_id",
545 "item_id",
546 }
547
548
549 def test_effective_body_fields_from_app_router_include_and_route_match_openapi():
550 def app_body_dependency(app_body: Annotated[str, Body()]):
551 return app_body
552
553 def router_body_dependency(router_body: Annotated[int, Body()]):
554 return router_body
555
556 def include_body_dependency(include_body: Annotated[bool, Body()]):
557 return include_body
558
559 app = FastAPI(dependencies=[Depends(app_body_dependency)])
560 router = APIRouter(dependencies=[Depends(router_body_dependency)])
561
562 @router.post("/items")
563 def create_item(route_body: Annotated[float, Body()]):
564 return {"route_body": route_body}
565
566 app.include_router(
567 router,
568 prefix="/api",
569 dependencies=[Depends(include_body_dependency)],
570 )
571
572 client = TestClient(app)
573 response = client.post(
574 "/api/items",
575 json={
576 "app_body": "app",
577 "router_body": 1,
578 "include_body": True,
579 "route_body": 2.5,
580 },
581 )
582
583 assert response.status_code == 200
584 assert response.json() == {"route_body": 2.5}
585
586 schema = client.get("/openapi.json").json()
587 request_body_schema = schema["paths"]["/api/items"]["post"]["requestBody"][
588 "content"
589 ]["application/json"]["schema"]
590 body_ref = request_body_schema["$ref"].removeprefix("#/components/schemas/")
591 body_schema = schema["components"]["schemas"][body_ref]
592 assert set(body_schema["required"]) == {
593 "app_body",
594 "router_body",
595 "include_body",
596 "route_body",
597 }
598 assert set(body_schema["properties"]) == {
599 "app_body",
600 "router_body",
601 "include_body",
602 "route_body",
603 }
604
605
606 def test_later_full_match_wins_over_earlier_included_partial_match():
607 get_router = APIRouter()
608 post_router = APIRouter()
609
610 @get_router.get("/items")
611 def read_items(): # pragma: no cover
612 return {"method": "get"}
613
614 @post_router.post("/items")
615 def create_item():
616 return {"method": "post"}
617
618 app = FastAPI()
619 app.include_router(get_router, prefix="/api")
620 app.include_router(post_router, prefix="/api")
621
622 response = TestClient(app).post("/api/items")
623
624 assert response.status_code == 200
625 assert response.json() == {"method": "post"}
626
627
628 def test_included_partial_match_returns_405_when_no_later_full_match_exists():
629 router = APIRouter()
630
631 @router.get("/items")
632 def read_items(): # pragma: no cover
633 return []
634
635 app = FastAPI()
636 app.include_router(router, prefix="/api")
637
638 response = TestClient(app).post("/api/items")
639
640 assert response.status_code == 405
641 assert response.headers["allow"] == "GET"
642
643
644 def test_included_slash_redirect_does_not_block_later_exact_match():
645 redirect_router = APIRouter()
646 exact_router = APIRouter()
647
648 @redirect_router.get("/items/")
649 def read_items_with_slash(): # pragma: no cover
650 return {"path": "slash"}
651
652 @exact_router.get("/items")
653 def read_items_without_slash():
654 return {"path": "exact"}
655
656 app = FastAPI()
657 app.include_router(redirect_router, prefix="/api")
658 app.include_router(exact_router, prefix="/api")
659
660 response = TestClient(app).get("/api/items", follow_redirects=False)
661
662 assert response.status_code == 200
663 assert response.json() == {"path": "exact"}
664
665
666 def test_failed_included_match_does_not_leak_effective_context_to_later_route():
667 class RejectingRoute(APIRoute):
668 def matches(self, scope):
669 return Match.NONE, {}
670
671 rejecting_router = APIRouter(route_class=RejectingRoute)
672 fallback_router = APIRouter()
673
674 @rejecting_router.get("/items")
675 def rejected_item(): # pragma: no cover
676 return {"source": "rejected"}
677
678 @fallback_router.get("/items")
679 def fallback_item(request: Request):
680 fastapi_scope = request.scope.get("fastapi", {})
681 context = fastapi_scope.get("effective_route_context")
682 return {
683 "source": "fallback",
684 "context_path": getattr(context, "path", None),
685 }
686
687 app = FastAPI()
688 app.include_router(rejecting_router, prefix="/api")
689 app.include_router(fallback_router, prefix="/api")
690
691 response = TestClient(app).get("/api/items")
692
693 assert response.status_code == 200
694 assert response.json() == {"source": "fallback", "context_path": "/api/items"}
695
696
697 def test_included_starlette_mount_keeps_prefix_runtime_and_url_path_for():
698 def mounted_endpoint(request):
699 return PlainTextResponse("mounted")
700
701 router = APIRouter(
702 routes=[
703 Mount(
704 "/mounted",
705 routes=[Route("/items/{item_id}", mounted_endpoint, name="read_item")],
706 name="mounted",
707 )
708 ]
709 )
710 app = FastAPI()
711 app.include_router(router, prefix="/api")
712
713 client = TestClient(app)
714 response = client.get("/api/mounted/items/abc")
715
716 assert response.status_code == 200
717 assert response.text == "mounted"
718 assert (
719 app.url_path_for("mounted:read_item", item_id="abc") == "/api/mounted/items/abc"
720 )
721
722
723 def test_included_starlette_host_keeps_prefix_runtime_and_url_path_for():
724 def hosted_endpoint(request):
725 return PlainTextResponse("hosted")
726
727 hosted_app = Router(
728 routes=[Route("/items/{item_id}", hosted_endpoint, name="read_item")]
729 )
730 router = APIRouter(
731 routes=[Host("{subdomain}.example.com", hosted_app, name="hosted")]
732 )
733 app = FastAPI()
734 app.include_router(router, prefix="/api")
735
736 client = TestClient(app, base_url="http://api.example.com")
737 response = client.get("/api/items/abc")
738
739 assert response.status_code == 200
740 assert response.text == "hosted"
741 url = app.url_path_for("hosted:read_item", subdomain="api", item_id="abc")
742 assert str(url) == "/api/items/abc"
743 assert url.host == "api.example.com"
744
745
746 def test_restore_fastapi_scope_key_ignores_non_dict_fastapi_scope():
747 scope = {"fastapi": "not-a-dict"}
748
749 _restore_fastapi_scope_key(scope, "effective_route_context", object())
750
751 assert scope == {"fastapi": "not-a-dict"}
752
753
754 @pytest.mark.anyio
755 async def test_included_api_route_without_app_scope_returns_405_response():
756 router = APIRouter()
757
758 @router.get("/items")
759 def read_items(): # pragma: no cover
760 return {"items": []}
761
762 app = FastAPI()
763 app.include_router(router, prefix="/api")
764 included_router = cast(_IncludedRouter, app.router.routes[-1])
765 effective_context = next(included_router.effective_route_contexts())
766 route = effective_context.original_route
767 messages = []
768
769 async def receive(): # pragma: no cover
770 return {"type": "http.request", "body": b"", "more_body": False}
771
772 async def send(message):
773 messages.append(message)
774
775 scope = {
776 "type": "http",
777 "method": "POST",
778 "path": "/api/items",
779 "raw_path": b"/api/items",
780 "root_path": "",
781 "scheme": "http",
782 "query_string": b"",
783 "headers": [],
784 "fastapi": {"effective_route_context": effective_context},
785 }
786
787 await route.handle(scope, receive, send)
788
789 assert messages[0]["type"] == "http.response.start"
790 assert messages[0]["status"] == 405
791 assert dict(messages[0]["headers"])[b"allow"] == b"GET"
792
793
794 def test_effective_api_route_context_does_not_match_websocket_scope():
795 router = APIRouter()
796
797 @router.get("/items")
798 def read_items(): # pragma: no cover
799 return {"items": []}
800
801 app = FastAPI()
802 app.include_router(router, prefix="/api")
803 included_router = cast(_IncludedRouter, app.router.routes[-1])
804 effective_context = next(included_router.effective_route_contexts())
805
806 match, child_scope = effective_context.matches(
807 {
808 "type": "websocket",
809 "path": "/api/items",
810 "root_path": "",
811 }
812 )
813
814 assert match == Match.NONE
815 assert child_scope == {}
816
817
818 def test_effective_api_route_context_url_path_for_no_match():
819 router = APIRouter()
820
821 @router.get("/items/{item_id}")
822 def read_item(item_id: str): # pragma: no cover
823 return {"item_id": item_id}
824
825 app = FastAPI()
826 app.include_router(router, prefix="/api")
827 included_router = cast(_IncludedRouter, app.router.routes[-1])
828 effective_context = next(included_router.effective_route_contexts())
829
830 with pytest.raises(NoMatchFound):
831 effective_context.url_path_for("missing", item_id="abc")
832
833 with pytest.raises(NoMatchFound):
834 included_router.url_path_for("missing", item_id="abc")
835
836
837 def test_included_starlette_host_without_prefix_keeps_original_app():
838 def hosted_endpoint(request):
839 return PlainTextResponse("hosted")
840
841 hosted_app = Router(
842 routes=[Route("/items/{item_id}", hosted_endpoint, name="read_item")]
843 )
844 router = APIRouter(
845 routes=[Host("{subdomain}.example.com", hosted_app, name="hosted")]
846 )
847 app = FastAPI()
848 app.include_router(router)
849
850 client = TestClient(app, base_url="http://api.example.com")
851 response = client.get("/items/abc")
852
853 assert response.status_code == 200
854 assert response.text == "hosted"
855
856
857 class UnknownRoute(BaseRoute):
858 def matches(self, scope): # pragma: no cover
859 return Match.NONE, {}
860
861 async def handle(self, scope, receive, send): # pragma: no cover
862 raise AssertionError("UnknownRoute should not be handled")
863
864 def url_path_for(self, name, /, **path_params): # pragma: no cover
865 raise NoMatchFound(name, path_params)
866
867
868 @pytest.mark.anyio
869 async def test_included_unknown_route_is_ignored_and_can_return_default_404():
870 router = APIRouter(routes=[UnknownRoute()])
871 app = FastAPI()
872 app.include_router(router, prefix="/api")
873 included_router = cast(_IncludedRouter, app.router.routes[-1])
874
875 assert included_router.effective_candidates() == []
876
877 messages = []
878
879 async def receive(): # pragma: no cover
880 return {"type": "http.request", "body": b"", "more_body": False}
881
882 async def send(message):
883 messages.append(message)
884
885 scope = {
886 "type": "http",
887 "method": "GET",
888 "path": "/api/missing",
889 "raw_path": b"/api/missing",
890 "root_path": "",
891 "scheme": "http",
892 "query_string": b"",
893 "headers": [],
894 "fastapi": {},
895 }
896
897 await included_router._handle_selected(scope, receive, send)
898
899 assert messages[0]["type"] == "http.response.start"
900 assert messages[0]["status"] == 404
901
902
903 def test_included_router_candidate_cache_is_thread_safe():
904 router = APIRouter()
905 route_count = 120
906 thread_count = 6
907 for index in range(route_count):
908
909 @router.get(f"/items/{index}")
910 def read_item(index: int = index):
911 return {"index": index}
912
913 app = FastAPI()
914 app.include_router(router)
915 included_router = cast(_IncludedRouter, app.router.routes[-1])
916 barrier = threading.Barrier(thread_count)
917 results: list[Sequence[object]] = []
918
919 def build_candidates() -> None:
920 barrier.wait()
921 results.append(included_router.effective_candidates())
922
923 threads = [threading.Thread(target=build_candidates) for _ in range(thread_count)]
924 for thread in threads:
925 thread.start()
926 for thread in threads:
927 thread.join()
928
929 assert len(results) == thread_count
930 assert all(result is results[0] for result in results)
931 assert len(results[0]) == route_count
932 assert TestClient(app).get("/items/0").json() == {"index": 0}
933
934
935 def test_included_router_low_priority_cache_rechecks_version_after_lock(monkeypatch):
936 router = APIRouter()
937 app = FastAPI()
938 app.include_router(router)
939 included_router = cast(_IncludedRouter, app.router.routes[-1])
940 routes_version = router._get_routes_version()
941 version_checked = threading.Event()
942
943 def get_routes_version() -> int:
944 version_checked.set()
945 return routes_version
946
947 monkeypatch.setattr(router, "_get_routes_version", get_routes_version)
948 result: list[Sequence[object]] = []
949
950 def build_low_priority_routes() -> None:
951 result.append(included_router.effective_low_priority_routes())
952
953 with included_router._effective_routes_lock:
954 thread = threading.Thread(target=build_low_priority_routes)
955 thread.start()
956 assert version_checked.wait(timeout=1)
957 included_router._effective_low_priority_routes_version = routes_version
958 thread.join()
959
960 assert result == [[]]
961
962
963 def test_no_prefix_include_validation_sees_effective_starlette_route_candidates():
964 def endpoint(request): # pragma: no cover
965 return PlainTextResponse("ok")
966
967 child_router = APIRouter(routes=[Route("/items", endpoint, name="read_items")])
968 parent_router = APIRouter()
969 parent_router.include_router(child_router, prefix="/child")
970
971 candidates = list(_iter_included_route_candidates(parent_router.routes))
972
973 assert cast(Route, candidates[0]).path == "/child/items"
974
975
976 def test_no_prefix_include_validation_sees_effective_api_route_path():
977 leaf_router = APIRouter()
978
979 @leaf_router.get("")
980 def read_items():
981 return []
982
983 parent_router = APIRouter()
984 parent_router.include_router(leaf_router, prefix="/items")
985
986 # for coverage
987 candidates = list(_iter_included_route_candidates(parent_router.routes))
988 assert cast(APIRoute, candidates[0]).path == ""
989
990 app = FastAPI()
991 app.include_router(parent_router)
992 client = TestClient(app)
993
994 response = client.get("/items")
995
996 assert response.status_code == 200, response.text
997 assert response.json() == []
998
999
1000 def test_no_prefix_include_validation_sees_effective_starlette_route_path():
1001 def endpoint(request):
1002 return PlainTextResponse("ok")
1003
1004 child_router = APIRouter(routes=[Route("/items", endpoint, name="read_items")])
1005 parent_router = APIRouter()
1006 parent_router.include_router(child_router, prefix="/child")
1007
1008 app = FastAPI()
1009 app.include_router(parent_router)
1010 client = TestClient(app)
1011
1012 response = client.get("/child/items")
1013
1014 assert response.status_code == 200, response.text
1015 assert response.text == "ok"
1016
1017
1018 def test_no_prefix_include_validation_rejects_empty_effective_api_route_path():
1019 router = APIRouter()
1020
1021 @router.get("")
1022 def read_items(): # pragma: no cover
1023 return []
1024
1025 app = FastAPI()
1026 with pytest.raises(FastAPIError):
1027 app.include_router(router)
1028
1029
1030 def test_apirouter_matches_fallback_without_include_context():
1031 router = APIRouter()
1032
1033 def read_items(request): # pragma: no cover
1034 return PlainTextResponse("items")
1035
1036 router.add_route("/items", read_items)
1037
1038 assert router.matches({"type": "http", "path": "/items", "root_path": ""}) == (
1039 Match.NONE,
1040 {},
1041 )
1042
1043
1044 @pytest.mark.anyio
1045 async def test_apirouter_handle_fallback_without_include_context():
1046 router = APIRouter()
1047
1048 def read_items(request):
1049 return PlainTextResponse("items")
1050
1051 router.add_route("/items", read_items)
1052 messages = []
1053
1054 async def receive(): # pragma: no cover
1055 return {"type": "http.request", "body": b"", "more_body": False}
1056
1057 async def send(message):
1058 messages.append(message)
1059
1060 scope = {
1061 "type": "http",
1062 "method": "GET",
1063 "path": "/items",
1064 "raw_path": b"/items",
1065 "root_path": "",
1066 "scheme": "http",
1067 "query_string": b"",
1068 "headers": [],
1069 }
1070
1071 await router.handle(scope, receive, send)
1072
1073 assert messages[0]["type"] == "http.response.start"
1074 assert messages[0]["status"] == 200
1075 assert messages[1]["body"] == b"items"