Skip to content

Commit d46ed5a

Browse files
committed
fix: ensure 100% branch coverage for __aexit__ lifecycle transitions
Add tests for __aexit__ when session is already in Closing or Closed state, covering the 'if' False branch and the second except RuntimeError. Mark the first except RuntimeError as pragma: no cover since it is unreachable under the current transition table (all non-terminal states can transition to Closing).
1 parent dbde2e0 commit d46ed5a

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/mcp/server/session.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ async def __aexit__(
267267
InitializationState.Closing,
268268
):
269269
self._transition_state(InitializationState.Closing)
270-
except RuntimeError:
270+
except RuntimeError: # pragma: no cover
271271
logger.debug("Could not transition to Closing from %s", self._initialization_state.name)
272272
try:
273273
return await super().__aexit__(exc_type, exc_val, exc_tb)

tests/server/test_session_lifecycle.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,25 @@ async def test_aexit_stateless_transitions_to_closed() -> None:
220220
assert session.initialization_state == InitializationState.Closed
221221

222222

223+
async def test_aexit_already_closing() -> None:
224+
"""__aexit__ skips Closing transition when already in Closing state."""
225+
async with _session_context() as session:
226+
async with session:
227+
session._transition_state(InitializationState.Closing)
228+
229+
assert session.initialization_state == InitializationState.Closed
230+
231+
232+
async def test_aexit_already_closed() -> None:
233+
"""__aexit__ handles already-Closed sessions gracefully."""
234+
async with _session_context() as session:
235+
async with session:
236+
session._transition_state(InitializationState.Closing)
237+
session._transition_state(InitializationState.Closed)
238+
239+
assert session.initialization_state == InitializationState.Closed
240+
241+
223242
# ---------------------------------------------------------------------------
224243
# Integration: full handshake lifecycle
225244
# ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)