Newer
Older
TIASJudgeModel / tests / conftest.py
"""テスト全体で共有するフィクスチャ.

セグメンテーションのテスト(segmentation・evaluation・cli)で使うダミーの ONNX モデル
(`scripts/make_dummy_seg_models.py`.入出力の形だけを本物に合わせたもの)と,
合成データ生成スクリプト(`scripts/make_synthetic_segmentation.py`)の読み込み.
"""

from __future__ import annotations

import importlib.util
import sys
from pathlib import Path
from types import ModuleType

import pytest

SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts"


def load_script(name: str) -> ModuleType:
    """`scripts/<name>.py` をモジュールとして読み込む."""
    module_name = f"_test_script_{name}"
    if module_name in sys.modules:
        return sys.modules[module_name]
    spec = importlib.util.spec_from_file_location(module_name, SCRIPTS_DIR / f"{name}.py")
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module


@pytest.fixture(scope="session")
def dummy_seg_models(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Path]:
    """ダミーの ResUNet・検出モデルの ONNX を書き出し,そのパスを返す."""
    onnx = pytest.importorskip("onnx")
    script = load_script("make_dummy_seg_models")
    out = tmp_path_factory.mktemp("dummy_seg_models")
    onnx.save(script.build_resunet(), out / "ResUNet.onnx")
    onnx.save(script.build_detector(), out / "Detection_Normal.onnx")
    return {
        "root": out,
        "resunet": out / "ResUNet.onnx",
        "detector": out / "Detection_Normal.onnx",
    }


@pytest.fixture(scope="session")
def script_loader():
    """`scripts/<name>.py` を読み込む関数(`load_script`)を返す."""
    return load_script