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
+10 -9
View File
@@ -180,15 +180,16 @@ async def lifespan(app: FastAPI):
yield yield
await app.state.federation_client.aclose() try:
await app.state.federation_client.aclose()
# Shutdown: cancel the poll loop task and wait for it to finish. finally:
if _poll_task is not None: # Shutdown: cancel the poll loop task and wait for it to finish.
_poll_task.cancel() if _poll_task is not None:
try: _poll_task.cancel()
await _poll_task try:
except (asyncio.CancelledError, Exception): await _poll_task
pass except (asyncio.CancelledError, Exception):
pass
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
+7
View File
@@ -1464,3 +1464,10 @@ def test_federation_client_exists_on_app_state(monkeypatch):
assert isinstance(app.state.federation_client, httpx.AsyncClient), ( assert isinstance(app.state.federation_client, httpx.AsyncClient), (
"app.state.federation_client must be an httpx.AsyncClient instance" "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"
)