2
from fastapi import APIRouter, FastAPI
3
from fastapi.routing import APIRoute
4
from fastapi.testclient import TestClient
5
from starlette.routing import Route
10
class APIRouteA(APIRoute):
14
class APIRouteB(APIRoute):
18
class APIRouteC(APIRoute):
22
router_a = APIRouter(route_class=APIRouteA)
23
router_b = APIRouter(route_class=APIRouteB)
24
router_c = APIRouter(route_class=APIRouteC)
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")
47
client = TestClient(app)
50
@pytest.mark.parametrize(
51
"path,expected_status,expected_response",
53
("/a", 200, {"msg": "A"}),
54
("/a/b", 200, {"msg": "B"}),
55
("/a/b/c", 200, {"msg": "C"}),
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
64
def test_route_classes():
66
for r in app.router.routes:
67
assert isinstance(r, Route)
69
assert getattr(routes["/a/"], "x_type") == "A"
70
assert getattr(routes["/a/b/"], "x_type") == "B"
71
assert getattr(routes["/a/b/c/"], "x_type") == "C"
74
def test_openapi_schema():
75
response = client.get("/openapi.json")
76
assert response.status_code == 200, response.text
77
assert response.json() == {
79
"info": {"title": "FastAPI", "version": "0.1.0"},
85
"description": "Successful Response",
86
"content": {"application/json": {"schema": {}}},
90
"operationId": "get_a_a__get",
97
"description": "Successful Response",
98
"content": {"application/json": {"schema": {}}},
102
"operationId": "get_b_a_b__get",
109
"description": "Successful Response",
110
"content": {"application/json": {"schema": {}}},
114
"operationId": "get_c_a_b_c__get",