Newer
Older
TIASJudgeModel / tests / data / test_bundle.py
"""TIASDataHub のバンドルからの読み込み(`data/bundle.py`)のテスト.

仕様(SPEC の更新前のため確定した仕様として扱う):

- `BundleRow` → `ManifestRecord`: `image_path` は `files/` を除いた `<sha256>.png`,`patient_id` は
  `subject_id`,`label`・`severity` は所見 `tongue_color`.欠け・不正は ValueError
- 例外・ログに患者 ID・ハッシュ・パスを出さない(行番号と件数のみ).
  `verify()` の例外のハッシュも伏せる
- `load_dataset_source`: bundle なら records・images_dir(`<バンドル>/files`)・指紋.
  root なら指紋は None
- `tiasdata` の import は `data/bundle.py` だけ

バンドルは `tmp_path` に作る合成のもの(臨床データは使わない).
"""

from __future__ import annotations

import hashlib
import json
import logging
import re
from collections.abc import Callable
from pathlib import Path

import pytest
import tiasdata
from PIL import Image

from tias_judge_model.data.bundle import load_dataset_source, records_from_bundle_rows
from tias_judge_model.data.manifest import (
    ManifestRecord,
    resolve_image_path,
    write_manifest,
)
from tias_judge_model.schema import DataConfig

SECRET = "SECRETSUBJ"
SHA_A = "a" * 64
SHA_B = "b" * 64
FULL_HASH = re.compile(r"[0-9a-f]{12,}")
SRC_DIR = Path(__file__).resolve().parents[2] / "src" / "tias_judge_model"


def _row(
    sha256: str = SHA_A,
    *,
    subject_id: str = f"{SECRET}1",
    label: str | None = "red",
    severity: str | None = "mild",
    kind: str = "tongue_crop_masked",
    path: str | None = None,
    annotations: dict | None = None,
) -> tiasdata.BundleRow:
    return tiasdata.BundleRow(
        path=f"files/{sha256}.png" if path is None else path,
        sha256=sha256,
        kind=kind,
        subject_id=subject_id,
        capture_id="C0001",
        annotations=(
            {"tongue_color": {"label": label, "severity": severity}}
            if annotations is None
            else annotations
        ),
    )


def _assert_no_identifiers(text: str) -> None:
    assert SECRET not in text
    assert SHA_A not in text and SHA_A[:12] not in text
    assert SHA_B not in text and SHA_B[:12] not in text


# --- records_from_bundle_rows -------------------------------------------------------------------


def test_rows_become_manifest_records_in_order() -> None:
    rows = [
        _row(SHA_B, subject_id="s2", label="purple", severity="strong"),
        _row(SHA_A, subject_id="s1", label="light_red", severity="normal"),
    ]
    assert records_from_bundle_rows(rows) == [
        ManifestRecord(f"{SHA_B}.png", "s2", "purple", "strong", ""),
        ManifestRecord(f"{SHA_A}.png", "s1", "light_red", "normal", ""),
    ]


def test_rows_accept_any_iterable() -> None:
    assert len(records_from_bundle_rows(iter([_row()]))) == 1


def test_rows_allow_multiple_labels_for_one_subject() -> None:
    rows = [_row(SHA_A, label="red"), _row(SHA_B, label="purple")]
    records = records_from_bundle_rows(rows)
    assert {r.patient_id for r in records} == {f"{SECRET}1"}
    assert [r.label for r in records] == ["red", "purple"]


def test_rows_ignore_other_annotations() -> None:
    row = _row(
        annotations={
            "tongue_color": {"label": "red", "severity": "mild"},
            "other": {"value": "x"},
        }
    )
    assert records_from_bundle_rows([row])[0].label == "red"


def test_empty_rows_are_rejected() -> None:
    with pytest.raises(ValueError):
        records_from_bundle_rows([])


BAD_ROWS = {
    "other_kind": _row(kind="tongue_crop"),
    "jpg": _row(path=f"files/{SHA_A}.jpg"),
    "upper_case_png": _row(path=f"files/{SHA_A}.PNG"),
    "not_under_files": _row(path=f"other/{SHA_A}.png"),
    "nested_path": _row(path=f"files/x/{SHA_A}.png"),
    "no_annotation": _row(annotations={}),
    "other_annotation_only": _row(annotations={"other": {"label": "red", "severity": "mild"}}),
    "empty_label": _row(label=None),
    "empty_severity": _row(severity=None),
    "label_column_missing": _row(annotations={"tongue_color": {"severity": "mild"}}),
    "severity_column_missing": _row(annotations={"tongue_color": {"label": "red"}}),
    "unknown_label": _row(label="orange"),
    "unknown_severity": _row(severity="weak"),
    "invalid_combination": _row(label="light_red", severity="strong"),
    "empty_subject": _row(subject_id=""),
}


@pytest.mark.parametrize("name", list(BAD_ROWS))
def test_bad_row_raises_without_identifiers(name: str) -> None:
    # 2 行目の正常な行のあとに不正な行を置く(黙って除外しない)
    with pytest.raises(ValueError) as excinfo:
        records_from_bundle_rows([_row(SHA_B, subject_id=f"{SECRET}0"), BAD_ROWS[name]])
    message = str(excinfo.value)
    _assert_no_identifiers(message)
    assert "3" in message, "行番号(見出しを 1 行目として 3 行目)で示す"


def test_bad_rows_are_counted_and_first_line_is_shown() -> None:
    rows = [_row(SHA_A), _row(SHA_A, kind="x"), _row(SHA_B, kind="x")]
    with pytest.raises(ValueError) as excinfo:
        records_from_bundle_rows(rows)
    message = str(excinfo.value)
    assert "2 件" in message
    assert "3 行目" in message
    _assert_no_identifiers(message)


# --- load_dataset_source(bundle) ----------------------------------------------------------------


def _png_bytes(tmp_path: Path, color: tuple[int, int, int]) -> bytes:
    path = tmp_path / "one.png"
    Image.new("RGB", (8, 8), color).save(path)
    return path.read_bytes()


@pytest.fixture
def bundle(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bundle_writer: Callable) -> dict:
    items = [
        {
            "data": _png_bytes(tmp_path, (200, 40, 40)),
            "subject_id": f"{SECRET}2",
            "label": "red",
            "severity": "mild",
        },
        {
            "data": _png_bytes(tmp_path, (100, 40, 140)),
            "subject_id": f"{SECRET}1",
            "label": "purple",
            "severity": "strong",
        },
        {
            "data": _png_bytes(tmp_path, (110, 40, 150)),
            "subject_id": f"{SECRET}1",
            "label": "light_red",
            "severity": "normal",
        },
    ]
    bundles_dir = tmp_path / "bundles"
    root = bundle_writer(bundles_dir, items)
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles_dir))
    hashes = sorted(hashlib.sha256(item["data"]).hexdigest() for item in items)
    return {"root": root, "items": items, "hashes": hashes, "bundles_dir": bundles_dir}


def _bundle_data(name: str = "tongue_color", version: int = 1) -> DataConfig:
    return DataConfig.model_validate({"bundle": {"name": name, "version": version}})


def _assert_no_bundle_secrets(text: str, bundle: dict) -> None:
    assert SECRET not in text
    # str(OSError) はパスを repr で出す(Windows では \ が二重)ので,戻してから比べる
    unescaped = text.replace("\\\\", "\\")
    bundles_dir = bundle["bundles_dir"]
    assert str(bundles_dir) not in unescaped
    assert bundles_dir.parent.name not in text
    for sha256 in bundle["hashes"]:
        assert sha256[:12] not in text


def test_bundle_mode_returns_records_images_dir_and_fingerprint(bundle: dict) -> None:
    source = load_dataset_source(_bundle_data())

    assert source.images_dir.resolve() == (bundle["root"] / "files").resolve()
    # 行の順は tiasdata の manifest の順(subject_id → capture_id)
    assert [r.patient_id for r in source.records] == [f"{SECRET}1", f"{SECRET}1", f"{SECRET}2"]
    assert {r.label for r in source.records} == {"red", "purple", "light_red"}
    for record in source.records:
        assert re.fullmatch(r"[0-9a-f]{64}\.png", record.image_path)
        # image_path は images_dir からの相対で実ファイルを指す
        assert resolve_image_path(source.images_dir, record).is_file()

    manifest_bytes = (bundle["root"] / "manifest.csv").read_bytes()
    assert source.fingerprint == {
        "name": "tongue_color",
        "version": 1,
        "manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(),
    }
    json.dumps(source.fingerprint)  # 実験記録に書ける


def test_bundle_mode_verify_passes_on_intact_bundle(bundle: dict) -> None:
    assert len(load_dataset_source(_bundle_data(), verify=True).records) == 3


def test_bundle_logs_have_no_identifiers(bundle: dict, caplog: pytest.LogCaptureFixture) -> None:
    with caplog.at_level(logging.DEBUG):
        load_dataset_source(_bundle_data(), verify=True)
    _assert_no_bundle_secrets(caplog.text, bundle)
    assert "3 件" in caplog.text


def _corrupt_first(bundle: dict) -> None:
    (bundle["root"] / "files" / f"{bundle['hashes'][0]}.png").write_bytes(b"broken")


def _remove_first(bundle: dict) -> None:
    (bundle["root"] / "files" / f"{bundle['hashes'][0]}.png").unlink()


def _add_stray_file(bundle: dict) -> None:
    (bundle["root"] / "files" / f"{'c' * 64}.png").write_bytes(b"stray")


def _break_sums(bundle: dict) -> None:
    (bundle["root"] / "SHA256SUMS").write_text("", encoding="utf-8")


@pytest.mark.parametrize("damage", [_corrupt_first, _remove_first, _add_stray_file, _break_sums])
def test_verify_failure_is_value_error_without_hash(bundle: dict, damage: Callable) -> None:
    damage(bundle)
    with pytest.raises(ValueError) as excinfo:
        load_dataset_source(_bundle_data(), verify=True)
    _assert_no_bundle_secrets(str(excinfo.value), bundle)
    assert not FULL_HASH.search(str(excinfo.value))
    # 例外の連鎖に元のメッセージ(ハッシュ入り)を残さない
    assert excinfo.value.__cause__ is None
    assert excinfo.value.__suppress_context__


def test_corrupted_file_is_only_detected_with_verify(bundle: dict) -> None:
    # 照合は時間がかかるので survey だけ.既定では開くだけ
    _corrupt_first(bundle)
    assert len(load_dataset_source(_bundle_data()).records) == 3


def test_unreadable_file_during_verify_does_not_expose_hash(
    bundle: dict, monkeypatch: pytest.MonkeyPatch
) -> None:
    # 権限エラー等の OSError はメッセージにファイルのパス(= ハッシュ)を含む
    def denied(path: Path) -> str:
        raise PermissionError(13, "Permission denied", str(path))

    monkeypatch.setattr("tiasdata.bundle.sha256_file", denied)
    with pytest.raises(ValueError) as excinfo:
        load_dataset_source(_bundle_data(), verify=True)
    message = str(excinfo.value)
    _assert_no_bundle_secrets(message, bundle)
    assert not FULL_HASH.search(message)
    # 例外の連鎖に元のメッセージ(パス入り)を残さない
    assert excinfo.value.__cause__ is None
    assert excinfo.value.__suppress_context__


@pytest.mark.parametrize("filename", ["dataset.json", "manifest.csv"])
def test_unreadable_file_during_load_does_not_expose_path(
    bundle: dict, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, filename: str
) -> None:
    # load は verify=False でも走り,OSError の文面にはバンドルのフルパスが出る
    original_read_bytes = Path.read_bytes
    denied_paths: list[str] = []

    def read_bytes(path: Path) -> bytes:
        if path.name == filename:
            denied_paths.append(str(path))
            raise PermissionError(13, "Permission denied", str(path))
        return original_read_bytes(path)

    monkeypatch.setattr(Path, "read_bytes", read_bytes)
    with pytest.raises(ValueError) as excinfo:
        load_dataset_source(_bundle_data(), verify=False)

    assert len(denied_paths) == 1, "tiasdata.load の読み込みで失敗させる"
    message = str(excinfo.value)
    _assert_no_bundle_secrets(message, bundle)
    # str(OSError) はパスを repr で出す(Windows では \ が二重)ので,戻してから比べる
    unescaped = message.replace("\\\\", "\\")
    denied_path = Path(denied_paths[0])
    for path in (denied_path, denied_path.parent, tmp_path, bundle["root"]):
        assert str(path) not in unescaped
    assert tmp_path.name not in message
    assert not FULL_HASH.search(message)
    # 例外の連鎖に元のメッセージ(パス入り)を残さない
    assert excinfo.value.__cause__ is None
    assert excinfo.value.__suppress_context__


def test_changed_manifest_is_rejected_without_verify(bundle: dict) -> None:
    path = bundle["root"] / "manifest.csv"
    path.write_bytes(path.read_bytes() + b"\n")
    with pytest.raises(ValueError) as excinfo:
        load_dataset_source(_bundle_data())
    _assert_no_bundle_secrets(str(excinfo.value), bundle)


def test_duplicated_hash_in_manifest_message_is_masked(bundle: dict) -> None:
    # tiasdata の「SHA-256 が 2 回以上ある」は全桁を出すので,ここで伏せる
    manifest = bundle["root"] / "manifest.csv"
    lines = manifest.read_bytes().splitlines(keepends=True)
    data = b"".join([*lines, lines[1]])
    manifest.write_bytes(data)
    dataset_json = bundle["root"] / "dataset.json"
    info = json.loads(dataset_json.read_text(encoding="utf-8"))
    info["manifest_sha256"] = hashlib.sha256(data).hexdigest()
    info["files"] += 1
    dataset_json.write_text(json.dumps(info), encoding="utf-8")
    with pytest.raises(ValueError) as excinfo:
        load_dataset_source(_bundle_data())
    assert not FULL_HASH.search(str(excinfo.value))


def test_missing_bundle_and_version_are_value_errors(bundle: dict) -> None:
    for data in (_bundle_data(version=2), _bundle_data(name="unknown")):
        with pytest.raises(ValueError) as excinfo:
            load_dataset_source(data)
        _assert_no_bundle_secrets(str(excinfo.value), bundle)


def test_bundle_with_bad_annotation_is_value_error_without_identifiers(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bundle_writer: Callable
) -> None:
    items = [
        {
            "data": _png_bytes(tmp_path, (1, 2, 3)),
            "subject_id": f"{SECRET}1",
            "label": None,
            "severity": "mild",
        }
    ]
    bundles_dir = tmp_path / "bundles"
    bundle_writer(bundles_dir, items)
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles_dir))
    with pytest.raises(ValueError) as excinfo:
        load_dataset_source(_bundle_data())
    assert SECRET not in str(excinfo.value)
    assert not FULL_HASH.search(str(excinfo.value))


def test_bundle_of_other_kind_is_rejected(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bundle_writer: Callable
) -> None:
    items = [
        {
            "data": _png_bytes(tmp_path, (1, 2, 3)),
            "subject_id": f"{SECRET}1",
            "label": "red",
            "severity": "mild",
            "kind": "tongue_crop",
        }
    ]
    bundles_dir = tmp_path / "bundles"
    bundle_writer(bundles_dir, items)
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles_dir))
    with pytest.raises(ValueError):
        load_dataset_source(_bundle_data())


def test_bundle_without_rows_is_rejected(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bundle_writer: Callable
) -> None:
    bundles_dir = tmp_path / "bundles"
    bundle_writer(bundles_dir, [])
    monkeypatch.setenv("TIASDATA_BUNDLES", str(bundles_dir))
    with pytest.raises(ValueError):
        load_dataset_source(_bundle_data())


# --- load_dataset_source(root) ------------------------------------------------------------------


def _root_data(tmp_path: Path) -> DataConfig:
    records = [ManifestRecord("red_mild/a.png", "p1", "red", "mild")]
    write_manifest(records, tmp_path / "ds" / "manifest.csv")
    return DataConfig.model_validate({"root": str(tmp_path / "ds")})


@pytest.mark.parametrize("verify", [False, True])
def test_root_mode_reads_manifest_without_fingerprint(tmp_path: Path, verify: bool) -> None:
    source = load_dataset_source(_root_data(tmp_path), verify=verify)
    assert source.records == [ManifestRecord("red_mild/a.png", "p1", "red", "mild")]
    assert source.images_dir == tmp_path / "ds" / "images"
    assert source.fingerprint is None


def test_root_mode_does_not_look_at_bundles(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.setenv("TIASDATA_BUNDLES", str(tmp_path / "does_not_exist"))
    assert load_dataset_source(_root_data(tmp_path)).fingerprint is None


def test_root_mode_missing_manifest_is_value_error(tmp_path: Path) -> None:
    with pytest.raises(ValueError):
        load_dataset_source(DataConfig.model_validate({"root": str(tmp_path / "none")}))


# --- 依存の閉じ込め -------------------------------------------------------------------------------


def test_tiasdata_is_imported_only_by_bundle_module() -> None:
    pattern = re.compile(r"^\s*(import tiasdata|from tiasdata)", re.MULTILINE)
    users = [
        path.relative_to(SRC_DIR).as_posix()
        for path in SRC_DIR.rglob("*.py")
        if pattern.search(path.read_text(encoding="utf-8"))
    ]
    assert users == ["data/bundle.py"]