Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 60 additions & 19 deletions tests/unit/experimental_mcp_client/test_mcp_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
import importlib
import json
import os
import selectors
import sys
from collections.abc import AsyncIterator
from collections.abc import AsyncIterator, Callable
from pathlib import Path
from types import ModuleType
from typing import Final
Expand Down Expand Up @@ -84,8 +85,8 @@ def _create_transport_context(self) -> tuple[_TransportContext, httpx2.AsyncClie
class _ManualClockLoop(asyncio.SelectorEventLoop):
"""An event loop whose clock moves only when the test advances it, so timeouts fire on test-controlled conditions"""

def __init__(self) -> None:
super().__init__()
def __init__(self, selector: selectors.BaseSelector | None = None) -> None:
super().__init__(selector)
self._now = 0.0

def time(self) -> float:
Expand All @@ -95,6 +96,28 @@ def advance(self, seconds: float) -> None:
self._now += seconds


class _AutojumpSelector(selectors.DefaultSelector):
def __init__(self, advance: Callable[[float], None]) -> None:
super().__init__()
self._advance = advance

def select(self, timeout: float | None = None) -> list[tuple[selectors.SelectorKey, int]]:
ready: Final = super().select(0)
if ready or timeout == 0:
return ready

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Unit test uses clock This selector advances a manual clock, which the SSE test uses to drive its deadline. The tests/unit guidance requires unit tests to use no clock, so this repository requirement must be satisfied before merging

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guidance bans real wall-clock dependence. This loop is an injected virtual clock, the same fake _ManualClockLoop this file already uses, so no real time is read

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. This does not introduce real wall-clock dependence: _AutojumpSelector only advances the injected _ManualClockLoop's virtual time when no I/O or callback is ready, and no wall-clock value is read. That is consistent with the existing fake-clock pattern in this file. My earlier comment was incorrect; I withdraw it.

if timeout is None:
return super().select(None)
self._advance(timeout)
return []


class _AutojumpClockLoop(_ManualClockLoop):
"""A manual-clock loop that jumps to the next timer only once no callback or I/O event is left to run"""

def __init__(self) -> None:
super().__init__(_AutojumpSelector(self.advance))


class _FakeExceptionGroup(Exception):
"""Duck-typed stand-in for an anyio/builtin ExceptionGroup.

Expand Down Expand Up @@ -1890,16 +1913,26 @@ async def test_transport_parsing_failure_is_preserved(transport: MCPTransport, f
)


@pytest.mark.asyncio
async def test_sse_read_failure_is_preserved() -> None:
client: Final = MCPClient(server_url="https://example.com/sse", transport_type=MCPTransport.sse, timeout=0.2)
with pytest.raises(httpx2.ReadError, match="secret-read-error"):
await asyncio.wait_for(
client._execute_session_operation(
_diagnostic_transport(MCPTransport.sse, "io-error", "tools/list"), lambda session: session.list_tools()
),
timeout=3,
)
def test_sse_read_failure_is_preserved() -> None:
loop: Final = _AutojumpClockLoop()

async def run() -> None:
client: Final = MCPClient(server_url="https://example.com/sse", transport_type=MCPTransport.sse, timeout=0.2)
with pytest.raises(httpx2.ReadError, match="secret-read-error"):
await asyncio.wait_for(
client._execute_session_operation(
_diagnostic_transport(MCPTransport.sse, "io-error", "tools/list"),
lambda session: session.list_tools(),
),
timeout=3,
)

try:
loop.run_until_complete(run())
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.run_until_complete(loop.shutdown_default_executor())
loop.close()


@pytest.mark.asyncio
Expand Down Expand Up @@ -2638,9 +2671,12 @@ def test_public_mcp_import_preserves_incompatible_sdk_error() -> None:
@pytest.mark.parametrize("grouped", (False, True))
@pytest.mark.parametrize("raise_on_error", (False, True))
@pytest.mark.parametrize("termination", ("ok", "failure", "hang"))
async def test_outer_deadline_delivers_session_termination(termination: str, grouped: bool, raise_on_error: bool) -> None:
async def test_outer_deadline_delivers_session_termination(
termination: str, grouped: bool, raise_on_error: bool
) -> None:
deleted: Final = asyncio.Event()
started: Final = asyncio.Event()
caller_deadline: Final[asyncio.Future[anyio.CancelScope]] = asyncio.get_running_loop().create_future()

async def respond(request: httpx2.Request) -> httpx2.Response:
await anyio.lowlevel.checkpoint()
Expand Down Expand Up @@ -2672,22 +2708,27 @@ async def respond(request: httpx2.Request) -> httpx2.Response:
if payload.method == "tools/list":
return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": {"tools": []}})
started.set()
caller_deadline.result().deadline = anyio.current_time()
await anyio.sleep_forever()
raise AssertionError("cancelled request resumed")

client: Final = _MockTransportClient(respond, server_url="https://example.com/mcp", timeout=30)

async def invoke():
with anyio.fail_after(0.2):
pending: Final = client.call_tool(CallToolRequestParams(name="slow", arguments={}), raise_on_error=raise_on_error)
async def invoke() -> None:
with anyio.fail_after(None) as deadline:
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
caller_deadline.set_result(deadline)
pending: Final = client.call_tool(
CallToolRequestParams(name="slow", arguments={}), raise_on_error=raise_on_error
)
if grouped:
await asyncio.gather(pending)
else:
await pending

before: Final = anyio.current_time()
with pytest.raises(TimeoutError):
await invoke()
with anyio.fail_after(6.5):
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
with pytest.raises(TimeoutError):
await invoke()
assert started.is_set()
assert deleted.is_set(), "Cancellation must deliver DELETE before returning to the caller"

Expand Down
Loading