Newer
Older
TongueSegModel / tests / cli / test_export.py
"""`tsm-export --run <実験ID>`(`cli/export.py`)の統合テスト.

期待値は SPEC_01「CLI」「実験の出力」(`checkpoints/ResUNet.onnx`・`metrics.json` は集計値だけで
ファイル名を含まない)と SPEC_02「ONNX の書き出し」(opset 11・入出力の形と型・PyTorch との差を
確かめて記録する),ENV_04 の終了コード(0 成功/1 入力の問題/2 引数の誤り/3 確認を通らなかった.
確認を通らなければ ONNX を置かず `metrics.json` も変えない)を基準にする.

実験フォルダは学習を回さずに作る(`build_model` の state_dict を `best.pth` に保存し,
`config.yaml`・`metrics.json` は run_artifacts・metrics の関数で書く).画像は 64×64.
実際に書き出すテストは `slow`.書き出すたびに約 70MB のファイルができるので,回数を絞り,
テストの後で ONNX を消す.
"""

from __future__ import annotations

import importlib.metadata
import json
import logging
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import pytest
import torch

import tongue_seg_model.cli.export as export_cli
from tongue_seg_model.cli.export import main
from tongue_seg_model.export.check import MAX_ABS_DIFF_TOLERANCE
from tongue_seg_model.models.resunet import build_model
from tongue_seg_model.schema import ExperimentConfig
from tongue_seg_model.training.metrics import build_metrics_document, write_metrics_json
from tongue_seg_model.training.run_artifacts import (
    build_config_document,
    configure_logging,
    create_run_dir,
    write_config_yaml,
)

SIZE = (64, 64)
RUN_ID = "20261119-102030_synthetic_abc1234"
SHA = "0123456789abcdef" * 4
PREVIOUS_LOG_LINE = "previous training log line"


def _close_own_handlers() -> None:
    configure_logging(None)
    root = logging.getLogger()
    for handler in list(root.handlers):
        if handler.get_name() and handler.get_name().startswith("tongue_seg_model."):
            root.removeHandler(handler)
            handler.close()


@pytest.fixture(autouse=True)
def restore_logging() -> Iterator[None]:
    """root logger の状態を戻し,`log.txt` のハンドラを閉じる(Windows での削除失敗を防ぐ)."""
    level = logging.getLogger().level
    yield
    _close_own_handlers()
    logging.getLogger().setLevel(level)


def _config(**overrides: Any) -> ExperimentConfig:
    raw: dict[str, Any] = {
        "data": {"bundle": {"name": "synthetic", "version": 1}, "image_size": list(SIZE)},
        # 学習時の設定は事前学習の重みあり(書き出しでは使わずダウンロードもしないこと)
        "model": {"pretrained": True},
        "train": {"device": "cpu", "seed": 0},
    }
    for section, values in overrides.items():
        raw.setdefault(section, {}).update(values)
    return ExperimentConfig.model_validate(raw)


def _metrics() -> dict[str, Any]:
    return build_metrics_document(
        best_epoch=1,
        best_val_loss=0.5,
        epochs_run=2,
        stopped_early=False,
        test_iou={"count": 2, "mean": 0.5, "median": 0.5, "min": 0.4, "max": 0.6, "std": 0.1},
        counts={"train": 4, "val": 2, "test": 2},
        data_bundle={"name": "synthetic", "version": 1, "manifest_sha256": SHA},
        elapsed_seconds=1.0,
    )


def _make_run(
    runs_dir: Path,
    *,
    config: ExperimentConfig | None = None,
    best_pth: bool = True,
    metrics: bool = True,
) -> Path:
    """学習を回さずに,書き出しに要るものだけをそろえた実験ディレクトリを作る."""
    config = _config() if config is None else config
    run_dir = create_run_dir(runs_dir, RUN_ID)
    write_config_yaml(run_dir, build_config_document(config, run_id=RUN_ID, git_commit="abc1234"))
    if best_pth:
        torch.manual_seed(0)
        model = build_model(config.model.model_copy(update={"pretrained": False}))
        torch.save(model.state_dict(), run_dir / "checkpoints" / "best.pth")
    if metrics:
        write_metrics_json(run_dir / "metrics.json", _metrics())
    (run_dir / "log.txt").write_text(PREVIOUS_LOG_LINE + "\n", encoding="utf-8")
    return run_dir


def _argv(runs_dir: Path, *extra: str, run_id: str = RUN_ID) -> list[str]:
    return ["--run", run_id, "--runs-dir", str(runs_dir), *extra]


def _onnx(run_dir: Path) -> Path:
    return run_dir / "checkpoints" / "ResUNet.onnx"


def _checkpoint_names(run_dir: Path) -> set[str]:
    return {p.name for p in (run_dir / "checkpoints").iterdir()}


def _read_log(run_dir: Path) -> str:
    for handler in logging.getLogger().handlers:
        handler.flush()
    return (run_dir / "log.txt").read_text(encoding="utf-8")


def _strict_json(path: Path) -> Any:
    def _reject(constant: str) -> Any:
        raise AssertionError(f"厳密な JSON でない値 {constant} がある")

    return json.loads(path.read_text(encoding="utf-8"), parse_constant=_reject)


def test_entry_point_is_registered() -> None:
    points = importlib.metadata.entry_points(group="console_scripts", name="tsm-export")
    assert [p.value for p in points] == ["tongue_seg_model.cli.export:main"]


# ---------------------------------------------------------------------------
# 引数の誤り(終了コード 2)
# ---------------------------------------------------------------------------


class TestArgumentErrors:
    def test_missing_run_option_exits_with_2(self) -> None:
        with pytest.raises(SystemExit) as info:
            main([])
        assert info.value.code == 2

    def test_unknown_option_exits_with_2(self, tmp_path: Path) -> None:
        with pytest.raises(SystemExit) as info:
            main([*_argv(tmp_path), "--unknown"])
        assert info.value.code == 2

    def test_overwrite_takes_no_value(self, tmp_path: Path) -> None:
        with pytest.raises(SystemExit) as info:
            main(["--run", RUN_ID, "--overwrite=yes"])
        assert info.value.code == 2


# ---------------------------------------------------------------------------
# 入力の問題(終了コード 1.書き出す前に止まる)
# ---------------------------------------------------------------------------


class TestInputErrors:
    @pytest.mark.parametrize(
        "run_id",
        [
            "..",
            ".",
            "",
            "../" + RUN_ID,
            RUN_ID + "/..",
            "..\\" + RUN_ID,
            RUN_ID + "\n",
            "not-a-run-id",
        ],
    )
    def test_invalid_run_id_exits_with_1(
        self, tmp_path: Path, run_id: str, caplog: pytest.LogCaptureFixture
    ) -> None:
        runs_dir = tmp_path / "runs"
        _make_run(runs_dir, best_pth=False)
        assert main(_argv(runs_dir, run_id=run_id)) == 1
        assert "実験 ID" in caplog.text
        assert "Traceback" not in caplog.text

    def test_parent_dir_run_id_does_not_touch_parent(self, tmp_path: Path) -> None:
        # runs/.. が「実験ディレクトリ」として扱われ,その下に何か作られることがない
        runs_dir = tmp_path / "runs"
        runs_dir.mkdir()
        before = sorted(p.name for p in tmp_path.rglob("*"))
        assert main(_argv(runs_dir, run_id="..")) == 1
        assert sorted(p.name for p in tmp_path.rglob("*")) == before

    def test_missing_run_dir_exits_with_1(
        self, tmp_path: Path, caplog: pytest.LogCaptureFixture
    ) -> None:
        assert main(_argv(tmp_path / "runs")) == 1
        assert "実験ディレクトリが無い" in caplog.text

    def test_missing_config_exits_with_1(
        self, tmp_path: Path, caplog: pytest.LogCaptureFixture
    ) -> None:
        run_dir = _make_run(tmp_path, best_pth=False)
        (run_dir / "config.yaml").unlink()
        assert main(_argv(tmp_path)) == 1
        assert "config.yaml" in caplog.text

    def test_invalid_config_content_exits_with_1(self, tmp_path: Path) -> None:
        # pydantic の ValidationError も ValueError の一種として終了コード 1
        run_dir = _make_run(tmp_path, best_pth=False)
        (run_dir / "config.yaml").write_text(
            "config:\n  data:\n    bundle: {name: synthetic, version: 1}\n  export: {opset: 3}\n",
            encoding="utf-8",
        )
        assert main(_argv(tmp_path)) == 1

    def test_image_size_not_multiple_of_32_exits_with_1(
        self, tmp_path: Path, caplog: pytest.LogCaptureFixture
    ) -> None:
        config = _config(
            data={"bundle": {"name": "synthetic", "version": 1}, "image_size": [48, 64]}
        )
        _make_run(tmp_path, config=config, best_pth=False)
        assert main(_argv(tmp_path)) == 1
        assert "32" in caplog.text

    def test_missing_best_pth_exits_with_1(
        self, tmp_path: Path, caplog: pytest.LogCaptureFixture
    ) -> None:
        run_dir = _make_run(tmp_path, best_pth=False)
        assert main(_argv(tmp_path)) == 1
        assert "best.pth" in caplog.text
        assert _checkpoint_names(run_dir) == set()

    def test_broken_best_pth_exits_with_1(self, tmp_path: Path) -> None:
        run_dir = _make_run(tmp_path, best_pth=False)
        (run_dir / "checkpoints" / "best.pth").write_bytes(b"not a checkpoint")
        assert main(_argv(tmp_path)) == 1
        assert _checkpoint_names(run_dir) == {"best.pth"}

    def test_mismatched_best_pth_exits_with_1(self, tmp_path: Path) -> None:
        run_dir = _make_run(tmp_path, best_pth=False)
        torch.save({"unexpected.weight": torch.zeros(1)}, run_dir / "checkpoints" / "best.pth")
        assert main(_argv(tmp_path)) == 1
        assert _checkpoint_names(run_dir) == {"best.pth"}

    def test_missing_metrics_exits_with_1(
        self, tmp_path: Path, caplog: pytest.LogCaptureFixture
    ) -> None:
        run_dir = _make_run(tmp_path, metrics=False)
        assert main(_argv(tmp_path)) == 1
        assert "metrics.json" in caplog.text
        assert _checkpoint_names(run_dir) == {"best.pth"}
        assert not (run_dir / "metrics.json").exists()

    @pytest.mark.parametrize("text", ["{broken", "[1, 2]", '"text"'])
    def test_unreadable_metrics_exits_with_1(self, tmp_path: Path, text: str) -> None:
        run_dir = _make_run(tmp_path)
        (run_dir / "metrics.json").write_text(text, encoding="utf-8")
        assert main(_argv(tmp_path)) == 1
        assert (run_dir / "metrics.json").read_text(encoding="utf-8") == text
        assert _checkpoint_names(run_dir) == {"best.pth"}

    def test_existing_onnx_without_overwrite_exits_with_1(
        self, tmp_path: Path, caplog: pytest.LogCaptureFixture
    ) -> None:
        run_dir = _make_run(tmp_path)
        _onnx(run_dir).write_bytes(b"old onnx")
        metrics_before = (run_dir / "metrics.json").read_bytes()
        assert main(_argv(tmp_path)) == 1
        assert "--overwrite" in caplog.text
        assert _onnx(run_dir).read_bytes() == b"old onnx"
        assert (run_dir / "metrics.json").read_bytes() == metrics_before

    def test_error_is_appended_to_log_txt(self, tmp_path: Path) -> None:
        run_dir = _make_run(tmp_path, best_pth=False)
        assert main(_argv(tmp_path)) == 1
        log = _read_log(run_dir)
        assert log.startswith(PREVIOUS_LOG_LINE + "\n")
        assert "best.pth" in log

    def test_nothing_written_to_stdout_on_error(
        self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        _make_run(tmp_path, best_pth=False)
        assert main(_argv(tmp_path)) == 1
        assert capsys.readouterr().out == ""


# ---------------------------------------------------------------------------
# 書き出しの成功(終了コード 0.slow)
# ---------------------------------------------------------------------------


@dataclass(frozen=True)
class ExportedRun:
    run_dir: Path
    runs_dir: Path
    exit_code: int
    stdout: str
    metrics_before: dict[str, Any]


@pytest.fixture(scope="module")
def exported_run(tmp_path_factory: pytest.TempPathFactory) -> Iterator[ExportedRun]:
    """実験フォルダを作り,`tsm-export` を 1 回通す(このモジュールの成功系で共有する)."""
    import contextlib
    import io

    runs_dir = tmp_path_factory.mktemp("export") / "runs"
    run_dir = _make_run(runs_dir)
    metrics_before = _strict_json(run_dir / "metrics.json")
    level = logging.getLogger().level
    stdout = io.StringIO()
    try:
        with contextlib.redirect_stdout(stdout):
            code = main(_argv(runs_dir))
        _close_own_handlers()
        yield ExportedRun(
            run_dir=run_dir,
            runs_dir=runs_dir,
            exit_code=code,
            stdout=stdout.getvalue(),
            metrics_before=metrics_before,
        )
    finally:
        _close_own_handlers()
        logging.getLogger().setLevel(level)
        _onnx(run_dir).unlink(missing_ok=True)


@pytest.mark.slow
class TestExportSucceeds:
    def test_exit_code_is_0(self, exported_run: ExportedRun) -> None:
        assert exported_run.exit_code == 0

    def test_prints_onnx_path_on_one_line(self, exported_run: ExportedRun) -> None:
        assert exported_run.stdout == f"{_onnx(exported_run.run_dir)}\n"

    def test_onnx_is_placed_and_temp_file_removed(self, exported_run: ExportedRun) -> None:
        assert _onnx(exported_run.run_dir).is_file()
        assert _checkpoint_names(exported_run.run_dir) == {"best.pth", "ResUNet.onnx"}

    def test_run_dir_has_no_other_new_files(self, exported_run: ExportedRun) -> None:
        names = {p.name for p in exported_run.run_dir.iterdir()}
        assert names == {"config.yaml", "metrics.json", "log.txt", "figures", "checkpoints"}
        assert list((exported_run.run_dir / "figures").iterdir()) == []

    def test_metrics_keeps_existing_keys(self, exported_run: ExportedRun) -> None:
        metrics = _strict_json(exported_run.run_dir / "metrics.json")
        assert {k: v for k, v in metrics.items() if k != "export"} == exported_run.metrics_before

    def test_metrics_export_record(self, exported_run: ExportedRun) -> None:
        record = _strict_json(exported_run.run_dir / "metrics.json")["export"]
        assert record["onnx_file"] == "checkpoints/ResUNet.onnx"
        assert record["opset"] == 11
        assert len(record["inputs"]) == 1
        assert len(record["outputs"]) == 1
        assert record["inputs"][0]["shape"] == [1, 3, *SIZE]
        assert record["inputs"][0]["dtype"] == "float32"
        assert record["outputs"][0]["shape"] == [1, 2, *SIZE]
        assert record["outputs"][0]["dtype"] == "float32"
        # 名前は記録する(合わせ込みはしない)
        assert isinstance(record["inputs"][0]["name"], str) and record["inputs"][0]["name"]
        assert isinstance(record["outputs"][0]["name"], str) and record["outputs"][0]["name"]
        assert 0.0 <= record["max_abs_diff"] <= MAX_ABS_DIFF_TOLERANCE
        assert record["tolerance"] == MAX_ABS_DIFF_TOLERANCE
        assert record["file_bytes"] == _onnx(exported_run.run_dir).stat().st_size
        assert record["elapsed_seconds"] > 0
        assert record["torch_version"] == torch.__version__
        assert isinstance(record["check_input_seed"], int)

    def test_metrics_has_no_absolute_paths(self, exported_run: ExportedRun) -> None:
        text = (exported_run.run_dir / "metrics.json").read_text(encoding="utf-8")
        assert str(exported_run.runs_dir) not in text
        assert str(exported_run.runs_dir).replace("\\", "\\\\") not in text
        assert exported_run.runs_dir.as_posix() not in text

    def test_log_txt_is_appended(self, exported_run: ExportedRun) -> None:
        log = (exported_run.run_dir / "log.txt").read_text(encoding="utf-8")
        assert log.startswith(PREVIOUS_LOG_LINE + "\n")
        assert "ONNX" in log
        assert "opset 11" in log

    def test_exported_onnx_runs_and_matches_record(self, exported_run: ExportedRun) -> None:
        from tongue_seg_model.export.check import make_check_input
        from tongue_seg_model.export.onnx_export import read_onnx_info, run_onnxruntime

        path = _onnx(exported_run.run_dir)
        info = read_onnx_info(path)
        record = _strict_json(exported_run.run_dir / "metrics.json")["export"]
        assert [s.to_dict() for s in info.inputs] == record["inputs"]
        assert [s.to_dict() for s in info.outputs] == record["outputs"]
        y = run_onnxruntime(path, make_check_input((1, 3, *SIZE), 0))
        assert y.shape == (1, 2, *SIZE)

    def test_onnx_uses_best_pth_weights(self, exported_run: ExportedRun) -> None:
        # best.pth の重みで書き出していること(PyTorch に best.pth を読ませた出力と一致)
        from tongue_seg_model.export.check import make_check_input, max_abs_diff
        from tongue_seg_model.export.onnx_export import run_onnxruntime, run_pytorch
        from tongue_seg_model.models.resunet import ResUNet

        model = ResUNet(pretrained=False)
        state = torch.load(
            exported_run.run_dir / "checkpoints" / "best.pth", map_location="cpu", weights_only=True
        )
        model.load_state_dict(state)
        x = make_check_input((1, 3, *SIZE), 5)
        diff = max_abs_diff(run_pytorch(model, x), run_onnxruntime(_onnx(exported_run.run_dir), x))
        assert diff <= MAX_ABS_DIFF_TOLERANCE

    def test_second_run_without_overwrite_exits_with_1(self, exported_run: ExportedRun) -> None:
        path = _onnx(exported_run.run_dir)
        before = (path.stat().st_mtime_ns, path.stat().st_size)
        metrics_before = (exported_run.run_dir / "metrics.json").read_bytes()
        assert main(_argv(exported_run.runs_dir)) == 1
        assert (path.stat().st_mtime_ns, path.stat().st_size) == before
        assert (exported_run.run_dir / "metrics.json").read_bytes() == metrics_before


@pytest.mark.slow
def test_overwrite_replaces_existing_onnx(tmp_path: Path) -> None:
    run_dir = _make_run(tmp_path)
    _onnx(run_dir).write_bytes(b"old onnx")
    try:
        assert main(_argv(tmp_path, "--overwrite")) == 0
        assert _onnx(run_dir).read_bytes() != b"old onnx"
        assert _onnx(run_dir).stat().st_size > 1000
        assert _checkpoint_names(run_dir) == {"best.pth", "ResUNet.onnx"}
        record = _strict_json(run_dir / "metrics.json")["export"]
        assert record["file_bytes"] == _onnx(run_dir).stat().st_size
    finally:
        _close_own_handlers()
        _onnx(run_dir).unlink(missing_ok=True)


# ---------------------------------------------------------------------------
# 確認を通らない(終了コード 3.slow)
# ---------------------------------------------------------------------------


def _force_check_failure(monkeypatch: pytest.MonkeyPatch) -> None:
    original = export_cli.find_export_problems

    def failing(*args: Any, **kwargs: Any) -> list[str]:
        kwargs["tolerance"] = -1.0  # 差 0 でも通らない
        return original(*args, **kwargs)

    monkeypatch.setattr(export_cli, "find_export_problems", failing)


@pytest.mark.slow
def test_failed_check_exits_with_3_and_leaves_nothing(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    caplog: pytest.LogCaptureFixture,
    capsys: pytest.CaptureFixture[str],
) -> None:
    run_dir = _make_run(tmp_path)
    metrics_before = (run_dir / "metrics.json").read_bytes()
    _force_check_failure(monkeypatch)
    try:
        assert main(_argv(tmp_path)) == 3
        # ONNX(一時ファイルも)を置かず,metrics.json も変えない
        assert _checkpoint_names(run_dir) == {"best.pth"}
        assert (run_dir / "metrics.json").read_bytes() == metrics_before
        assert "確認を通らなかった" in caplog.text
        assert "絶対差" in caplog.text
        assert str(_onnx(run_dir)) not in capsys.readouterr().out
        log = _read_log(run_dir)
        assert log.startswith(PREVIOUS_LOG_LINE + "\n")
        assert "確認を通らなかった" in log
    finally:
        _close_own_handlers()
        for path in (run_dir / "checkpoints").glob("*.onnx"):
            path.unlink()


@pytest.mark.slow
def test_failed_check_with_overwrite_keeps_old_onnx(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    run_dir = _make_run(tmp_path)
    _onnx(run_dir).write_bytes(b"old onnx")
    metrics_before = (run_dir / "metrics.json").read_bytes()
    _force_check_failure(monkeypatch)
    try:
        assert main(_argv(tmp_path, "--overwrite")) == 3
        assert _onnx(run_dir).read_bytes() == b"old onnx"
        assert _checkpoint_names(run_dir) == {"best.pth", "ResUNet.onnx"}
        assert (run_dir / "metrics.json").read_bytes() == metrics_before
    finally:
        _close_own_handlers()
        for path in (run_dir / "checkpoints").glob("*.onnx"):
            path.unlink()


@pytest.mark.slow
def test_unsupported_opset_exits_with_1_and_leaves_no_temp_file(
    tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
    # 設定の export.opset(7 以上で受け付ける)で書き出せない場合は設定の問題として 1
    run_dir = _make_run(tmp_path, config=_config(export={"opset": 10}))
    metrics_before = (run_dir / "metrics.json").read_bytes()
    try:
        assert main(_argv(tmp_path)) == 1
        assert "opset 10" in caplog.text
        assert _checkpoint_names(run_dir) == {"best.pth"}
        assert (run_dir / "metrics.json").read_bytes() == metrics_before
    finally:
        _close_own_handlers()