Debian Codegraph @

tests/memory_benchmarks/test_dependency_graph.py

raw
1 import inspect
2 import sys
3 from collections.abc import Callable
4 from typing import Any
5
6 import pytest
7 from fastapi import Depends, FastAPI
8 from fastapi.routing import APIRoute
9
10 if "--codspeed" not in sys.argv:
11 pytest.skip(
12 "Benchmark tests are skipped by default; run with --codspeed.",
13 allow_module_level=True,
14 )
15
16 LAST_DEPENDENCY_INDEX = 100
17 ENDPOINT_PARAMETER_COUNT = 50
18 ROUTE_PATH = "/dynamic-health"
19
20
21 def _create_app() -> FastAPI:
22 app = FastAPI()
23 dependencies: dict[int, Callable[..., Any]] = {}
24
25 def create_dependency(index: int) -> Callable[..., Any]:
26 if index == LAST_DEPENDENCY_INDEX:
27
28 def dependency() -> str:
29 return str(index)
30
31 dependency.__name__ = f"dependency_{index}"
32 return dependency
33
34 next_dependency = dependencies[index + 1]
35
36 async def dependency(
37 sub_dependency: str = Depends(next_dependency),
38 ) -> str:
39 return f"{index} -> {sub_dependency}"
40
41 dependency.__name__ = f"dependency_{index}"
42 return dependency
43
44 for index in reversed(range(LAST_DEPENDENCY_INDEX + 1)):
45 dependencies[index] = create_dependency(index)
46
47 def create_endpoint() -> Callable[..., Any]:
48 parameters = [
49 inspect.Parameter(
50 name=f"arg_{index}",
51 kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
52 default=Depends(dependencies[index]),
53 annotation=str,
54 )
55 for index in range(ENDPOINT_PARAMETER_COUNT)
56 ]
57
58 async def endpoint(**kwargs: str) -> dict[str, int]:
59 return {"parameter_count": len(kwargs)}
60
61 endpoint_with_signature: Any = endpoint
62 endpoint_with_signature.__signature__ = inspect.Signature(parameters)
63 return endpoint
64
65 for method in ("GET", "POST"):
66 app.add_api_route(
67 ROUTE_PATH,
68 create_endpoint(),
69 methods=[method],
70 )
71
72 return app
73
74
75 def test_dependency_graph(benchmark) -> None:
76 app = benchmark(_create_app)
77 dynamic_routes = [
78 route
79 for route in app.routes
80 if isinstance(route, APIRoute) and route.path == ROUTE_PATH
81 ]
82 assert len(dynamic_routes) == 2
83 assert {method for route in dynamic_routes for method in route.methods} == {
84 "GET",
85 "POST",
86 }