Skip to content

Commit 39adf30

Browse files
committed
test(cli): cover _resolve_env error paths
Add tests for the dotenv-missing, dotenv-raises, and malformed-`-v` branches so coverage stays at 100% on `src/mcp/cli/cli.py`. Also drop the now-obsolete `# pragma: no cover` from `_parse_env_var` (it's exercised through `_resolve_env`).
1 parent 123ad26 commit 39adf30

2 files changed

Lines changed: 34 additions & 1 deletion

File tree

src/mcp/cli/cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def _get_npx_command():
5353
return "npx" # On Unix-like systems, just use npx
5454

5555

56-
def _parse_env_var(env_var: str) -> tuple[str, str]: # pragma: no cover
56+
def _parse_env_var(env_var: str) -> tuple[str, str]:
5757
"""Parse environment variable string in format KEY=VALUE."""
5858
if "=" not in env_var:
5959
logger.error(f"Invalid environment variable format: {env_var}. Must be KEY=VALUE")

tests/cli/test_utils.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,36 @@ def test_resolve_env_inline_vars_override_dotenv(tmp_path: Path):
134134
env_file.write_text("FOO=from_file\nBAR=keep_me\n")
135135
result = _resolve_env(env_file, ["FOO=from_cli"])
136136
assert result == {"FOO": "from_cli", "BAR": "keep_me"}
137+
138+
139+
def test_resolve_env_exits_when_dotenv_missing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
140+
"""If python-dotenv isn't installed, asking to load a .env file should exit."""
141+
env_file = tmp_path / ".env"
142+
env_file.write_text("FOO=bar\n")
143+
monkeypatch.setattr("mcp.cli.cli.dotenv", None)
144+
with pytest.raises(SystemExit) as exc:
145+
_resolve_env(env_file, [])
146+
assert exc.value.code == 1
147+
148+
149+
def test_resolve_env_exits_when_dotenv_raises(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
150+
"""OSError/ValueError from dotenv_values should be turned into a clean exit."""
151+
env_file = tmp_path / ".env"
152+
env_file.write_text("FOO=bar\n")
153+
154+
class _FakeDotenv:
155+
@staticmethod
156+
def dotenv_values(_path: Path) -> dict[str, str]:
157+
raise OSError("simulated read failure")
158+
159+
monkeypatch.setattr("mcp.cli.cli.dotenv", _FakeDotenv)
160+
with pytest.raises(SystemExit) as exc:
161+
_resolve_env(env_file, [])
162+
assert exc.value.code == 1
163+
164+
165+
def test_resolve_env_exits_on_malformed_inline_var():
166+
"""A -v flag without '=' should exit cleanly instead of raising ValueError."""
167+
with pytest.raises(SystemExit) as exc:
168+
_resolve_env(None, ["NO_EQUALS_SIGN"])
169+
assert exc.value.code == 1

0 commit comments

Comments
 (0)