MCPcopy
hub / github.com/fastapi/fastapi / test_router_nested_lifespan_state

Function test_router_nested_lifespan_state

tests/test_router_events.py:114–171  ·  view source on GitHub ↗
(state: State)

Source from the content-addressed store, hash-verified

112
113
114def test_router_nested_lifespan_state(state: State) -> None:
115 @asynccontextmanager
116 async def lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
117 state.app_startup = True
118 yield {"app": True}
119 state.app_shutdown = True
120
121 @asynccontextmanager
122 async def router_lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
123 state.router_startup = True
124 yield {"router": True}
125 state.router_shutdown = True
126
127 @asynccontextmanager
128 async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
129 state.sub_router_startup = True
130 yield {"sub_router": True}
131 state.sub_router_shutdown = True
132
133 sub_router = APIRouter(lifespan=subrouter_lifespan)
134
135 router = APIRouter(lifespan=router_lifespan)
136 router.include_router(sub_router)
137
138 app = FastAPI(lifespan=lifespan)
139 app.include_router(router)
140
141 @app.get("/")
142 def main(request: Request) -> dict[str, str]:
143 assert request.state.app
144 assert request.state.router
145 assert request.state.sub_router
146 return {"message": "Hello World"}
147
148 assert state.app_startup is False
149 assert state.router_startup is False
150 assert state.sub_router_startup is False
151 assert state.app_shutdown is False
152 assert state.router_shutdown is False
153 assert state.sub_router_shutdown is False
154
155 with TestClient(app) as client:
156 assert state.app_startup is True
157 assert state.router_startup is True
158 assert state.sub_router_startup is True
159 assert state.app_shutdown is False
160 assert state.router_shutdown is False
161 assert state.sub_router_shutdown is False
162 response = client.get("/")
163 assert response.status_code == 200, response.text
164 assert response.json() == {"message": "Hello World"}
165
166 assert state.app_startup is True
167 assert state.router_startup is True
168 assert state.sub_router_startup is True
169 assert state.app_shutdown is True
170 assert state.router_shutdown is True
171 assert state.sub_router_shutdown is True

Callers

nothing calls this directly

Calls 5

include_routerMethod · 0.95
include_routerMethod · 0.95
APIRouterClass · 0.90
FastAPIClass · 0.90
getMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…