| 1 |
import sys |
| 2 |
from collections.abc import Callable |
| 3 |
from typing import Annotated, Any |
| 4 |
|
| 5 |
import pytest |
| 6 |
from fastapi import Depends, FastAPI |
| 7 |
from fastapi.routing import APIRoute |
| 8 |
|
| 9 |
if "--codspeed" not in sys.argv: |
| 10 |
pytest.skip( |
| 11 |
"Benchmark tests are skipped by default; run with --codspeed.", |
| 12 |
allow_module_level=True, |
| 13 |
) |
| 14 |
|
| 15 |
LAST_DEPENDENCY_INDEX = 100 |
| 16 |
ROUTE_COUNT = 20 |
| 17 |
ROUTE_PATH_PREFIX = "/route-" |
| 18 |
|
| 19 |
|
| 20 |
def _create_app() -> FastAPI: |
| 21 |
app = FastAPI() |
| 22 |
dependencies: dict[int, Callable[..., Any]] = {} |
| 23 |
|
| 24 |
def create_dependency(index: int) -> Callable[..., Any]: |
| 25 |
if index == LAST_DEPENDENCY_INDEX: |
| 26 |
|
| 27 |
def dependency() -> str: |
| 28 |
return str(index) |
| 29 |
|
| 30 |
dependency.__name__ = f"dependency_{index}" |
| 31 |
return dependency |
| 32 |
|
| 33 |
next_dependency = dependencies[index + 1] |
| 34 |
|
| 35 |
async def dependency( |
| 36 |
sub_dependency: Annotated[str, Depends(next_dependency)], |
| 37 |
) -> str: |
| 38 |
return f"{index} -> {sub_dependency}" |
| 39 |
|
| 40 |
dependency.__name__ = f"dependency_{index}" |
| 41 |
return dependency |
| 42 |
|
| 43 |
for index in reversed(range(LAST_DEPENDENCY_INDEX + 1)): |
| 44 |
dependencies[index] = create_dependency(index) |
| 45 |
|
| 46 |
async def endpoint( |
| 47 |
value: Annotated[str, Depends(dependencies[0])], |
| 48 |
) -> dict[str, str]: |
| 49 |
return {"value": value} |
| 50 |
|
| 51 |
for index in range(ROUTE_COUNT): |
| 52 |
app.add_api_route(f"{ROUTE_PATH_PREFIX}{index}", endpoint) |
| 53 |
|
| 54 |
return app |
| 55 |
|
| 56 |
|
| 57 |
def test_route_dependency_graph(benchmark) -> None: |
| 58 |
app = benchmark(_create_app) |
| 59 |
api_routes = [ |
| 60 |
route |
| 61 |
for route in app.routes |
| 62 |
if isinstance(route, APIRoute) and route.path.startswith(ROUTE_PATH_PREFIX) |
| 63 |
] |
| 64 |
assert len(api_routes) == ROUTE_COUNT |