Skip to content

#122 test: a cancelled request releases its DB session - #130

Merged
gregoryfoster merged 1 commit into
mainfrom
122-cancel-releases-session
Nov 17, 2026
Merged

gregoryfoster merged 1 commit into
mainfrom
122-cancel-releases-session

Conversation

@gregoryfoster

Copy link
Copy Markdown
Member

Closes #122

Tests only (tests/api/test_deps.py). No deploy: drift.counts() ignores tests/.

What

  • real_engine fixture: the app's own engine (reset_engine() + get_engine() on TEST_DATABASE_URL), disposed and reset in teardown. This exercises the real get_db_session, not the client fixtures' savepointed override.
  • A test-only app: one route with Depends(get_db_session) that runs SELECT 1 (sessions check out lazily) and then blocks on an asyncio.Event.
  • Task cancellation (test_a_cancelled_request_releases_its_session): under ASGITransport the app runs in the client's task. The test cancels the task while the handler is inside, then asserts pool.checkedout() is back to baseline. This is the path 🐛 Fix async yield dependency cleanup on cancellation fastapi/fastapi#16739 (0.162.7) changed.
  • Client disconnect, as uvicorn delivers it (test_a_request_whose_client_disconnected_releases_its_session): this drives raw ASGI. receive answers http.disconnect and send drops the response. That matches uvicorn's h11 cycle (connection_lost sets disconnected, and send returns early). uvicorn doesn't cancel the app task on a disconnect, so the handler runs to completion. The test then asserts the pool is back to baseline.
  • Each test also asserts checkedout() == baseline + 1 while the handler is blocked, so a session that never checks out a connection can't make it pass.

Evidence

  • fastapi 0.162.7 / starlette 1.7.0 (lock): 6/6 in test_deps.py pass. Full suite: 1990 passed, 12 skipped, 98.80% coverage. ruff clean.
  • Red: a dependency that opens a session without async with and never closes it fails both tests at the final assertion (assert 1 == 0). That change was temporary and isn't committed.
  • uv run --no-sync --with fastapi==0.162.0 (fastapi 0.162.0, starlette 1.7.0, no lock change): both pass. So 0.162.0 didn't leak on this path either.

🤖 Generated with Claude Code

Drives the real get_db_session (the client fixtures override it) through
a blocking route on the app's own engine, reset to the test database, and
asserts pool.checkedout() returns to baseline after a task cancellation
and after an http.disconnect as uvicorn delivers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Test that a cancelled request releases its DB session (fastapi 0.162.5/0.162.7 cancellation cleanup, from #121)

1 participant