Skip to content

Commit ded5594

Browse files
cliffhallclaude
andcommitted
test(time): characterize serve() through the protocol, per-file coverage
Part of #4855. - Rename src/time/test/ to tests/ and time_server_test.py to test_server.py, matching fetch and git; set testpaths and asyncio_mode = "auto". - Add pytest-asyncio and pytest-cov to the dev group; configure branch coverage of src/mcp_server_time and a gitignored coverage.json. - tests/test_protocol.py drives serve() in-process over memory streams with a ClientSession: initialize (serverInfo.version is the SDK's, #360), the pinned tool list and schemas (#3201, #2853), both tools across zones and DST edges, and every error branch, compared as wire JSON. - tests/test_entrypoints.py covers main(), both __main__ paths in-process and one console-script stdio smoke. - Mark convert_time's missing-key check unreachable, with its reason. - Document the coverage command in the README. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent f702610 commit ded5594

9 files changed

Lines changed: 1245 additions & 4 deletions

File tree

‎.claude/skills/testing/SKILL.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ when they land. Do not write a test that assumes them.
2626
| Server | Directory | File name | Runner |
2727
| --- | --- | --- | --- |
2828
| `everything`, `filesystem`, `memory`, `sequentialthinking` | `src/<server>/__tests__/` | `<subject>.test.ts` | vitest, `globals: true` |
29-
| `fetch`, `git` | `src/<server>/tests/` | `test_<subject>.py` | pytest |
30-
| `time` | `src/time/test/` | `<subject>_test.py` | pytest |
29+
| `fetch`, `git`, `time` | `src/<server>/tests/` | `test_<subject>.py` | pytest |
3130
| Root tooling | `scripts/`, beside the script | `<name>.test.mjs` | `node --test` |
3231

3332
Each vitest config includes only `**/__tests__/**/*.test.ts`, so a test file
@@ -216,7 +215,7 @@ than adding a dependency for one test.
216215
| Every TypeScript server | `npm test` at the root |
217216
| One TypeScript server's whole chain | `npm run validate -w src/<server>` (format check, lint, typecheck, build, test) |
218217
| One Python server | `uv run pytest` in `src/<server>` |
219-
| One Python test | `uv run pytest <path to the test file>::<name>` in `src/<server>` (for example `tests/test_server.py::test_git_checkout_existing_branch`, or `test/time_server_test.py::…` in `time`) |
218+
| One Python test | `uv run pytest <path to the test file>::<name>` in `src/<server>` (for example `tests/test_server.py::test_git_checkout_existing_branch`) |
220219
| One Python server's whole chain | `npm run validate:py -- <server>` |
221220
| Root tooling | `npm run test:scripts` |
222221

‎src/time/.gitignore‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Coverage output from the per-server coverage command (see README,
2+
# "Development"); generated locally and never committed.
3+
coverage.json
4+
.coverage
5+
.coverage.*

‎src/time/README.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,31 @@ npx @modelcontextprotocol/inspector uv run mcp-server-time
274274
3. "When it's 4 PM in New York, what time is it in London?"
275275
4. "Convert 9:30 AM Tokyo time to New York time"
276276

277+
## Development
278+
279+
Run the tests from `src/time`. They live in `tests/`: `test_protocol.py` drives
280+
the server through an MCP `ClientSession` in-process, `test_entrypoints.py`
281+
covers `main()`, `python -m mcp_server_time` and the console script, and
282+
`test_server.py` unit-tests the time helpers.
283+
284+
```bash
285+
cd src/time
286+
uv run pytest
287+
```
288+
289+
Coverage is a separate command. It measures line and branch coverage of
290+
`src/mcp_server_time`, prints the missing lines, and writes `coverage.json`
291+
(ignored by git):
292+
293+
```bash
294+
cd src/time
295+
uv run --frozen pytest --cov --cov-report=term-missing --cov-report=json
296+
```
297+
298+
Every file must reach 90% of its lines and 90% of its branches. Code that
299+
cannot be reached is marked `# pragma: no cover # <reason>`, always with the
300+
reason, rather than lowering the bar.
301+
277302
## Build
278303

279304
Docker build:

‎src/time/pyproject.toml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,18 @@ dev-dependencies = [
3939
"freezegun>=1.5.1",
4040
"pyright>=1.1.389",
4141
"pytest>=8.3.3",
42+
"pytest-asyncio>=1.4.0",
43+
"pytest-cov>=7.1.0",
4244
"ruff>=0.8.1",
4345
]
46+
47+
[tool.pytest.ini_options]
48+
testpaths = ["tests"]
49+
asyncio_mode = "auto"
50+
51+
[tool.coverage.run]
52+
branch = true
53+
source = ["src/mcp_server_time"]
54+
55+
[tool.coverage.report]
56+
show_missing = true

‎src/time/src/mcp_server_time/server.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,9 @@ async def call_tool(
208208
k in arguments
209209
for k in ["source_timezone", "time", "target_timezone"]
210210
):
211-
raise ValueError("Missing required arguments")
211+
raise ValueError( # pragma: no cover # unreachable: the SDK rejects a missing key against inputSchema first
212+
"Missing required arguments"
213+
)
212214

213215
result = time_server.convert_time(
214216
arguments["source_timezone"],

‎src/time/tests/test_entrypoints.py‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# Tests for mcp-server-time's entry points (#4855): `main()` in `__init__.py`,
2+
# `python -m mcp_server_time` (`__main__.py`), and the `mcp-server-time`
3+
# console script.
4+
#
5+
# `main()` and both `__main__` paths run in-process with `serve` patched out,
6+
# so coverage measures them and nothing reads real stdin. The console script
7+
# gets the one thin subprocess smoke test: it is the only way to prove the
8+
# installed entry point boots and speaks MCP over real stdio.
9+
10+
import os
11+
import runpy
12+
import shutil
13+
import sys
14+
from pathlib import Path
15+
from unittest.mock import AsyncMock, MagicMock, patch
16+
17+
import pytest
18+
from mcp import ClientSession, StdioServerParameters
19+
from mcp.client.stdio import stdio_client
20+
21+
import mcp_server_time
22+
23+
24+
@pytest.mark.parametrize(
25+
"argv,expected_local_timezone",
26+
[
27+
([], None),
28+
(["--local-timezone", "Europe/Paris"], "Europe/Paris"),
29+
(["--local-timezone=America/Chicago"], "America/Chicago"),
30+
],
31+
)
32+
def test_main_passes_local_timezone_to_serve(
33+
argv: list[str], expected_local_timezone: str | None
34+
) -> None:
35+
serve = AsyncMock()
36+
with (
37+
patch.object(mcp_server_time, "serve", serve),
38+
patch.object(sys, "argv", ["mcp-server-time", *argv]),
39+
):
40+
mcp_server_time.main()
41+
serve.assert_awaited_once_with(expected_local_timezone)
42+
43+
44+
def test_main_help_describes_the_server(capsys: pytest.CaptureFixture[str]) -> None:
45+
serve = AsyncMock()
46+
with (
47+
patch.object(mcp_server_time, "serve", serve),
48+
patch.object(sys, "argv", ["mcp-server-time", "--help"]),
49+
pytest.raises(SystemExit) as exit_info,
50+
):
51+
mcp_server_time.main()
52+
assert exit_info.value.code == 0
53+
out = capsys.readouterr().out
54+
assert (
55+
"give a model the ability to handle time queries and timezone conversions"
56+
in out
57+
)
58+
assert "--local-timezone" in out
59+
serve.assert_not_awaited()
60+
61+
62+
def test_main_rejects_unknown_arguments(capsys: pytest.CaptureFixture[str]) -> None:
63+
serve = AsyncMock()
64+
with (
65+
patch.object(mcp_server_time, "serve", serve),
66+
patch.object(sys, "argv", ["mcp-server-time", "--bogus"]),
67+
pytest.raises(SystemExit) as exit_info,
68+
):
69+
mcp_server_time.main()
70+
assert exit_info.value.code == 2
71+
assert "unrecognized arguments: --bogus" in capsys.readouterr().err
72+
serve.assert_not_awaited()
73+
74+
75+
def test_python_dash_m_calls_main() -> None:
76+
# What `python -m mcp_server_time` executes.
77+
main = MagicMock()
78+
with patch.object(mcp_server_time, "main", main):
79+
runpy.run_module("mcp_server_time", run_name="__main__")
80+
main.assert_called_once_with()
81+
82+
83+
def test_init_module_run_as_main_calls_main() -> None:
84+
# `__init__.py` carries its own `if __name__ == "__main__"` guard. Running
85+
# it as a module re-executes it in a fresh namespace, which imports
86+
# `serve` from `.server` again, so the patch goes there.
87+
serve = AsyncMock()
88+
with (
89+
patch("mcp_server_time.server.serve", serve),
90+
patch.object(sys, "argv", ["mcp-server-time", "--local-timezone", "UTC"]),
91+
):
92+
runpy.run_module("mcp_server_time.__init__", run_name="__main__")
93+
serve.assert_awaited_once_with("UTC")
94+
95+
96+
async def test_console_script_boots_over_stdio() -> None:
97+
script = shutil.which("mcp-server-time", path=str(Path(sys.executable).parent))
98+
assert script is not None, "the console script is not installed in this venv"
99+
params = StdioServerParameters(
100+
command=script,
101+
args=["--local-timezone", "UTC"],
102+
env={**os.environ},
103+
)
104+
with open(os.devnull, "w") as errlog:
105+
async with stdio_client(params, errlog=errlog) as (read, write):
106+
async with ClientSession(read, write) as session:
107+
init = await session.initialize()
108+
tools = await session.list_tools()
109+
result = await session.call_tool(
110+
"get_current_time", {"timezone": "UTC"}
111+
)
112+
assert init.model_dump(by_alias=True, mode="json")["serverInfo"]["name"] == (
113+
"mcp-time"
114+
)
115+
assert [tool.name for tool in tools.tools] == ["get_current_time", "convert_time"]
116+
assert result.model_dump(by_alias=True, mode="json")["isError"] is False

0 commit comments

Comments
 (0)