Newer
Older
LabRemote / tests / test_files.py
"""push で送るファイルの選別のテスト(SPEC_03「push」).

`.git/`・`.venv/`・`__pycache__/`・`.pytest_cache/`・`.ruff_cache/` はどこにあっても送らない.
`data/`・`runs/`・`.claude/`・`legacy/` はプロジェクト直下のみ除外する
(`src/tongue_seg_model/data/`・`tests/data/` は送る).
重み(`.pt`・`.pth`・`.ckpt`・`.pb`・`.onnx`.大文字小文字を問わず)と `.env`・`.env.*` は
どの階層でも送らない(SPEC_03「移植で変える点」).

TIASJudgeModel の tests/remote/test_files.py の移植に,`legacy/`・重み・`.env` の除外と,実際の
リポジトリに対する確認を足した(`legacy/` の中は一覧しない.送信対象の一覧の側から確かめる).
"""

from __future__ import annotations

from collections.abc import Iterator
from pathlib import Path

import pytest
from link_helpers import LinkFactory

from labremote.files import (
    PushEntry,
    PushSelection,
    collect_push_entries,
    is_excluded,
    is_link,
    select_push_files,
)

SENT = [
    "pyproject.toml",
    "uv.lock",
    ".python-version",
    "src/tongue_seg_model/__init__.py",
    "src/tongue_seg_model/data/manifest.py",
    "src/tongue_seg_model/remote/gpu.py",
    "tests/data/test_split.py",
    "tests/remote/test_gpu.py",
    "scripts/make_synthetic_dataset.py",
    "configs/remote.yaml",
    "configs/synthetic-gpu.yaml",
    "src/tongue_seg_model/data/bundle.py",
    "tests/data/original_tongue_seg_dataset.py",
    # 重みの拡張子に似ているが違うもの・.env に似ているが違うもの
    "docs/onnx.md",
    "src/tongue_seg_model/export/onnx_export.py",
    "scripts/pth_tool.py",
    "src/a.pth.py",
    ".envrc",
    "src/environment.py",
    "my.env",
    # legacy・data・runs を名前に含むがプロジェクト直下の別名
    "legacy.md",
    "src/tongue_seg_model/legacy/x.py",
    "docs/legacy/a.md",
    "tests/runs/a.py",
    # サブモジュール TIASDataHub は導入に要るものだけ
    "external/TIASDataHub/pyproject.toml",
    "external/TIASDataHub/README.md",
    "external/TIASDataHub/src/tiasdata/__init__.py",
    "external/TIASDataHub/src/tiasdata/catalog/migrations/catalog/0001_x.sql",
]

NOT_SENT = [
    ".git/config",
    ".git/objects/ab/cdef",
    ".venv/Scripts/python.exe",
    "__pycache__/x.pyc",
    "src/tongue_seg_model/__pycache__/a.cpython-312.pyc",
    "tests/data/__pycache__/b.pyc",
    ".pytest_cache/v/cache/nodeids",
    ".ruff_cache/0.1/x",
    "data/synthetic/manifest.csv",
    "data/synthetic/synthetic/v1/files/ab.png",
    # 原本(重みと,画像のファイル名を含む結果がある)
    "legacy/source/main.py",
    "legacy/hparams.yaml",
    "legacy/result/x.csv",
    "legacy/output/bestModel.pth",
    "Legacy/source/main.py",
    "LEGACY/a.txt",
    "DATA/x.png",
    "Runs/x/metrics.json",
    # 重み(どの階層でも・大文字小文字を問わず)
    "model.pt",
    "best.pth",
    "src/tongue_seg_model/models/best.pth",
    "tests/fixtures/ResUNet.onnx",
    "scripts/x.ckpt",
    "configs/frozen.pb",
    "BEST.PTH",
    "a/b/c/Model.Onnx",
    "x.tar.pt",
    # 環境変数ファイル(秘密を含みうる)
    ".env",
    ".env.local",
    "configs/.env",
    "src/.ENV",
    ".Env.production",
    "runs/20260927-120000_x/metrics.json",
    "runs/_remote_logs/exp1.log",
    ".claude/settings.json",
    ".claude/rules/testing.md",
    "external/TIASDataHub/.git",
    "external/TIASDataHub/.claude/settings.json",
    "external/TIASDataHub/.github/dependabot.yml",
    "external/TIASDataHub/CLAUDE.md",
    "external/TIASDataHub/uv.lock",
    "external/TIASDataHub/docs/PROGRESS.md",
    "external/TIASDataHub/tests/test_bundle.py",
    "external/TIASDataHub/datasets/tongue_color.toml",
    "external/TIASDataHub/reviews/r1.md",
    "external/TIASDataHub/src/tiasdata/__pycache__/bundle.cpython-312.pyc",
]


def _make_tree(root: Path, paths: list[str]) -> None:
    for rel in paths:
        path = root / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(b"x")


def test_collect_push_entries_excludes_listed_directories(tmp_path: Path) -> None:
    _make_tree(tmp_path, SENT + NOT_SENT)
    arcnames = [entry.arcname for entry in collect_push_entries(tmp_path)]
    assert sorted(arcnames) == sorted(SENT)


def test_arcnames_are_posix_relative(tmp_path: Path) -> None:
    _make_tree(tmp_path, ["src/tongue_seg_model/data/manifest.py"])
    entries = collect_push_entries(tmp_path)
    assert [e.arcname for e in entries] == ["src/tongue_seg_model/data/manifest.py"]
    assert entries[0].size == 1


@pytest.mark.parametrize("rel", NOT_SENT)
def test_is_excluded_for_not_sent(rel: str) -> None:
    assert is_excluded(rel)


@pytest.mark.parametrize("rel", SENT)
def test_is_not_excluded_for_sent(rel: str) -> None:
    assert not is_excluded(rel)


@pytest.mark.parametrize(
    "rel", ["data", "runs", ".claude", ".git", ".venv", "legacy", "Legacy", "src/__pycache__"]
)
def test_root_directories_themselves_are_excluded(rel: str) -> None:
    assert is_excluded(rel)


@pytest.mark.parametrize(
    "rel", ["src/tongue_seg_model/data", "tests/data", "src/tongue_seg_model/runs_util.py"]
)
def test_nested_data_is_not_excluded(rel: str) -> None:
    assert not is_excluded(rel)


# --- サブモジュール external/TIASDataHub/ ---


@pytest.mark.parametrize("rel", ["external", "external/TIASDataHub"])
def test_submodule_parent_directories_are_walked(rel: str) -> None:
    assert not is_excluded(rel)


@pytest.mark.parametrize(
    "rel",
    [
        "external/TIASDataHub/src",
        "external/TIASDataHub/pyproject.toml",
        "external/TIASDataHub/README.md",
    ],
)
def test_submodule_sent_entries_are_not_excluded(rel: str) -> None:
    assert not is_excluded(rel)


@pytest.mark.parametrize(
    "rel",
    [
        "external/TIASDataHub/docs",
        "external/TIASDataHub/tests",
        "external/TIASDataHub/.claude",
        "external/TIASDataHub/datasets",
    ],
)
def test_submodule_other_directories_are_excluded(rel: str) -> None:
    assert is_excluded(rel)


@pytest.mark.parametrize(
    "rel",
    [
        # 同じ名前でも submodule の直下でなければ規則の対象外
        "external/Other/docs/a.md",
        "external/TIASDataHub2/docs/a.md",
        "src/external/TIASDataHub/docs/a.md",
        # submodule の src の下は名前によらず送る
        "external/TIASDataHub/src/tiasdata/docs/a.md",
        "external/TIASDataHub/src/tiasdata/tests/a.py",
    ],
)
def test_submodule_rule_is_limited_to_its_top_level(rel: str) -> None:
    assert not is_excluded(rel)


def test_repository_submodule_sends_only_install_files() -> None:
    root = Path(__file__).resolve().parents[1]
    if not (root / "external" / "TIASDataHub" / "pyproject.toml").is_file():
        pytest.skip("サブモジュールが展開されていない")
    prefix = "external/TIASDataHub/"
    sent = [e.arcname for e in collect_push_entries(root) if e.arcname.startswith(prefix)]
    assert f"{prefix}pyproject.toml" in sent
    assert f"{prefix}README.md" in sent
    assert f"{prefix}src/tiasdata/bundle.py" in sent
    assert {name.removeprefix(prefix).split("/")[0] for name in sent} == {
        "pyproject.toml",
        "README.md",
        "src",
    }


# --- ディレクトリの扱い ---


@pytest.mark.parametrize("rel", ["models.onnx", "src/weights.pth", ".env.d"])
def test_directory_names_are_not_matched_by_file_rules(rel: str) -> None:
    # 拡張子・.env の除外はファイルだけに当てはめる(中のファイルは名前で判断する)
    assert not is_excluded(rel, is_dir=True)


def test_files_inside_weight_like_directory(tmp_path: Path) -> None:
    _make_tree(tmp_path, ["models.onnx/readme.md", "models.onnx/w.ONNX"])
    assert [e.arcname for e in collect_push_entries(tmp_path)] == ["models.onnx/readme.md"]


def test_legacy_directory_is_not_walked(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    """`legacy/`・`data/`・`runs/` の中は列挙もしない(ファイル名を読まない)."""
    import os

    _make_tree(tmp_path, ["legacy/result/x.csv", "data/a.png", "runs/r/log.txt", "src/a.py"])
    visited: list[str] = []
    real_walk = os.walk

    def spy_walk(top, *args, **kwargs):
        for dirpath, dirnames, filenames in real_walk(top, *args, **kwargs):
            visited.append(Path(dirpath).relative_to(tmp_path).as_posix())
            yield dirpath, dirnames, filenames

    monkeypatch.setattr("labremote.files.os.walk", spy_walk)
    assert [e.arcname for e in collect_push_entries(tmp_path)] == ["src/a.py"]
    assert not any(v.split("/")[0] in {"legacy", "data", "runs"} for v in visited)


def test_entries_are_sorted_and_sizes_are_real(tmp_path: Path) -> None:
    (tmp_path / "b").mkdir()
    (tmp_path / "b" / "z.py").write_bytes(b"12345")
    (tmp_path / "a.py").write_bytes(b"")
    entries = collect_push_entries(tmp_path)
    assert [(e.arcname, e.size) for e in entries] == [("a.py", 0), ("b/z.py", 5)]


# --- 実際のリポジトリ ---

REPO_ROOT = Path(__file__).resolve().parents[1]
WEIGHT_SUFFIXES = (".pt", ".pth", ".ckpt", ".pb", ".onnx")


def _repository_entries() -> list[str]:
    return [e.arcname for e in collect_push_entries(REPO_ROOT)]


def test_repository_push_has_no_legacy_data_runs_or_weights() -> None:
    """実際のリポジトリの送信対象に,`legacy/`・`data/`・`runs/`・重み・`.env` が 0 件."""
    sent = _repository_entries()
    assert sent, "送信対象が空"
    for name in sent:
        top = name.split("/")[0].lower()
        assert top not in {"legacy", "data", "runs", ".claude", ".git", ".venv"}, name
        assert not name.lower().endswith(WEIGHT_SUFFIXES), name
        base = name.rsplit("/", 1)[-1].lower()
        assert base != ".env" and not base.startswith(".env."), name
        assert "__pycache__" not in name.split("/"), name


def test_repository_push_contains_code_needed_on_server() -> None:
    sent = set(_repository_entries())
    for required in [
        "pyproject.toml",
        "uv.lock",
        "src/labremote/__init__.py",
        "src/labremote/cli.py",
    ]:
        assert required in sent, required


# ---------------------------------------------------------------------------
# シンボリックリンク・ジャンクションは送らない(リンクのディレクトリの中にも入らない)
# ---------------------------------------------------------------------------


@pytest.fixture
def links() -> Iterator[LinkFactory]:
    factory = LinkFactory()
    yield factory
    factory.cleanup()


@pytest.fixture
def repo_and_outside(tmp_path: Path) -> tuple[Path, Path]:
    """tmp_path の中に「リポジトリ役」と「外役」の 2 つのフォルダを作る."""
    repo = tmp_path / "repo"
    outside = tmp_path / "outside"
    _make_tree(repo, ["pyproject.toml", "src/tongue_seg_model/__init__.py"])
    _make_tree(outside, ["secret.py", "patients/P0001.png", "sub/code.py"])
    return repo, outside


REPO_CODE = ["pyproject.toml", "src/tongue_seg_model/__init__.py"]


def _arcnames(root: Path) -> list[str]:
    return [entry.arcname for entry in select_push_files(root).entries]


def _nothing_from(outside: Path, entries: tuple[PushEntry, ...]) -> bool:
    resolved = outside.resolve()
    return all(resolved not in e.path.resolve().parents for e in entries)


class TestIsLink:
    def test_regular_file_and_directory_are_not_links(self, tmp_path: Path) -> None:
        (tmp_path / "d").mkdir()
        (tmp_path / "f.py").write_bytes(b"x")
        assert not is_link(tmp_path / "d")
        assert not is_link(tmp_path / "f.py")

    def test_missing_path_is_not_link(self, tmp_path: Path) -> None:
        assert not is_link(tmp_path / "missing")

    def test_file_symlink(self, tmp_path: Path, links: LinkFactory) -> None:
        (tmp_path / "t.py").write_bytes(b"x")
        assert is_link(links.symlink(tmp_path / "l.py", tmp_path / "t.py"))

    def test_directory_symlink(self, tmp_path: Path, links: LinkFactory) -> None:
        (tmp_path / "t").mkdir()
        assert is_link(links.symlink(tmp_path / "l", tmp_path / "t"))

    def test_broken_symlink(self, tmp_path: Path, links: LinkFactory) -> None:
        assert is_link(links.symlink(tmp_path / "l.py", tmp_path / "gone.py", is_dir=False))

    def test_junction(self, tmp_path: Path, links: LinkFactory) -> None:
        (tmp_path / "t").mkdir()
        assert is_link(links.junction(tmp_path / "j", tmp_path / "t"))


class TestSelectPushFilesWithoutLinks:
    def test_no_links_gives_empty_skipped(self, tmp_path: Path) -> None:
        _make_tree(tmp_path, ["a.py", "src/b.py"])
        selection = select_push_files(tmp_path)
        assert isinstance(selection, PushSelection)
        assert [e.arcname for e in selection.entries] == ["a.py", "src/b.py"]
        assert selection.skipped_links == ()

    def test_collect_push_entries_is_selection_entries(self, tmp_path: Path) -> None:
        _make_tree(tmp_path, SENT + NOT_SENT)
        entries = collect_push_entries(tmp_path)
        assert isinstance(entries, list)
        assert entries == list(select_push_files(tmp_path).entries)


class TestFileLinks:
    def test_file_symlink_inside_repo_is_skipped(
        self, repo_and_outside: tuple[Path, Path], links: LinkFactory
    ) -> None:
        repo, _ = repo_and_outside
        links.symlink(repo / "src" / "alias.py", repo / "pyproject.toml")
        selection = select_push_files(repo)
        assert [e.arcname for e in selection.entries] == REPO_CODE
        assert selection.skipped_links == ("src/alias.py",)

    def test_file_symlink_to_outside_is_not_sent(
        self, repo_and_outside: tuple[Path, Path], links: LinkFactory
    ) -> None:
        repo, outside = repo_and_outside
        links.symlink(repo / "leak.py", outside / "secret.py")
        selection = select_push_files(repo)
        assert [e.arcname for e in selection.entries] == REPO_CODE
        assert selection.skipped_links == ("leak.py",)
        assert _nothing_from(outside, selection.entries)

    def test_broken_file_symlink_is_skipped(
        self, repo_and_outside: tuple[Path, Path], links: LinkFactory
    ) -> None:
        repo, outside = repo_and_outside
        links.symlink(repo / "broken.py", outside / "does_not_exist.py", is_dir=False)
        selection = select_push_files(repo)
        assert [e.arcname for e in selection.entries] == REPO_CODE
        assert selection.skipped_links == ("broken.py",)


class TestDirectoryLinks:
    @pytest.mark.parametrize("kind", ["symlink", "junction"])
    def test_directory_link_to_outside_is_not_walked(
        self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str
    ) -> None:
        repo, outside = repo_and_outside
        getattr(links, kind)(repo / "src" / "ext", outside)
        selection = select_push_files(repo)
        assert [e.arcname for e in selection.entries] == REPO_CODE
        assert selection.skipped_links == ("src/ext",)
        # リンク先の中身(患者の画像に見立てたもの)は送信対象に一切入らない
        assert _nothing_from(outside, selection.entries)

    @pytest.mark.parametrize("kind", ["symlink", "junction"])
    def test_directory_link_inside_repo_is_not_walked(
        self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str
    ) -> None:
        repo, _ = repo_and_outside
        getattr(links, kind)(repo / "mirror", repo / "src")
        selection = select_push_files(repo)
        assert [e.arcname for e in selection.entries] == REPO_CODE
        assert selection.skipped_links == ("mirror",)

    @pytest.mark.parametrize("kind", ["symlink", "junction"])
    def test_link_to_legacy_or_data_like_folder_is_not_walked(
        self, tmp_path: Path, links: LinkFactory, kind: str
    ) -> None:
        """tmp_path の中の「legacy 役」「data 役」を別名で指すリンクも送らない."""
        repo = tmp_path / "repo"
        _make_tree(repo, ["legacy/result/r.csv", "data/a.png", "src/a.py"])
        getattr(links, kind)(repo / "src" / "old", repo / "legacy")
        getattr(links, kind)(repo / "src" / "d", repo / "data")
        selection = select_push_files(repo)
        assert [e.arcname for e in selection.entries] == ["src/a.py"]
        assert selection.skipped_links == ("src/d", "src/old")

    @pytest.mark.parametrize("kind", ["symlink", "junction"])
    def test_os_walk_does_not_enter_links(
        self,
        repo_and_outside: tuple[Path, Path],
        links: LinkFactory,
        monkeypatch: pytest.MonkeyPatch,
        kind: str,
    ) -> None:
        import os

        repo, outside = repo_and_outside
        getattr(links, kind)(repo / "src" / "ext", outside)
        visited: list[str] = []
        real_walk = os.walk

        def spy_walk(top, *args, **kwargs):
            for dirpath, dirnames, filenames in real_walk(top, *args, **kwargs):
                visited.append(Path(dirpath).relative_to(repo.resolve()).as_posix())
                yield dirpath, dirnames, filenames

        monkeypatch.setattr("labremote.files.os.walk", spy_walk)
        select_push_files(repo)
        assert not any(v == "src/ext" or v.startswith("src/ext/") for v in visited)


class TestLinksInExcludedDirectories:
    @pytest.mark.parametrize("kind", ["symlink", "junction"])
    def test_links_inside_excluded_directories_are_not_counted(
        self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str
    ) -> None:
        repo, outside = repo_and_outside
        getattr(links, kind)(repo / ".venv" / "lib" / "ext", outside / "sub")
        getattr(links, kind)(repo / "src" / "__pycache__" / "ext", outside / "sub")
        getattr(links, kind)(repo / "runs" / "r" / "ext", outside / "sub")
        selection = select_push_files(repo)
        assert selection.skipped_links == ()
        assert [e.arcname for e in selection.entries] == REPO_CODE

    def test_file_links_inside_excluded_directories_are_not_counted(
        self, repo_and_outside: tuple[Path, Path], links: LinkFactory
    ) -> None:
        repo, outside = repo_and_outside
        links.symlink(repo / ".venv" / "python.py", outside / "secret.py")
        selection = select_push_files(repo)
        assert selection.skipped_links == ()
        assert [e.arcname for e in selection.entries] == REPO_CODE


class TestSkippedLinksOrder:
    def test_skipped_links_are_sorted_posix_paths(
        self, repo_and_outside: tuple[Path, Path], links: LinkFactory
    ) -> None:
        repo, outside = repo_and_outside
        links.symlink(repo / "z.py", outside / "secret.py")
        links.symlink(repo / "src" / "b" / "a.py", outside / "secret.py")
        links.symlink(repo / "a" / "dir", outside / "sub")
        selection = select_push_files(repo)
        assert selection.skipped_links == ("a/dir", "src/b/a.py", "z.py")