|
| 1 | +import json |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import pytest |
| 5 | +from pydantic import ValidationError |
| 6 | + |
| 7 | +from mcp.server.mcpserver.resources import DirectoryResource |
| 8 | + |
| 9 | + |
| 10 | +@pytest.fixture |
| 11 | +def directory_with_files(tmp_path: Path) -> Path: |
| 12 | + (tmp_path / "z.txt").write_text("z", encoding="utf-8") |
| 13 | + (tmp_path / "a.txt").write_text("a", encoding="utf-8") |
| 14 | + (tmp_path / "nested").mkdir() |
| 15 | + (tmp_path / "nested" / "b.txt").write_text("b", encoding="utf-8") |
| 16 | + return tmp_path |
| 17 | + |
| 18 | + |
| 19 | +@pytest.fixture |
| 20 | +def regular_file(tmp_path: Path) -> Path: |
| 21 | + path = tmp_path / "file.txt" |
| 22 | + path.write_text("content", encoding="utf-8") |
| 23 | + return path |
| 24 | + |
| 25 | + |
| 26 | +@pytest.mark.anyio |
| 27 | +@pytest.mark.parametrize( |
| 28 | + ("recursive", "pattern", "expected"), |
| 29 | + [ |
| 30 | + (False, None, ["a.txt", "z.txt"]), |
| 31 | + (True, None, ["a.txt", "nested/b.txt", "z.txt"]), |
| 32 | + (False, "*.txt", ["a.txt", "z.txt"]), |
| 33 | + (True, "*.txt", ["a.txt", "nested/b.txt", "z.txt"]), |
| 34 | + ], |
| 35 | +) |
| 36 | +async def test_directory_resource_returns_sorted_posix_file_paths( |
| 37 | + directory_with_files: Path, recursive: bool, pattern: str | None, expected: list[str] |
| 38 | +) -> None: |
| 39 | + """SDK-defined listings contain sorted relative file paths for each glob mode.""" |
| 40 | + resource = DirectoryResource( |
| 41 | + uri="test://directory", name="directory", path=directory_with_files, recursive=recursive, pattern=pattern |
| 42 | + ) |
| 43 | + |
| 44 | + assert json.loads(await resource.read()) == {"files": expected} |
| 45 | + |
| 46 | + |
| 47 | +@pytest.mark.anyio |
| 48 | +async def test_directory_resource_rejects_missing_directory(tmp_path: Path) -> None: |
| 49 | + """SDK-defined directory reads report a missing path.""" |
| 50 | + resource = DirectoryResource(uri="test://directory", name="directory", path=tmp_path / "missing") |
| 51 | + |
| 52 | + with pytest.raises(FileNotFoundError): |
| 53 | + await resource.read() |
| 54 | + |
| 55 | + |
| 56 | +@pytest.mark.anyio |
| 57 | +async def test_directory_resource_rejects_regular_file(regular_file: Path) -> None: |
| 58 | + """SDK-defined directory reads reject a regular file path.""" |
| 59 | + resource = DirectoryResource(uri="test://directory", name="directory", path=regular_file) |
| 60 | + |
| 61 | + with pytest.raises(NotADirectoryError): |
| 62 | + await resource.read() |
| 63 | + |
| 64 | + |
| 65 | +def test_directory_resource_requires_absolute_path() -> None: |
| 66 | + """SDK-defined resource validation rejects relative directory paths.""" |
| 67 | + with pytest.raises(ValidationError): |
| 68 | + DirectoryResource(uri="test://directory", name="directory", path=Path("relative")) |
0 commit comments