|
| 1 | +"""Regression tests for issue #2233: stdio imports should stay optional on Windows.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import subprocess |
| 5 | +import sys |
| 6 | +import textwrap |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +REPO_ROOT = Path(__file__).resolve().parents[2] |
| 10 | + |
| 11 | + |
| 12 | +def _run_repo_python(script: str) -> subprocess.CompletedProcess[str]: |
| 13 | + env = os.environ.copy() |
| 14 | + src_path = str(REPO_ROOT / "src") |
| 15 | + env["PYTHONPATH"] = src_path if "PYTHONPATH" not in env else os.pathsep.join([src_path, env["PYTHONPATH"]]) |
| 16 | + return subprocess.run( |
| 17 | + [sys.executable, "-c", script], |
| 18 | + cwd=REPO_ROOT, |
| 19 | + env=env, |
| 20 | + capture_output=True, |
| 21 | + text=True, |
| 22 | + check=False, |
| 23 | + ) |
| 24 | + |
| 25 | + |
| 26 | +def test_server_stdio_import_does_not_load_client_stdio(): |
| 27 | + script = textwrap.dedent(""" |
| 28 | + import importlib |
| 29 | + import sys |
| 30 | +
|
| 31 | + importlib.import_module("mcp.server.stdio") |
| 32 | + assert "mcp.client.stdio" not in sys.modules |
| 33 | + """) |
| 34 | + |
| 35 | + result = _run_repo_python(script) |
| 36 | + |
| 37 | + assert result.returncode == 0, result.stderr |
| 38 | + |
| 39 | + |
| 40 | +def test_root_stdio_exports_handle_missing_pywin32(): |
| 41 | + script = textwrap.dedent(""" |
| 42 | + import builtins |
| 43 | +
|
| 44 | + real_import = builtins.__import__ |
| 45 | + blocked_modules = {"pywintypes", "win32api", "win32con", "win32job"} |
| 46 | +
|
| 47 | + def guarded_import(name, globals=None, locals=None, fromlist=(), level=0): |
| 48 | + if name.split(".", 1)[0] in blocked_modules: |
| 49 | + raise ImportError(f"blocked import: {name}") |
| 50 | + return real_import(name, globals, locals, fromlist, level) |
| 51 | +
|
| 52 | + builtins.__import__ = guarded_import |
| 53 | + try: |
| 54 | + from mcp import StdioServerParameters, stdio_client |
| 55 | +
|
| 56 | + assert StdioServerParameters.__name__ == "StdioServerParameters" |
| 57 | + assert callable(stdio_client) |
| 58 | + finally: |
| 59 | + builtins.__import__ = real_import |
| 60 | + """) |
| 61 | + |
| 62 | + result = _run_repo_python(script) |
| 63 | + |
| 64 | + assert result.returncode == 0, result.stderr |
0 commit comments