Skip to content

Commit 0d1031d

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 4af9799 commit 0d1031d

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
@@ -266,7 +266,7 @@ async def __aexit__(
266266
InitializationState.Closing,
267267
):
268268
self._transition_state(InitializationState.Closing)
269-
except RuntimeError:
269+
except RuntimeError: # pragma: no cover
270270
logger.debug("Could not transition to Closing from %s", self._initialization_state.name)
271271
try:
272272
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)