refactor: harden lifespan shutdown with try/finally and assert client closed in test

main.py: Wrapped `app.state.federation_client.aclose()` in a `try/finally` block so the poll task cleanup always runs even if `aclose()` raises unexpectedly.

test_api.py: Extended `test_federation_client_exists_on_app_state` to capture the client reference and assert `client_ref.is_closed` after the `TestClient` context exits, verifying the lifespan shutdown closes the client.

🤖 Generated with Amplifier

Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com>
This commit is contained in:
Brian Krabach
2026-04-01 10:52:22 -07:00
parent 9c423d07db
commit 8d8d0826a7
2 changed files with 17 additions and 9 deletions
+2 -1
View File
@@ -180,8 +180,9 @@ async def lifespan(app: FastAPI):
yield
try:
await app.state.federation_client.aclose()
finally:
# Shutdown: cancel the poll loop task and wait for it to finish.
if _poll_task is not None:
_poll_task.cancel()
+7
View File
@@ -1464,3 +1464,10 @@ def test_federation_client_exists_on_app_state(monkeypatch):
assert isinstance(app.state.federation_client, httpx.AsyncClient), (
"app.state.federation_client must be an httpx.AsyncClient instance"
)
# Capture reference before lifespan shuts down
client_ref = app.state.federation_client
# After lifespan shutdown completes, the client must be closed
assert client_ref.is_closed, (
"app.state.federation_client must be closed after lifespan shutdown"
)