"""`labremote` と `labremote.cli` が重い依存を読み込まないことのテスト.
TongueSegModel の tests/remote/test_imports.py の移植.手元で GPU 用の依存を読み込まずに
動かすため,`labremote` は `torch`・`cv2` 等を import しない
(`.claude/rules/project-structure.md`).
移植元の「`tongue_seg_model` の他のサブパッケージを import しない」確認は,LabRemote に
該当するパッケージが無いため外した.テストの他のモジュールが既に読み込んだものと
混ざらないよう,別プロセスで `sys.modules` を確かめる.
"""
from __future__ import annotations
import json
import subprocess
import sys
import pytest
FORBIDDEN_TOP_LEVEL = ["torch", "torchvision", "cv2", "onnx", "onnxruntime", "numpy", "tiasdata"]
_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",
[
"labremote",
"labremote.commands",
"labremote.config",
"labremote.files",
"labremote.gpu",
"labremote.observe",
"labremote.report",
"labremote.transfer",
"labremote.whitelist",
"labremote.cli",
],
)
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} を読み込んだ"
def test_help_runs_without_torch() -> None:
"""`labremote --help` が torch を読み込まずに終わる(ENV_04)."""
script = (
"import sys\n"
"import labremote.cli 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")
def test_remote_does_not_import_source_project() -> None:
"""移す元のパッケージ(`tongue_seg_model`)を読み込まない(SPEC_01「モジュールの構成」)."""
loaded = _loaded_modules("labremote.cli")
assert "labremote.cli" in loaded
assert not [name for name in loaded if name.split(".")[0] == "tongue_seg_model"]