|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import pytest |
| 4 | +from starlette.requests import Request |
| 5 | +from starlette.types import Message |
| 6 | + |
| 7 | +from mcp.server.http_body import BodyTooLargeError, read_request_body |
| 8 | + |
| 9 | + |
| 10 | +def make_request(*, body_chunks: list[bytes], headers: dict[str, str] | None = None) -> Request: |
| 11 | + scope = { |
| 12 | + "type": "http", |
| 13 | + "method": "POST", |
| 14 | + "path": "/", |
| 15 | + "query_string": b"", |
| 16 | + "headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()], |
| 17 | + } |
| 18 | + |
| 19 | + messages: list[Message] = [ |
| 20 | + { |
| 21 | + "type": "http.request", |
| 22 | + "body": chunk, |
| 23 | + "more_body": i < len(body_chunks) - 1, |
| 24 | + } |
| 25 | + for i, chunk in enumerate(body_chunks) |
| 26 | + ] |
| 27 | + |
| 28 | + async def receive() -> Message: |
| 29 | + if messages: |
| 30 | + return messages.pop(0) |
| 31 | + return {"type": "http.request", "body": b"", "more_body": False} |
| 32 | + |
| 33 | + return Request(scope, receive) |
| 34 | + |
| 35 | + |
| 36 | +pytestmark = pytest.mark.anyio |
| 37 | + |
| 38 | + |
| 39 | +async def test_read_request_body_allows_disabling_limit_with_none(): |
| 40 | + request = make_request(body_chunks=[b"x" * 20]) |
| 41 | + body = await read_request_body(request, max_body_bytes=None) |
| 42 | + assert body == b"x" * 20 |
| 43 | + |
| 44 | + |
| 45 | +async def test_read_request_body_rejects_non_positive_limit(): |
| 46 | + request = make_request(body_chunks=[b"{}"]) |
| 47 | + with pytest.raises(ValueError, match="max_body_bytes must be positive or None"): |
| 48 | + await read_request_body(request, max_body_bytes=0) |
| 49 | + |
| 50 | + |
| 51 | +async def test_read_request_body_ignores_invalid_content_length_header(): |
| 52 | + request = make_request(body_chunks=[b"{}"], headers={"content-length": "not-a-number"}) |
| 53 | + body = await read_request_body(request, max_body_bytes=10) |
| 54 | + assert body == b"{}" |
| 55 | + |
| 56 | + |
| 57 | +async def test_read_request_body_errors_if_more_chunks_arrive_after_limit_is_reached(): |
| 58 | + # First chunk reaches the limit exactly; the next non-empty chunk should error. |
| 59 | + request = make_request(body_chunks=[b"12345", b"6"]) |
| 60 | + with pytest.raises(BodyTooLargeError): |
| 61 | + await read_request_body(request, max_body_bytes=5) |
| 62 | + |
| 63 | + |
| 64 | +async def test_read_request_body_handles_empty_request_body(): |
| 65 | + request = make_request(body_chunks=[]) |
| 66 | + body = await read_request_body(request, max_body_bytes=10) |
| 67 | + assert body == b"" |
0 commit comments