better web tests
This commit is contained in:
+21
-28
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
@@ -31,36 +32,28 @@ def mcp_endpoint_url() -> str:
|
||||
return os.getenv("PERSONAL_MCP_TEST_HTTP_URL", "")
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def mcp_http_client() -> AsyncIterator[AsyncClient]:
|
||||
"""Provides a reusable async HTTP client for MCP SDK transports."""
|
||||
async with AsyncClient(timeout=10.0) as http_client:
|
||||
yield http_client
|
||||
@pytest.fixture
|
||||
def mcp_session_factory(mcp_endpoint_url: str):
|
||||
"""Provides a context manager factory for MCP SDK sessions.
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def mcp_session_uninitialized(
|
||||
mcp_endpoint_url: str,
|
||||
mcp_http_client: AsyncClient,
|
||||
) -> AsyncIterator[ClientSession]:
|
||||
"""Provides a connected MCP SDK session before initialize is called."""
|
||||
Keeping stream/client/session enter and exit in the test task avoids
|
||||
cross-task cancel scope teardown errors from async generator fixtures.
|
||||
"""
|
||||
if not mcp_endpoint_url:
|
||||
pytest.skip("Set PERSONAL_MCP_TEST_HTTP_URL to run SDK-backed MCP endpoint tests.")
|
||||
|
||||
async with (
|
||||
streamable_http_client(
|
||||
mcp_endpoint_url,
|
||||
http_client=mcp_http_client,
|
||||
) as (read_stream, write_stream, _),
|
||||
ClientSession(read_stream, write_stream) as session,
|
||||
):
|
||||
yield session
|
||||
@asynccontextmanager
|
||||
async def create_session(*, initialize: bool = True) -> AsyncIterator[ClientSession]:
|
||||
async with (
|
||||
AsyncClient(timeout=10.0) as http_client,
|
||||
streamable_http_client(
|
||||
mcp_endpoint_url,
|
||||
http_client=http_client,
|
||||
) as (read_stream, write_stream, _),
|
||||
ClientSession(read_stream, write_stream) as session,
|
||||
):
|
||||
if initialize:
|
||||
await session.initialize()
|
||||
yield session
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def mcp_session(
|
||||
mcp_session_uninitialized: ClientSession,
|
||||
) -> AsyncIterator[ClientSession]:
|
||||
"""Provides an initialized MCP SDK session ready for endpoint calls."""
|
||||
await mcp_session_uninitialized.initialize()
|
||||
yield mcp_session_uninitialized
|
||||
return create_session
|
||||
|
||||
Reference in New Issue
Block a user