Debian Codegraph @

tests/test_custom_route_class.py

raw
1 import pytest
2 from fastapi import APIRouter, FastAPI
3 from fastapi.routing import APIRoute
4 from fastapi.testclient import TestClient
5 from inline_snapshot import snapshot
6
7 app = FastAPI()
8
9
10 class APIRouteA(APIRoute):
11 x_type = "A"
12
13
14 class APIRouteB(APIRoute):
15 x_type = "B"
16
17
18 class APIRouteC(APIRoute):
19 x_type = "C"
20
21
22 router_a = APIRouter(route_class=APIRouteA)
23 router_b = APIRouter(route_class=APIRouteB)
24 router_c = APIRouter(route_class=APIRouteC)
25
26
27 @router_a.get("/")
28 def get_a():
29 return {"msg": "A"}
30
31
32 @router_b.get("/")
33 def get_b():
34 return {"msg": "B"}
35
36
37 @router_c.get("/")
38 def get_c():
39 return {"msg": "C"}
40
41
42 router_b.include_router(router=router_c, prefix="/c")
43 router_a.include_router(router=router_b, prefix="/b")
44 app.include_router(router=router_a, prefix="/a")
45
46
47 client = TestClient(app)
48
49
50 @pytest.mark.parametrize(
51 "path,expected_status,expected_response",
52 [
53 ("/a", 200, {"msg": "A"}),
54 ("/a/b", 200, {"msg": "B"}),
55 ("/a/b/c", 200, {"msg": "C"}),
56 ],
57 )
58 def test_get_path(path, expected_status, expected_response):
59 response = client.get(path)
60 assert response.status_code == expected_status
61 assert response.json() == expected_response
62
63
64 def test_route_classes():
65 assert isinstance(router_a.routes[0], APIRouteA)
66 assert isinstance(router_b.routes[0], APIRouteB)
67 assert isinstance(router_c.routes[0], APIRouteC)
68
69
70 def test_openapi_schema():
71 response = client.get("/openapi.json")
72 assert response.status_code == 200, response.text
73 assert response.json() == snapshot(
74 {
75 "openapi": "3.1.0",
76 "info": {"title": "FastAPI", "version": "0.1.0"},
77 "paths": {
78 "/a/": {
79 "get": {
80 "responses": {
81 "200": {
82 "description": "Successful Response",
83 "content": {"application/json": {"schema": {}}},
84 }
85 },
86 "summary": "Get A",
87 "operationId": "get_a_a__get",
88 }
89 },
90 "/a/b/": {
91 "get": {
92 "responses": {
93 "200": {
94 "description": "Successful Response",
95 "content": {"application/json": {"schema": {}}},
96 }
97 },
98 "summary": "Get B",
99 "operationId": "get_b_a_b__get",
100 }
101 },
102 "/a/b/c/": {
103 "get": {
104 "responses": {
105 "200": {
106 "description": "Successful Response",
107 "content": {"application/json": {"schema": {}}},
108 }
109 },
110 "summary": "Get C",
111 "operationId": "get_c_a_b_c__get",
112 }
113 },
114 },
115 }
116 )