|
| 1 | +"""Tests for StreamableHTTPSessionManager.""" |
| 2 | + |
| 3 | +import anyio |
| 4 | +import pytest |
| 5 | + |
| 6 | +from mcp.server.lowlevel import Server |
| 7 | +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager |
| 8 | + |
| 9 | + |
| 10 | +@pytest.mark.anyio |
| 11 | +async def test_run_can_only_be_called_once(): |
| 12 | + """Test that run() can only be called once per instance.""" |
| 13 | + app = Server("test-server") |
| 14 | + manager = StreamableHTTPSessionManager(app=app) |
| 15 | + |
| 16 | + # First call should succeed |
| 17 | + async with manager.run(): |
| 18 | + pass |
| 19 | + |
| 20 | + # Second call should raise RuntimeError |
| 21 | + with pytest.raises(RuntimeError) as excinfo: |
| 22 | + async with manager.run(): |
| 23 | + pass |
| 24 | + |
| 25 | + assert ( |
| 26 | + "StreamableHTTPSessionManager .run() can only be called once per instance" |
| 27 | + in str(excinfo.value) |
| 28 | + ) |
| 29 | + |
| 30 | + |
| 31 | +@pytest.mark.anyio |
| 32 | +async def test_run_prevents_concurrent_calls(): |
| 33 | + """Test that concurrent calls to run() are prevented.""" |
| 34 | + app = Server("test-server") |
| 35 | + manager = StreamableHTTPSessionManager(app=app) |
| 36 | + |
| 37 | + errors = [] |
| 38 | + |
| 39 | + async def try_run(): |
| 40 | + try: |
| 41 | + async with manager.run(): |
| 42 | + # Simulate some work |
| 43 | + await anyio.sleep(0.1) |
| 44 | + except RuntimeError as e: |
| 45 | + errors.append(e) |
| 46 | + |
| 47 | + # Try to run concurrently |
| 48 | + async with anyio.create_task_group() as tg: |
| 49 | + tg.start_soon(try_run) |
| 50 | + tg.start_soon(try_run) |
| 51 | + |
| 52 | + # One should succeed, one should fail |
| 53 | + assert len(errors) == 1 |
| 54 | + assert ( |
| 55 | + "StreamableHTTPSessionManager .run() can only be called once per instance" |
| 56 | + in str(errors[0]) |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +@pytest.mark.anyio |
| 61 | +async def test_handle_request_without_run_raises_error(): |
| 62 | + """Test that handle_request raises error if run() hasn't been called.""" |
| 63 | + app = Server("test-server") |
| 64 | + manager = StreamableHTTPSessionManager(app=app) |
| 65 | + |
| 66 | + # Mock ASGI parameters |
| 67 | + scope = {"type": "http", "method": "POST", "path": "/test"} |
| 68 | + |
| 69 | + async def receive(): |
| 70 | + return {"type": "http.request", "body": b""} |
| 71 | + |
| 72 | + async def send(message): |
| 73 | + pass |
| 74 | + |
| 75 | + # Should raise error because run() hasn't been called |
| 76 | + with pytest.raises(RuntimeError) as excinfo: |
| 77 | + await manager.handle_request(scope, receive, send) |
| 78 | + |
| 79 | + assert "Task group is not initialized. Make sure to use run()." in str( |
| 80 | + excinfo.value |
| 81 | + ) |
0 commit comments