fastapi

Форк
0
/
test_custom_route_class.py 
118 строк · 3.1 Кб
1
import pytest
2
from fastapi import APIRouter, FastAPI
3
from fastapi.routing import APIRoute
4
from fastapi.testclient import TestClient
5
from starlette.routing import Route
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
    routes = {}
66
    for r in app.router.routes:
67
        assert isinstance(r, Route)
68
        routes[r.path] = r
69
    assert getattr(routes["/a/"], "x_type") == "A"  # noqa: B009
70
    assert getattr(routes["/a/b/"], "x_type") == "B"  # noqa: B009
71
    assert getattr(routes["/a/b/c/"], "x_type") == "C"  # noqa: B009
72

73

74
def test_openapi_schema():
75
    response = client.get("/openapi.json")
76
    assert response.status_code == 200, response.text
77
    assert response.json() == {
78
        "openapi": "3.1.0",
79
        "info": {"title": "FastAPI", "version": "0.1.0"},
80
        "paths": {
81
            "/a/": {
82
                "get": {
83
                    "responses": {
84
                        "200": {
85
                            "description": "Successful Response",
86
                            "content": {"application/json": {"schema": {}}},
87
                        }
88
                    },
89
                    "summary": "Get A",
90
                    "operationId": "get_a_a__get",
91
                }
92
            },
93
            "/a/b/": {
94
                "get": {
95
                    "responses": {
96
                        "200": {
97
                            "description": "Successful Response",
98
                            "content": {"application/json": {"schema": {}}},
99
                        }
100
                    },
101
                    "summary": "Get B",
102
                    "operationId": "get_b_a_b__get",
103
                }
104
            },
105
            "/a/b/c/": {
106
                "get": {
107
                    "responses": {
108
                        "200": {
109
                            "description": "Successful Response",
110
                            "content": {"application/json": {"schema": {}}},
111
                        }
112
                    },
113
                    "summary": "Get C",
114
                    "operationId": "get_c_a_b_c__get",
115
                }
116
            },
117
        },
118
    }
119

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.