Skip to content

Commit 5ac07dc

Browse files
cliffhallclaude
andauthored
test(git): characterize serve() through the protocol, gate coverage per file
Drive the real serve() in-process: stdio_server is patched to hand it the server side of in-memory streams, and a ClientSession asserts on the wire JSON of every result. Covers all 12 tools against temporary repositories, the list_tools wire snapshot, input-validation and bad repo_path errors, --repository restriction (incl. the #4550 concerns), Roots, serve() startup, main() and python -m, plus one console-script subprocess smoke. Pins current bugs without fixing them: #4762, #4763, #4804, #360, #3029, git_branch's non-error 'Invalid branch type', the uncaught NoSuchPathError for a nonexistent --repository, flag-injection messages wrapped by BadName, and git_show's repr header and strict UTF-8 decode. Regression guards for #628 and #1682. Adds pytest-asyncio (the anyio.run test is converted) and pytest-cov with branch coverage, documents the coverage command in the README, ignores its output, and marks the three unreachable spots with reasoned pragmas. Every file is at 100% lines and branches. Part of #4855 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 8170cb6 commit 5ac07dc

11 files changed

Lines changed: 2001 additions & 45 deletions

File tree

‎src/git/.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
11
__pycache__
22
.venv
3+
# Coverage output (see Development in README.md)
4+
.coverage
5+
.coverage.*
6+
coverage.json

‎src/git/README.md‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,24 @@ help you debug any issues.
290290

291291
## Development
292292

293-
If you are doing local development, there are two ways to test your changes:
293+
### Tests and coverage
294+
295+
The test suite drives `serve()` in-process through an MCP `ClientSession`
296+
(see `tests/conftest.py`). From `src/git`:
297+
298+
```bash
299+
uv run --frozen pytest # the tests
300+
uv run --frozen pytest --cov --cov-report=term-missing --cov-report=json
301+
```
302+
303+
The second command adds branch coverage of `src/mcp_server_git`, printed per
304+
file and written to `coverage.json` (ignored by git). Every file must stay at
305+
or above 90% of its lines and 90% of its branches. Code that cannot be reached
306+
is marked `# pragma: no cover # <reason>` rather than lowering that bar.
307+
308+
### Trying changes in a client
309+
310+
There are two ways to try your changes in a client:
294311

295312
1. Run the MCP inspector to test your changes. See [Debugging](#debugging) for run instructions.
296313

‎src/git/pyproject.toml‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,25 @@ requires = ["hatchling"]
3434
build-backend = "hatchling.build"
3535

3636
[dependency-groups]
37-
dev = ["pyright>=1.1.407", "ruff>=0.7.3", "pytest>=8.0.0"]
37+
dev = [
38+
"pyright>=1.1.407",
39+
"ruff>=0.7.3",
40+
"pytest>=8.0.0",
41+
"pytest-cov>=7.1.0",
42+
"pytest-asyncio>=1.4.0",
43+
]
3844

3945
[tool.pytest.ini_options]
4046
testpaths = ["tests"]
4147
python_files = "test_*.py"
4248
python_classes = "Test*"
4349
python_functions = "test_*"
50+
asyncio_mode = "auto"
51+
asyncio_default_fixture_loop_scope = "function"
52+
53+
[tool.coverage.run]
54+
branch = true
55+
source = ["src/mcp_server_git"]
56+
57+
[tool.coverage.report]
58+
show_missing = true

‎src/git/src/mcp_server_git/__init__.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,7 @@ def main(repository: Path | None, verbose: bool) -> None:
2222
asyncio.run(serve(repository))
2323

2424

25-
if __name__ == "__main__":
25+
if (
26+
__name__ == "__main__"
27+
): # pragma: no cover # `python -m` runs __main__.py; running this file directly fails on the relative import
2628
main()

‎src/git/src/mcp_server_git/server.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,10 +255,10 @@ def git_show(repo: git.Repo, revision: str) -> str:
255255
for d in diff:
256256
output.append(f"\n--- {d.a_path}\n+++ {d.b_path}\n")
257257
if d.diff is None:
258-
continue
258+
continue # pragma: no cover # with create_patch=True GitPython always assigns the patch as bytes
259259
if isinstance(d.diff, bytes):
260260
output.append(d.diff.decode("utf-8"))
261-
else:
261+
else: # pragma: no cover # with create_patch=True GitPython always assigns the patch as bytes
262262
output.append(d.diff)
263263
return "".join(output)
264264

‎src/git/tests/conftest.py‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
"""Shared fixtures: temporary repositories and an in-process MCP client.
2+
3+
`connect()` drives the real `serve()` through the protocol without a
4+
subprocess: `stdio_server` is patched to hand `serve()` the server side of a
5+
pair of in-memory streams, and a `ClientSession` talks to the other side. Every
6+
assertion is then made on what a client receives over the wire.
7+
"""
8+
9+
import shutil
10+
from collections.abc import AsyncIterator, Iterator
11+
from contextlib import asynccontextmanager
12+
from pathlib import Path
13+
from typing import Any
14+
from unittest import mock
15+
16+
import anyio
17+
import git
18+
import pytest
19+
from mcp import ClientSession
20+
from mcp.client.session import ListRootsFnT
21+
from mcp.shared.memory import create_client_server_memory_streams
22+
from pydantic import BaseModel
23+
24+
from mcp_server_git.server import serve
25+
26+
27+
@pytest.fixture
28+
def test_repository(tmp_path: Path) -> Iterator[git.Repo]:
29+
repo_path = tmp_path / "temp_test_repo"
30+
test_repo = git.Repo.init(repo_path)
31+
32+
Path(repo_path / "test.txt").write_text("test")
33+
test_repo.index.add(["test.txt"])
34+
test_repo.index.commit("initial commit")
35+
36+
yield test_repo
37+
38+
# Close GitPython's persistent `git cat-file` processes first: on Windows
39+
# their cwd is inside the repository, so rmtree fails with WinError 32
40+
# (#4855, unblocks #1149).
41+
test_repo.close()
42+
shutil.rmtree(repo_path)
43+
44+
45+
def make_repo(path: Path) -> git.Repo:
46+
"""A repository on branch `main` with one commit of `test.txt`."""
47+
repo = git.Repo.init(path, initial_branch="main")
48+
with repo.config_writer() as config:
49+
config.set_value("user", "name", "Test User")
50+
config.set_value("user", "email", "[email protected]")
51+
(path / "test.txt").write_text("line 1\nline 2\nline 3\nline 4\nline 5\n")
52+
repo.index.add(["test.txt"])
53+
repo.index.commit("initial commit")
54+
return repo
55+
56+
57+
@pytest.fixture
58+
def repo(tmp_path: Path) -> Iterator[git.Repo]:
59+
r = make_repo(tmp_path / "repo")
60+
yield r
61+
r.close()
62+
63+
64+
@asynccontextmanager
65+
async def connect(
66+
repository: Path | None,
67+
*,
68+
list_roots_callback: ListRootsFnT | None = None,
69+
initialize: bool = True,
70+
) -> AsyncIterator[ClientSession]:
71+
"""Run `serve(repository)` in-process and yield a connected client.
72+
73+
The client is initialized unless `initialize=False`, for a test that
74+
inspects the initialize result itself.
75+
"""
76+
async with create_client_server_memory_streams() as (
77+
client_streams,
78+
server_streams,
79+
):
80+
81+
@asynccontextmanager
82+
async def fake_stdio_server() -> AsyncIterator[Any]:
83+
yield server_streams
84+
85+
with mock.patch("mcp_server_git.server.stdio_server", fake_stdio_server):
86+
async with anyio.create_task_group() as tg:
87+
tg.start_soon(serve, repository)
88+
async with ClientSession(
89+
*client_streams, list_roots_callback=list_roots_callback
90+
) as session:
91+
if initialize:
92+
await session.initialize()
93+
yield session
94+
tg.cancel_scope.cancel()
95+
96+
97+
def wire(model: BaseModel) -> dict[str, Any]:
98+
"""A result as it travels on the wire, independent of SDK attribute names."""
99+
return model.model_dump(by_alias=True, mode="json", exclude_none=True)
100+
101+
102+
def text_result(text: str, *, is_error: bool = False) -> dict[str, Any]:
103+
"""The wire shape of a tool result holding a single text block."""
104+
return {"content": [{"type": "text", "text": text}], "isError": is_error}

0 commit comments

Comments
 (0)