"""`remote` と `cli/remote.py` が重い依存・他のサブパッケージを読み込まないことのテスト.
手元で GPU 用の依存を読み込まずに動かすため,`remote` は `torch`・`cv2` と
`tongue_seg_model` の他のサブパッケージ(`data`・`models`・`training`・`export`)を import しない
(`.claude/rules/project-structure.md`).テストの他のモジュールが既に読み込んだものと
混ざらないよう,別プロセスで `sys.modules` を確かめる.
"""
from __future__ import annotations
import json
import subprocess
import sys
import pytest
FORBIDDEN_TOP_LEVEL = ["torch", "torchvision", "cv2", "onnx", "onnxruntime", "numpy", "tiasdata"]
FORBIDDEN_SUBPACKAGES = [
"tongue_seg_model.data",
"tongue_seg_model.models",
"tongue_seg_model.training",
"tongue_seg_model.export",
"tongue_seg_model.schema",
]
_SCRIPT = """
import importlib, json, sys
for name in sys.argv[1:]:
importlib.import_module(name)
print(json.dumps(sorted(sys.modules)))
"""
def _loaded_modules(*modules: str) -> set[str]:
result = subprocess.run(
[sys.executable, "-c", _SCRIPT, *modules],
capture_output=True,
text=True,
timeout=120,
check=True,
)
return set(json.loads(result.stdout.strip().splitlines()[-1]))
@pytest.mark.parametrize(
"module",
[
"tongue_seg_model.remote",
"tongue_seg_model.remote.commands",
"tongue_seg_model.remote.config",
"tongue_seg_model.remote.files",
"tongue_seg_model.remote.gpu",
"tongue_seg_model.remote.observe",
"tongue_seg_model.remote.report",
"tongue_seg_model.remote.transfer",
"tongue_seg_model.remote.whitelist",
"tongue_seg_model.cli.remote",
],
)
def test_remote_does_not_import_heavy_dependencies(module: str) -> None:
loaded = _loaded_modules(module)
assert module in loaded
for name in FORBIDDEN_TOP_LEVEL:
assert name not in loaded, f"{module} が {name} を読み込んだ"
for name in FORBIDDEN_SUBPACKAGES:
leaked = sorted(m for m in loaded if m == name or m.startswith(name + "."))
assert not leaked, f"{module} が {leaked} を読み込んだ"
def test_help_runs_without_torch() -> None:
"""`tsm-remote --help` が torch を読み込まずに終わる(ENV_04)."""
script = (
"import sys\n"
"import tongue_seg_model.cli.remote as cli\n"
"try:\n"
" cli.main(['--help'])\n"
"except SystemExit as exc:\n"
" assert exc.code == 0, exc.code\n"
"assert 'torch' not in sys.modules\n"
"print('ok')\n"
)
result = subprocess.run(
[sys.executable, "-c", script], capture_output=True, text=True, timeout=120, check=True
)
assert result.stdout.strip().endswith("ok")