Newer
Older
TongueSegModel / tests / training / test_run_artifacts.py
"""実験の出力 `runs/<実験ID>/` の土台(`training/run_artifacts.py`)のテスト.

期待値は SPEC_01「実験の出力」を基準にする.ファイル I/O はすべて `tmp_path` で行う.
"""

from __future__ import annotations

import logging
import re
from collections.abc import Iterator
from datetime import datetime
from pathlib import Path
from typing import Any

import pytest
import yaml

from tongue_seg_model.schema import ExperimentConfig
from tongue_seg_model.training.run_artifacts import (
    CHECKPOINTS_DIRNAME,
    CONFIG_FILENAME,
    FIGURES_DIRNAME,
    GIT_COMMIT_ENV_VAR,
    LOG_FILENAME,
    NO_GIT,
    BundleFingerprint,
    build_config_document,
    configure_logging,
    create_run_dir,
    make_run_id,
    resolve_git_commit,
    write_config_yaml,
)

SHA = "0123456789abcdef" * 4
RUN_ID_RE = re.compile(r"^\d{8}-\d{6}_[A-Za-z0-9][A-Za-z0-9._-]*_[A-Za-z0-9][A-Za-z0-9_-]*$")


def _config(**sections: Any) -> ExperimentConfig:
    raw: dict[str, Any] = {"data": {"bundle": {"name": "synthetic", "version": 1}}}
    raw.update(sections)
    return ExperimentConfig.model_validate(raw)


@pytest.fixture
def restore_logging() -> Iterator[None]:
    """root logger の状態を戻し,`log.txt` のハンドラを閉じる(Windows での削除失敗を防ぐ)."""
    root = logging.getLogger()
    level = root.level
    yield
    configure_logging(None)
    for handler in list(root.handlers):
        if handler.get_name() and handler.get_name().startswith("tongue_seg_model."):
            root.removeHandler(handler)
            handler.close()
    root.setLevel(level)


# ---------------------------------------------------------------------------
# 定数(SPEC_01 のファイル名)
# ---------------------------------------------------------------------------


def test_artifact_names_match_spec01() -> None:
    assert CONFIG_FILENAME == "config.yaml"
    assert LOG_FILENAME == "log.txt"
    assert FIGURES_DIRNAME == "figures"
    assert CHECKPOINTS_DIRNAME == "checkpoints"
    assert NO_GIT == "nogit"


# ---------------------------------------------------------------------------
# resolve_git_commit
# ---------------------------------------------------------------------------


class TestResolveGitCommit:
    def test_returns_nogit_without_env_var(self) -> None:
        assert resolve_git_commit({}) == "nogit"

    def test_returns_nogit_for_empty_value(self) -> None:
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: ""}) == "nogit"
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: "   "}) == "nogit"

    def test_returns_short_hash(self) -> None:
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: "a1b2c3d"}) == "a1b2c3d"

    def test_accepts_dirty_suffix(self) -> None:
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: "a1b2c3d-dirty"}) == "a1b2c3d-dirty"

    def test_strips_surrounding_whitespace(self) -> None:
        assert resolve_git_commit({GIT_COMMIT_ENV_VAR: " a1b2c3d\n"}) == "a1b2c3d"

    @pytest.mark.parametrize(
        "value",
        [
            "../evil",
            "a1b2c3d/x",
            "a1b2 c3d",
            "-dirty",
            "a1b2c3d;rm",
            "a" * 65,
        ],
    )
    def test_rejects_invalid_hash(self, value: str) -> None:
        with pytest.raises(ValueError):
            resolve_git_commit({GIT_COMMIT_ENV_VAR: value})

    def test_reads_os_environ_by_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setenv(GIT_COMMIT_ENV_VAR, "deadbee")
        assert resolve_git_commit() == "deadbee"
        monkeypatch.delenv(GIT_COMMIT_ENV_VAR)
        assert resolve_git_commit() == "nogit"


# ---------------------------------------------------------------------------
# make_run_id
# ---------------------------------------------------------------------------


class TestMakeRunId:
    def test_format_is_timestamp_config_name_and_hash(self) -> None:
        run_id = make_run_id(datetime(2026, 11, 18, 9, 5, 7), "resunet", "a1b2c3d")
        assert run_id == "20261118-090507_resunet_a1b2c3d"

    def test_includes_dirty_suffix(self) -> None:
        run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "synthetic", "a1b2c3d-dirty")
        assert run_id == "20260102-030405_synthetic_a1b2c3d-dirty"
        assert RUN_ID_RE.match(run_id)

    def test_includes_nogit(self) -> None:
        run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "synthetic", NO_GIT)
        assert run_id.endswith("_synthetic_nogit")

    def test_config_name_from_path_stem(self) -> None:
        stem = Path("configs/resunet.yaml").stem
        assert make_run_id(datetime(2026, 1, 1), stem, "abc1234") == (
            "20260101-000000_resunet_abc1234"
        )

    @pytest.mark.parametrize("name", ["", "../x", "a/b", "a b", "a\\b"])
    def test_rejects_unsafe_config_name(self, name: str) -> None:
        with pytest.raises(ValueError):
            make_run_id(datetime(2026, 1, 1), name, "abc1234")

    @pytest.mark.parametrize("commit", ["", "../x", "a/b"])
    def test_rejects_unsafe_git_commit(self, commit: str) -> None:
        with pytest.raises(ValueError):
            make_run_id(datetime(2026, 1, 1), "resunet", commit)


# ---------------------------------------------------------------------------
# create_run_dir
# ---------------------------------------------------------------------------


class TestCreateRunDir:
    def test_creates_run_dir_with_figures_and_checkpoints(self, tmp_path: Path) -> None:
        out_dir = tmp_path / "runs"
        run_dir = create_run_dir(out_dir, "20260101-000000_synthetic_nogit")
        assert run_dir == out_dir / "20260101-000000_synthetic_nogit"
        assert run_dir.is_dir()
        assert (run_dir / "figures").is_dir()
        assert (run_dir / "checkpoints").is_dir()

    def test_creates_missing_parent_out_dir(self, tmp_path: Path) -> None:
        out_dir = tmp_path / "nested" / "runs"
        run_dir = create_run_dir(out_dir, "rid")
        assert run_dir.is_dir()

    def test_does_not_overwrite_existing_run_dir(self, tmp_path: Path) -> None:
        run_dir = create_run_dir(tmp_path, "rid")
        marker = run_dir / CONFIG_FILENAME
        marker.write_text("original", encoding="utf-8")
        with pytest.raises(ValueError):
            create_run_dir(tmp_path, "rid")
        assert marker.read_text(encoding="utf-8") == "original"

    def test_existing_dir_without_subdirs_is_also_refused(self, tmp_path: Path) -> None:
        (tmp_path / "rid").mkdir()
        with pytest.raises(ValueError):
            create_run_dir(tmp_path, "rid")


# ---------------------------------------------------------------------------
# BundleFingerprint
# ---------------------------------------------------------------------------


class TestBundleFingerprint:
    def test_to_dict(self) -> None:
        fp = BundleFingerprint("synthetic", 1, SHA)
        assert fp.to_dict() == {"name": "synthetic", "version": 1, "manifest_sha256": SHA}

    @pytest.mark.parametrize(
        ("name", "version", "sha"),
        [
            ("", 1, SHA),
            ("a", 0, SHA),
            ("a", True, SHA),
            ("a", "1", SHA),
            ("a", 1, SHA[:-1]),
            ("a", 1, SHA.upper()),
            ("a", 1, "g" * 64),
        ],
    )
    def test_rejects_invalid_values(self, name: str, version: Any, sha: str) -> None:
        with pytest.raises(ValueError):
            BundleFingerprint(name, version, sha)


# ---------------------------------------------------------------------------
# build_config_document / write_config_yaml
# ---------------------------------------------------------------------------


class TestConfigDocument:
    def test_contains_run_record(self) -> None:
        config = _config(train={"seed": 7})
        fp = BundleFingerprint("synthetic", 1, SHA)
        doc = build_config_document(
            config, run_id="rid", git_commit="a1b2c3d-dirty", data_bundle=fp
        )
        assert doc["run"] == {
            "id": "rid",
            "git_commit": "a1b2c3d-dirty",
            "seed": 7,
            "data_bundle": {"name": "synthetic", "version": 1, "manifest_sha256": SHA},
        }

    def test_bundle_fingerprint_defaults_to_null(self) -> None:
        doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT)
        assert doc["run"]["data_bundle"] is None
        assert doc["run"]["git_commit"] == "nogit"
        assert doc["run"]["seed"] == 2021

    def test_config_contains_all_resolved_items(self) -> None:
        doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT)
        cfg = doc["config"]
        assert set(cfg) == {"data", "augment", "model", "loss", "train", "export", "run"}
        # 書いていない項目も既定値で埋まっている
        assert cfg["train"]["batch_size"] == 16
        assert cfg["train"]["learning_rate"] == pytest.approx(1e-4)
        assert cfg["train"]["max_epochs"] == 300
        assert cfg["train"]["early_stopping_patience"] == 30
        assert cfg["loss"] == {"bce_weight": 0.5, "bce_input": "sigmoid"}
        assert cfg["augment"]["hflip_prob"] == 0.5
        assert cfg["export"]["opset"] == 11
        assert list(cfg["data"]["image_size"]) == [256, 256]

    def test_written_yaml_round_trips(self, tmp_path: Path) -> None:
        config = _config(
            model={"pretrained": False},
            train={"batch_size": 4, "max_epochs": 3, "device": "cpu"},
            run={"out_dir": str(tmp_path / "runs")},
        )
        fp = BundleFingerprint("synthetic", 1, SHA)
        doc = build_config_document(config, run_id="rid", git_commit="abc1234", data_bundle=fp)
        path = write_config_yaml(tmp_path, doc)

        assert path == tmp_path / "config.yaml"
        loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
        assert loaded["run"] == {
            "id": "rid",
            "git_commit": "abc1234",
            "seed": 2021,
            "data_bundle": {"name": "synthetic", "version": 1, "manifest_sha256": SHA},
        }
        # 書き出した設定をスキーマで読み戻すと元と同じ設定になる
        assert ExperimentConfig.model_validate(loaded["config"]) == config

    def test_written_yaml_has_null_bundle_when_absent(self, tmp_path: Path) -> None:
        doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT)
        path = write_config_yaml(tmp_path, doc)
        text = path.read_text(encoding="utf-8")
        loaded = yaml.safe_load(text)
        assert "data_bundle" in loaded["run"]
        assert loaded["run"]["data_bundle"] is None


# ---------------------------------------------------------------------------
# configure_logging
# ---------------------------------------------------------------------------


def _own_handlers() -> list[logging.Handler]:
    return [
        h
        for h in logging.getLogger().handlers
        if h.get_name() and h.get_name().startswith("tongue_seg_model.")
    ]


@pytest.mark.usefixtures("restore_logging")
class TestConfigureLogging:
    def test_writes_to_log_txt(self, tmp_path: Path) -> None:
        configure_logging(tmp_path)
        logging.getLogger("tongue_seg_model.test").info("hello-log-file")
        for h in _own_handlers():
            h.flush()
        text = (tmp_path / "log.txt").read_text(encoding="utf-8")
        assert "hello-log-file" in text

    def test_writes_to_stderr_not_stdout(
        self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        configure_logging(tmp_path)
        logging.getLogger("tongue_seg_model.test").info("hello-console")
        captured = capsys.readouterr()
        assert "hello-console" in captured.err
        assert "hello-console" not in captured.out

    def test_calling_twice_does_not_duplicate_handlers(self, tmp_path: Path) -> None:
        configure_logging(tmp_path)
        configure_logging(tmp_path)
        assert len(_own_handlers()) == 2
        logging.getLogger("tongue_seg_model.test").info("only-once")
        for h in _own_handlers():
            h.flush()
        text = (tmp_path / "log.txt").read_text(encoding="utf-8")
        assert text.count("only-once") == 1

    def test_switching_run_dir_moves_file_output(self, tmp_path: Path) -> None:
        first = tmp_path / "first"
        second = tmp_path / "second"
        first.mkdir()
        second.mkdir()
        configure_logging(first)
        configure_logging(second)
        logging.getLogger("tongue_seg_model.test").info("to-second")
        for h in _own_handlers():
            h.flush()
        assert "to-second" in (second / "log.txt").read_text(encoding="utf-8")
        assert "to-second" not in (first / "log.txt").read_text(encoding="utf-8")

    def test_without_run_dir_only_console(self, tmp_path: Path) -> None:
        configure_logging(tmp_path)
        configure_logging(None)
        handlers = _own_handlers()
        assert len(handlers) == 1
        assert not isinstance(handlers[0], logging.FileHandler)

    def test_does_not_remove_foreign_handlers(self, tmp_path: Path) -> None:
        root = logging.getLogger()
        foreign = logging.NullHandler()
        root.addHandler(foreign)
        try:
            configure_logging(tmp_path)
            configure_logging(tmp_path)
            assert foreign in root.handlers
        finally:
            root.removeHandler(foreign)

    def test_sets_level(self, tmp_path: Path) -> None:
        configure_logging(tmp_path, level=logging.WARNING)
        assert logging.getLogger().level == logging.WARNING
        logging.getLogger("tongue_seg_model.test").info("suppressed-info")
        for h in _own_handlers():
            h.flush()
        assert "suppressed-info" not in (tmp_path / "log.txt").read_text(encoding="utf-8")