"""lab.py(撮影データのリポジトリ SmTIAS-Lab の場所とファイルのパス)の単体テスト.
仕様:
- SPEC_01: lab.py は SmTIAS-Lab の場所(環境変数 `SMTIAS_LAB` → `../SmTIAS-Lab`)と
実験フォルダ内のパスを返す.`..`・絶対パスは拒否する
- ENV_02: Lab は本リポジトリの隣(`../SmTIAS-Lab`)に clone し,撮影データは
`experiments/<YYYY-MM-DD>_<内容>/raw/`(git の対象外)
- ENV_04: Lab を別の場所に置くときは環境変数 `SMTIAS_LAB` を設定する
テスト方針 (.claude/rules/testing.md):
- pytest を使用
- Lab の実データには依存しない(`SMTIAS_LAB` を tmp_path に向ける).
既定の `../SmTIAS-Lab` と定数のフォルダの実在は,手元に Lab がある場合のみ確かめる
"""
import sys
from pathlib import Path
import pytest
from src import lab
from src.lab import (
LAB_ENV_VAR,
TIAS,
V3_ALL_LEDS,
V3_LOFT_W1P4,
V3_PNG,
V3_SINGLE_LED,
find_lab_file,
lab_file,
lab_path,
lab_root,
raw_file,
)
_EXP = "2026-01-01_test"
_REAL_LAB = Path(__file__).resolve().parents[1].parent / "SmTIAS-Lab"
def _windows_only(value: object) -> object:
"""Windows でだけ成り立つ parametrize のケースにする(他の OS では skip).
lab.py は PurePath(実行 OS のパス規則)で判定するため,`\\` の区切りとドライブ(`C:`)は
Windows でだけパスの構造として解釈され,Linux/macOS ではただのファイル名の文字になる.
"""
return pytest.param(
value,
marks=pytest.mark.skipif(
sys.platform != "win32", reason="\\ の区切り・ドライブは Windows のパス規則"
),
)
@pytest.fixture
def fake_lab(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""SMTIAS_LAB を tmp_path 配下の空の Lab に向ける fixture."""
root = tmp_path / "MyLab"
(root / "experiments" / _EXP / "raw").mkdir(parents=True)
monkeypatch.setenv(LAB_ENV_VAR, str(root))
return root
@pytest.fixture
def fake_repo_with_sibling(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""リポジトリのルートを tmp_path の偽リポジトリに差し替え,隣に SmTIAS-Lab を作る."""
fake_repo = tmp_path / "repos" / "SmTIAS-Evaluation"
fake_repo.mkdir(parents=True)
sibling = tmp_path / "repos" / "SmTIAS-Lab"
sibling.mkdir()
monkeypatch.setattr(lab, "REPO_ROOT", fake_repo)
return sibling
def test_env_var_name_is_smtias_lab() -> None:
"""ENV_04: Lab の場所を変える環境変数は SMTIAS_LAB."""
assert LAB_ENV_VAR == "SMTIAS_LAB"
# ---------------------------------------------------------------------------
# lab_root
# ---------------------------------------------------------------------------
class TestLabRoot:
"""lab_root 関数のテスト群."""
def test_env_var_points_to_lab(self, fake_lab: Path) -> None:
"""正常: SMTIAS_LAB が指すディレクトリを返すこと."""
assert lab_root().resolve() == fake_lab.resolve()
def test_env_var_takes_precedence_over_default(
self, fake_lab: Path, fake_repo_with_sibling: Path
) -> None:
"""優先順: 隣に Lab があっても SMTIAS_LAB が優先されること."""
assert lab_root().resolve() == fake_lab.resolve()
def test_default_is_sibling_smtias_lab(
self, monkeypatch: pytest.MonkeyPatch, fake_repo_with_sibling: Path
) -> None:
"""正常: SMTIAS_LAB 未設定ならリポジトリの隣の SmTIAS-Lab を返すこと."""
monkeypatch.delenv(LAB_ENV_VAR, raising=False)
assert lab_root().resolve() == fake_repo_with_sibling.resolve()
@pytest.mark.parametrize("value", ["", " ", "\t"])
def test_blank_env_var_treated_as_unset(
self, monkeypatch: pytest.MonkeyPatch, fake_repo_with_sibling: Path, value: str
) -> None:
"""境界値: 空・空白だけの SMTIAS_LAB は未設定扱い(既定の ../SmTIAS-Lab を見る)."""
monkeypatch.setenv(LAB_ENV_VAR, value)
assert lab_root().resolve() == fake_repo_with_sibling.resolve()
def test_env_var_missing_dir_raises_with_hint(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""エラー: SMTIAS_LAB の指す先が無いと FileNotFoundError.パスと SMTIAS_LAB を含む."""
missing = tmp_path / "nope"
monkeypatch.setenv(LAB_ENV_VAR, str(missing))
with pytest.raises(FileNotFoundError) as exc:
lab_root()
msg = str(exc.value)
assert str(missing) in msg
assert "SMTIAS_LAB" in msg
def test_env_var_pointing_to_file_raises(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""エラー: SMTIAS_LAB がディレクトリでなくファイルを指すと FileNotFoundError."""
not_dir = tmp_path / "file.txt"
not_dir.write_text("x", encoding="utf-8")
monkeypatch.setenv(LAB_ENV_VAR, str(not_dir))
with pytest.raises(FileNotFoundError):
lab_root()
def test_default_missing_raises_with_hint(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""エラー: 未設定で隣にも Lab が無いと FileNotFoundError.設定方法を案内する."""
monkeypatch.delenv(LAB_ENV_VAR, raising=False)
fake_repo = tmp_path / "SmTIAS-Evaluation"
fake_repo.mkdir()
monkeypatch.setattr(lab, "REPO_ROOT", fake_repo)
with pytest.raises(FileNotFoundError) as exc:
lab_root()
msg = str(exc.value)
assert "SmTIAS-Lab" in msg
assert "SMTIAS_LAB" in msg
# raw/ は git の対象外なので clone だけでは揃わないことを案内する(ENV_02)
assert "raw/" in msg
def test_real_default_points_next_to_repo(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""手元に ../SmTIAS-Lab があれば,未設定時にそこを指すこと."""
monkeypatch.delenv(LAB_ENV_VAR, raising=False)
if not _REAL_LAB.is_dir():
pytest.skip(f"隣に SmTIAS-Lab がありません: {_REAL_LAB}")
assert lab_root().resolve() == _REAL_LAB.resolve()
# ---------------------------------------------------------------------------
# lab_path
# ---------------------------------------------------------------------------
class TestLabPath:
"""lab_path 関数のテスト群."""
def test_joins_experiments_dir(self, fake_lab: Path) -> None:
"""正常: <Lab>/experiments/<実験>/<parts...> を返すこと."""
p = lab_path(_EXP, "raw", "a.dng")
assert p.resolve() == (fake_lab / "experiments" / _EXP / "raw" / "a.dng").resolve()
def test_experiment_only(self, fake_lab: Path) -> None:
"""正常: サブパス無しなら実験フォルダ自体を返すこと."""
assert lab_path(_EXP).resolve() == (fake_lab / "experiments" / _EXP).resolve()
def test_does_not_check_existence(self, fake_lab: Path) -> None:
"""仕様: ファイルの存在は確かめない(無くても例外にならない)."""
p = lab_path(_EXP, "raw", "missing.dng")
assert not p.exists()
def test_nested_relative_part_allowed(self, fake_lab: Path) -> None:
"""正常: 'raw/roi' のような区切りを含む相対パスは受け付けること(TIAS の raw/roi/)."""
p = lab_path(_EXP, "raw/roi", "a.png")
assert p.resolve() == (fake_lab / "experiments" / _EXP / "raw" / "roi" / "a.png").resolve()
def test_missing_lab_raises_file_not_found(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""エラー: Lab 自体が無いと FileNotFoundError(SMTIAS_LAB を案内)."""
monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "nope"))
with pytest.raises(FileNotFoundError, match="SMTIAS_LAB"):
lab_path(_EXP, "raw", "a.dng")
@pytest.mark.parametrize(
"parts",
[
("..",),
("../other",),
(_EXP, ".."),
(_EXP, "raw", "../../x"),
(_EXP, "..", "secret.txt"),
_windows_only((_EXP, "raw\\..\\..\\x")),
],
ids=["dotdot", "dotdot_prefix", "sub_dotdot", "nested_dotdot", "middle", "backslash"],
)
def test_rejects_parent_dir(self, fake_lab: Path, parts: tuple[str, ...]) -> None:
"""エラー: '..' を含むと ValueError(experiments/ の外を指させない)."""
with pytest.raises(ValueError):
lab_path(*parts)
@pytest.mark.parametrize(
"part",
[
"/x",
_windows_only("\\x"),
_windows_only("C:/x"),
_windows_only("C:\\x"),
_windows_only("C:x"),
"/etc/passwd",
],
ids=["slash", "backslash", "drive_slash", "drive_backslash", "drive_relative", "posix"],
)
def test_rejects_absolute_or_rooted(self, fake_lab: Path, part: str) -> None:
"""エラー: 絶対パス・ルート(/ や \\)始まり・ドライブ付きは ValueError."""
with pytest.raises(ValueError):
lab_path(part)
with pytest.raises(ValueError):
lab_path(_EXP, part)
def test_rejects_real_absolute_path(self, fake_lab: Path, tmp_path: Path) -> None:
"""エラー: 実在する絶対パス(tmp_path)も ValueError."""
with pytest.raises(ValueError):
lab_path(str(tmp_path / "abs"))
with pytest.raises(ValueError):
lab_path(_EXP, str(tmp_path / "abs.dng"))
def test_rejects_empty(self, fake_lab: Path) -> None:
"""エラー: 空文字の実験名・サブパスは ValueError."""
with pytest.raises(ValueError):
lab_path("")
with pytest.raises(ValueError):
lab_path(_EXP, "")
def test_validation_before_lab_lookup(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""エラー: 不正なパスは Lab が無くても ValueError(FileNotFoundError ではない)."""
monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "nope"))
with pytest.raises(ValueError):
lab_path("..", "x")
# ---------------------------------------------------------------------------
# lab_file / raw_file / find_lab_file
# ---------------------------------------------------------------------------
class TestLabFile:
"""lab_file 関数のテスト群."""
def test_returns_existing_file(self, fake_lab: Path) -> None:
"""正常: 存在するファイルのパスを返すこと."""
f = fake_lab / "experiments" / _EXP / "raw" / "a.dng"
f.write_bytes(b"x")
assert lab_file(_EXP, "raw", "a.dng").resolve() == f.resolve()
def test_missing_file_raises_with_hint(self, fake_lab: Path) -> None:
"""エラー: ファイルが無いと FileNotFoundError.
メッセージにパス・「raw/ は git の対象外」・SMTIAS_LAB を含む.
"""
with pytest.raises(FileNotFoundError) as exc:
lab_file(_EXP, "raw", "missing.dng")
msg = str(exc.value)
assert "missing.dng" in msg
assert "raw/" in msg
assert "git" in msg
assert "SMTIAS_LAB" in msg
def test_directory_is_not_a_file(self, fake_lab: Path) -> None:
"""エラー: ディレクトリを指すと FileNotFoundError(ファイルではない)."""
with pytest.raises(FileNotFoundError):
lab_file(_EXP, "raw")
def test_missing_lab_raises_file_not_found(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""エラー: Lab 自体が無いと FileNotFoundError(SMTIAS_LAB を案内)."""
monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "nope"))
with pytest.raises(FileNotFoundError, match="SMTIAS_LAB"):
lab_file(_EXP, "raw", "a.dng")
def test_rejects_parent_dir(self, fake_lab: Path) -> None:
"""エラー: '..' は ValueError."""
with pytest.raises(ValueError):
lab_file(_EXP, "..", "x")
class TestRawFile:
"""raw_file 関数のテスト群."""
def test_returns_file_in_raw(self, fake_lab: Path) -> None:
"""正常: <Lab>/experiments/<実験>/raw/<name> を返すこと."""
f = fake_lab / "experiments" / _EXP / "raw" / "b.dng"
f.write_bytes(b"x")
assert raw_file(_EXP, "b.dng").resolve() == f.resolve()
def test_does_not_look_outside_raw(self, fake_lab: Path) -> None:
"""仕様: raw/ の外(実験フォルダ直下)のファイルは見ない."""
(fake_lab / "experiments" / _EXP / "c.dng").write_bytes(b"x")
with pytest.raises(FileNotFoundError):
raw_file(_EXP, "c.dng")
def test_missing_raises(self, fake_lab: Path) -> None:
"""エラー: 無いと FileNotFoundError."""
with pytest.raises(FileNotFoundError, match="SMTIAS_LAB"):
raw_file(_EXP, "missing.dng")
@pytest.mark.parametrize(
"name", ["../x.dng", "/x.dng", _windows_only("\\x.dng"), _windows_only("C:/x.dng"), ""]
)
def test_rejects_invalid_name(self, fake_lab: Path, name: str) -> None:
"""エラー: '..'・ルート始まり・ドライブ付き・空文字は ValueError."""
with pytest.raises(ValueError):
raw_file(_EXP, name)
class TestFindLabFile:
"""find_lab_file 関数のテスト群."""
def test_returns_existing_file(self, fake_lab: Path) -> None:
"""正常: 存在すればパスを返すこと."""
f = fake_lab / "experiments" / _EXP / "raw" / "a.dng"
f.write_bytes(b"x")
assert find_lab_file(_EXP, "raw", "a.dng").resolve() == f.resolve()
def test_missing_file_returns_none(self, fake_lab: Path) -> None:
"""正常: ファイルが無ければ None(例外にしない)."""
assert find_lab_file(_EXP, "raw", "missing.dng") is None
def test_missing_lab_returns_none(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""正常: Lab 自体が無くても None(テストのスキップ判定に使える)."""
monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "nope"))
assert find_lab_file(_EXP, "raw", "a.dng") is None
def test_invalid_path_still_raises_value_error(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""エラー: 不正なパスは None にせず ValueError(Lab が無くても)."""
monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "nope"))
with pytest.raises(ValueError):
find_lab_file("..", "x")
with pytest.raises(ValueError):
find_lab_file(_EXP, "/x")
# ---------------------------------------------------------------------------
# 実験フォルダ名の定数
# ---------------------------------------------------------------------------
_CONSTANTS = [V3_ALL_LEDS, V3_SINGLE_LED, V3_LOFT_W1P4, V3_PNG, TIAS]
@pytest.mark.parametrize("name", _CONSTANTS)
def test_constant_follows_naming_convention(name: str) -> None:
"""ENV_02: 実験フォルダ名は <YYYY-MM-DD>_<内容> で,パスとして有効であること."""
date, _, content = name.partition("_")
assert len(date) == 10 and date[4] == "-" and date[7] == "-"
assert date.replace("-", "").isdigit()
assert content
assert "/" not in name and "\\" not in name
@pytest.mark.parametrize("name", _CONSTANTS)
def test_constant_folder_exists_in_real_lab(monkeypatch: pytest.MonkeyPatch, name: str) -> None:
"""手元の Lab に定数の実験フォルダと raw/ が実在すること(Lab が無ければ skip)."""
monkeypatch.delenv(LAB_ENV_VAR, raising=False)
if not _REAL_LAB.is_dir():
pytest.skip(f"隣に SmTIAS-Lab がありません: {_REAL_LAB}")
folder = lab_path(name)
assert folder.is_dir(), f"Lab に実験フォルダがありません: {folder}"
assert (folder / "raw").is_dir(), f"raw/ がありません: {folder / 'raw'}"