"""push で送るファイルの選別のテスト(SPEC_03「push」).
固定の除外(SPEC_01「安全の枠」の「送信」): `.git/`・`.venv/`・`.claude/`・`__pycache__/`・
`.pytest_cache/`・`.ruff_cache/` はどこにあっても,`.env`・`.env.*` はどの階層でも,`runs/` と
`labremote.yaml` はルートの直下で送らない.
設定の除外(SPEC_02「`push`」): 下の `PUSH` に,データ・原本(`data/`・`legacy/`.直下のみ)・
重みの拡張子(大文字小文字を問わず)・一部だけ送るサブモジュール(`external/DemoSub`)を書き,
それらが送られないことを確かめる(`src/demo_project/data/`・`tests/data/` は送る).
"""
from __future__ import annotations
from collections.abc import Iterator
from pathlib import Path
import pytest
from link_helpers import LinkFactory
from labremote.config import PartialPush, PushConfig
from labremote.files import (
PushEntry,
PushRules,
PushSelection,
collect_push_entries,
is_excluded,
is_link,
select_push_files,
)
# データ・原本・重み・サブモジュールの扱いを書いたテスト用の設定(利用する側の labremote.yaml の
# push に当たる).サブモジュールは,サーバで導入に要るものだけを送る
PUSH = PushConfig(
exclude_root=("data", "legacy"),
exclude_suffixes=(".pt", ".pth", ".ckpt", ".pb", ".onnx"),
partial=(PartialPush(path="external/DemoSub", include=("pyproject.toml", "README.md", "src")),),
)
RULES = PushRules.from_push(PUSH)
SENT = [
"pyproject.toml",
"uv.lock",
".python-version",
"src/demo_project/__init__.py",
"src/demo_project/data/manifest.py",
"src/demo_project/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/demo_project/data/bundle.py",
"tests/data/original_tongue_seg_dataset.py",
# 重みの拡張子に似ているが違うもの・.env に似ているが違うもの
"docs/onnx.md",
"src/demo_project/export/onnx_export.py",
"scripts/pth_tool.py",
"src/a.pth.py",
".envrc",
"src/environment.py",
"my.env",
# legacy・data・runs を名前に含むがプロジェクト直下の別名
"legacy.md",
"src/demo_project/legacy/x.py",
"docs/legacy/a.md",
"tests/runs/a.py",
# サブモジュール DemoSub は導入に要るものだけ
"external/DemoSub/pyproject.toml",
"external/DemoSub/README.md",
"external/DemoSub/src/demosub/__init__.py",
"external/DemoSub/src/demosub/catalog/migrations/catalog/0001_x.sql",
]
# 設定に関わらず送らないもの(固定の除外)
NOT_SENT_FIXED = [
".git/config",
".git/objects/ab/cdef",
".venv/Scripts/python.exe",
"__pycache__/x.pyc",
"src/demo_project/__pycache__/a.cpython-312.pyc",
"tests/data/__pycache__/b.pyc",
".pytest_cache/v/cache/nodeids",
".ruff_cache/0.1/x",
# 環境変数ファイル(秘密を含みうる)
".env",
".env.local",
"configs/.env",
"src/.ENV",
".Env.production",
"runs/20260927-120000_x/metrics.json",
"runs/_remote_logs/exp1.log",
"Runs/x/metrics.json",
".claude/settings.json",
".claude/rules/testing.md",
"labremote.yaml",
"external/DemoSub/.git",
"external/DemoSub/.claude/settings.json",
"external/DemoSub/src/demosub/__pycache__/bundle.cpython-312.pyc",
]
# 設定の push(上の PUSH)に書いたときに送らないもの
NOT_SENT_BY_CONFIG = [
"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",
# 重み(どの階層でも・大文字小文字を問わず)
"model.pt",
"best.pth",
"src/demo_project/models/best.pth",
"tests/fixtures/ResUNet.onnx",
"scripts/x.ckpt",
"configs/frozen.pb",
"BEST.PTH",
"a/b/c/Model.Onnx",
"x.tar.pt",
# サブモジュールは partial の include に書いたものだけを送る
"external/DemoSub/.github/dependabot.yml",
"external/DemoSub/CLAUDE.md",
"external/DemoSub/uv.lock",
"external/DemoSub/docs/PROGRESS.md",
"external/DemoSub/tests/test_bundle.py",
"external/DemoSub/datasets/tongue_color.toml",
"external/DemoSub/reviews/r1.md",
]
NOT_SENT = NOT_SENT_FIXED + NOT_SENT_BY_CONFIG
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, PUSH)]
assert sorted(arcnames) == sorted(SENT)
def test_arcnames_are_posix_relative(tmp_path: Path) -> None:
_make_tree(tmp_path, ["src/demo_project/data/manifest.py"])
entries = collect_push_entries(tmp_path)
assert [e.arcname for e in entries] == ["src/demo_project/data/manifest.py"]
assert entries[0].size == 1
@pytest.mark.parametrize("rel", NOT_SENT_FIXED)
def test_fixed_exclusions_apply_without_config(rel: str) -> None:
assert is_excluded(rel)
@pytest.mark.parametrize("rel", NOT_SENT)
def test_is_excluded_for_not_sent(rel: str) -> None:
assert is_excluded(rel, rules=RULES)
@pytest.mark.parametrize("rel", SENT)
def test_is_not_excluded_for_sent(rel: str) -> None:
assert not is_excluded(rel, rules=RULES)
@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, rules=RULES)
@pytest.mark.parametrize(
"rel", ["src/demo_project/data", "tests/data", "src/demo_project/runs_util.py"]
)
def test_nested_data_is_not_excluded(rel: str) -> None:
assert not is_excluded(rel, rules=RULES)
# --- サブモジュール external/DemoSub/ ---
@pytest.mark.parametrize("rel", ["external", "external/DemoSub"])
def test_submodule_parent_directories_are_walked(rel: str) -> None:
assert not is_excluded(rel, is_dir=True, rules=RULES)
@pytest.mark.parametrize(
"rel",
[
"external/DemoSub/src",
"external/DemoSub/pyproject.toml",
"external/DemoSub/README.md",
],
)
def test_submodule_sent_entries_are_not_excluded(rel: str) -> None:
assert not is_excluded(rel, rules=RULES)
@pytest.mark.parametrize(
"rel",
[
"external/DemoSub/docs",
"external/DemoSub/tests",
"external/DemoSub/.claude",
"external/DemoSub/datasets",
],
)
def test_submodule_other_directories_are_excluded(rel: str) -> None:
assert is_excluded(rel, is_dir=True, rules=RULES)
@pytest.mark.parametrize(
"rel",
[
# 同じ名前でも submodule の直下でなければ規則の対象外
"external/Other/docs/a.md",
"external/DemoSub2/docs/a.md",
"src/external/DemoSub/docs/a.md",
# submodule の src の下は名前によらず送る
"external/DemoSub/src/demosub/docs/a.md",
"external/DemoSub/src/demosub/tests/a.py",
],
)
def test_submodule_rule_is_limited_to_its_top_level(rel: str) -> None:
assert not is_excluded(rel, rules=RULES)
def test_submodule_sends_only_install_files(tmp_path: Path) -> None:
"""サブモジュールに見立てたフォルダから,partial の include に書いたものだけを送る."""
prefix = "external/DemoSub/"
_make_tree(
tmp_path,
[
"pyproject.toml",
f"{prefix}pyproject.toml",
f"{prefix}README.md",
f"{prefix}src/demosub/bundle.py",
f"{prefix}.git",
f"{prefix}.claude/settings.json",
f"{prefix}CLAUDE.md",
f"{prefix}uv.lock",
f"{prefix}docs/PROGRESS.md",
f"{prefix}tests/test_bundle.py",
f"{prefix}datasets/x.toml",
],
)
sent = [e.arcname for e in collect_push_entries(tmp_path, PUSH) if e.arcname.startswith(prefix)]
assert f"{prefix}pyproject.toml" in sent
assert f"{prefix}README.md" in sent
assert f"{prefix}src/demosub/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, rules=RULES)
def test_files_inside_weight_like_directory(tmp_path: Path) -> None:
_make_tree(tmp_path, ["models.onnx/readme.md", "models.onnx/w.ONNX"])
entries = collect_push_entries(tmp_path, PUSH)
assert [e.arcname for e in entries] == ["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, PUSH)] == ["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, PUSH)]
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/demo_project/__init__.py"])
_make_tree(outside, ["secret.py", "patients/P0001.png", "sub/code.py"])
return repo, outside
REPO_CODE = ["pyproject.toml", "src/demo_project/__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, PUSH)
assert isinstance(entries, list)
assert entries == list(select_push_files(tmp_path, PUSH).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, PUSH)
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")
# ---------------------------------------------------------------------------
# 固定の除外は設定に関わらず効き,設定で減らせない(SPEC_01「安全の枠」の「送信」)
# ---------------------------------------------------------------------------
FIXED_DIR_NAMES = [".git", ".venv", ".claude", "__pycache__", ".pytest_cache", ".ruff_cache"]
# 固定の除外のフォルダを置く場所(ルートの直下・2 段下・partial の include の下)
FIXED_DIR_PREFIXES = ["", "a/b/", "vendor/Sub/src/"]
# 一部だけ送るフォルダの include に,固定の除外の名前を書いた設定(書いても送られない)
PARTIAL_WITH_FIXED_NAMES = PushConfig(
partial=(
PartialPush(
path="vendor/Sub",
include=("src", *FIXED_DIR_NAMES, ".env", ".env.local", "runs", "labremote.yaml"),
),
)
)
# 送るべきもの(空の一覧で通ってしまわないための対照)
FIXED_CONTROL_SENT = [
"pyproject.toml",
"a/b/code.py",
"vendor/Sub/src/pkg.py",
# ルートの直下でない runs・labremote.yaml は送る
"src/runs/x.py",
"sub/labremote.yaml",
"vendor/Sub/src/runs/y.py",
]
def _fixed_not_sent() -> list[str]:
names = [f"{prefix}{name}/f.txt" for prefix in FIXED_DIR_PREFIXES for name in FIXED_DIR_NAMES]
names += [f"{prefix}{env}" for prefix in FIXED_DIR_PREFIXES for env in [".env", ".env.prod"]]
names += ["runs/r1/metrics.json", "runs/_remote_logs/a.log", "labremote.yaml"]
# partial の include に書いた固定の除外の名前(vendor/Sub の直下)
names += [
"vendor/Sub/.git",
"vendor/Sub/.venv/x.py",
"vendor/Sub/.claude/settings.json",
"vendor/Sub/__pycache__/a.pyc",
"vendor/Sub/.env",
"vendor/Sub/.env.local",
]
return names
class TestFixedExclusionsInTree:
@pytest.mark.parametrize(
"push",
[None, PushConfig(), PUSH, PARTIAL_WITH_FIXED_NAMES],
ids=["none", "empty", "PUSH", "partial-fixed"],
)
def test_fixed_exclusions_are_never_sent(self, tmp_path: Path, push: PushConfig | None) -> None:
"""SPEC_01「送信」: 固定の除外は,push に何を書いても(`{}` を含む)送られない."""
not_sent = _fixed_not_sent()
_make_tree(tmp_path, FIXED_CONTROL_SENT + not_sent)
sent = {e.arcname for e in collect_push_entries(tmp_path, push)}
assert not sent & set(not_sent)
for name in sent:
parts = name.lower().split("/")
assert not set(parts) & set(FIXED_DIR_NAMES), name
assert parts[-1] != ".env" and not parts[-1].startswith(".env."), name
assert parts[0] not in {"runs", "labremote.yaml"}, name
assert {"pyproject.toml", "a/b/code.py", "vendor/Sub/src/pkg.py"} <= sent
def test_empty_push_sends_everything_else(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: `push: {}` では固定の除外だけが効く(他は全部送る)."""
not_sent = _fixed_not_sent()
_make_tree(tmp_path, FIXED_CONTROL_SENT + not_sent)
sent = [e.arcname for e in collect_push_entries(tmp_path, PushConfig())]
assert sorted(sent) == sorted(FIXED_CONTROL_SENT)
@pytest.mark.parametrize(
"rel", ["src/runs/x.py", "sub/labremote.yaml", "a/runs", "docs/labremote.yaml"]
)
def test_runs_and_config_name_below_root_are_sent(self, rel: str) -> None:
"""SPEC_01「送信」: 結果の置き場と labremote.yaml の除外はルートの直下だけ."""
assert not is_excluded(rel, rules=PushRules.from_push(PushConfig()))
@pytest.mark.parametrize("rel", ["Labremote.yaml", "LABREMOTE.YAML", "RUNS/a.txt", ".GIT/x"])
def test_fixed_names_are_compared_in_lower_case(self, rel: str) -> None:
"""SPEC_01「送信」: 固定の除外は大文字小文字の違いでは外れない."""
assert is_excluded(rel)
class TestConfigFileIsNotSent:
@pytest.mark.parametrize("rel", ["custom.yaml", "cfg/my-remote.yaml", "labremote.yaml"])
def test_loaded_config_file_is_not_sent(self, tmp_path: Path, rel: str) -> None:
"""SPEC_01「送信」: 読み込んだ設定ファイルは,名前・場所によらず送らない."""
_make_tree(tmp_path, ["pyproject.toml", "cfg/other.yaml", rel])
sent = [
e.arcname
for e in collect_push_entries(tmp_path, PushConfig(), config_path=tmp_path / rel)
]
assert rel not in sent
assert "pyproject.toml" in sent
assert "cfg/other.yaml" in sent
def test_config_outside_root_excludes_nothing(self, tmp_path: Path) -> None:
"""SPEC_01「送信」: ルートの外の設定ファイルを指定しても,ルートの下は何も除かれない."""
root = tmp_path / "proj"
_make_tree(root, ["pyproject.toml", "custom.yaml"])
_make_tree(tmp_path, ["custom.yaml"])
sent = [
e.arcname
for e in collect_push_entries(root, PushConfig(), config_path=tmp_path / "custom.yaml")
]
assert sorted(sent) == ["custom.yaml", "pyproject.toml"]
# ---------------------------------------------------------------------------
# LabRemote 自身のフォルダを送らない(SPEC_01「送信」「プロジェクトからの使い方」)
# ---------------------------------------------------------------------------
LABREMOTE_FILES = ["pyproject.toml", "src/labremote/cli.py", "README.md", "docs/a.md"]
class TestLabRemoteDirIsNotSent:
@pytest.mark.parametrize("where", ["external/LabRemote", "LabRemote", "deps/x/y/tools-lr"])
def test_labremote_under_root_is_not_sent(self, tmp_path: Path, where: str) -> None:
"""SPEC_01「送信」: LabRemote のフォルダがルートの下にあれば,その下を 1 件も送らない."""
_make_tree(tmp_path, ["pyproject.toml", "src/app.py"])
_make_tree(tmp_path / where, LABREMOTE_FILES)
sent = [
e.arcname
for e in collect_push_entries(tmp_path, PushConfig(), labremote_dir=tmp_path / where)
]
assert not [name for name in sent if name.startswith(f"{where}/")]
assert sorted(sent) == ["pyproject.toml", "src/app.py"]
def test_exclusion_is_by_location_not_by_name(self, tmp_path: Path) -> None:
"""SPEC_01「送信」: 名前ではなく場所で除く(同じ名前でも LabRemote でなければ送る)."""
_make_tree(tmp_path, ["pyproject.toml"])
_make_tree(tmp_path / "external/LabRemote", ["a.py"])
_make_tree(tmp_path / "vendor/lr", LABREMOTE_FILES)
sent = [
e.arcname
for e in collect_push_entries(
tmp_path, PushConfig(), labremote_dir=tmp_path / "vendor/lr"
)
]
assert "external/LabRemote/a.py" in sent
assert not [name for name in sent if name.startswith("vendor/lr/")]
def test_sibling_with_common_prefix_is_sent(self, tmp_path: Path) -> None:
"""SPEC_01「送信」: 除くのは LabRemote のフォルダの下だけ(名前の前方一致で広げない)."""
_make_tree(tmp_path, ["external/LabRemote2/a.py", "external/LabRemote.md"])
_make_tree(tmp_path / "external/LabRemote", LABREMOTE_FILES)
sent = [
e.arcname
for e in collect_push_entries(
tmp_path, PushConfig(), labremote_dir=tmp_path / "external/LabRemote"
)
]
assert sorted(sent) == ["external/LabRemote.md", "external/LabRemote2/a.py"]
@pytest.mark.parametrize("case", ["root", "outside", "none"])
def test_labremote_at_root_or_outside_excludes_nothing(self, tmp_path: Path, case: str) -> None:
"""SPEC_01「送信」: ルートそのもの・ルートの外・指定が無いときは,何も除かない."""
root = tmp_path / "proj"
files = ["pyproject.toml", "src/labremote/cli.py", "external/LabRemote/a.py"]
_make_tree(root, files)
labremote_dir = {"root": root, "outside": tmp_path / "LabRemote", "none": None}[case]
if case == "outside":
_make_tree(tmp_path / "LabRemote", LABREMOTE_FILES)
sent = [
e.arcname for e in collect_push_entries(root, PushConfig(), labremote_dir=labremote_dir)
]
assert sorted(sent) == sorted(files)
def test_labremote_dir_is_excluded_even_inside_partial_include(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: LabRemote 自身は partial の include に書いても送られない."""
push = PushConfig(partial=(PartialPush(path="external", include=("LabRemote", "Other")),))
_make_tree(tmp_path, ["pyproject.toml", "external/Other/a.py"])
_make_tree(tmp_path / "external/LabRemote", LABREMOTE_FILES)
sent = [
e.arcname
for e in collect_push_entries(
tmp_path, push, labremote_dir=tmp_path / "external/LabRemote"
)
]
assert sorted(sent) == ["external/Other/a.py", "pyproject.toml"]
# ---------------------------------------------------------------------------
# 設定で足す除外(SPEC_02「`push`」)
# ---------------------------------------------------------------------------
def _sent(root: Path, push: PushConfig) -> list[str]:
return sorted(e.arcname for e in collect_push_entries(root, push))
class TestConfigExclusions:
def test_exclude_root_applies_only_at_root(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: exclude_root はルートの直下だけ.フォルダにもファイルにも効く."""
_make_tree(
tmp_path,
["data/a.png", "Data2/a.png", "notes.txt", "src/pkg/data/x.py", "src/notes.txt"],
)
push = PushConfig(exclude_root=("data", "notes.txt"))
assert _sent(tmp_path, push) == ["Data2/a.png", "src/notes.txt", "src/pkg/data/x.py"]
def test_exclude_root_is_compared_in_lower_case(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: data と書けば Data/ も送らない."""
_make_tree(tmp_path, ["Data/a.png", "keep.py"])
assert _sent(tmp_path, PushConfig(exclude_root=("data",))) == ["keep.py"]
def test_exclude_root_written_in_upper_case(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: exclude_root は小文字にして比べる(設定を大文字で書いても効く)."""
_make_tree(tmp_path, ["data/a.png", "keep.py"])
assert _sent(tmp_path, PushConfig(exclude_root=("DATA",))) == ["keep.py"]
def test_exclude_dirs_applies_at_any_depth_and_to_files(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: exclude_dirs はどの階層でも効き,同じ名前のファイルも送らない."""
_make_tree(
tmp_path,
["wandb/a.log", "src/x/wandb/b.log", "src/Wandb/c.log", "a/wandb", "keep/wandb2.py"],
)
assert _sent(tmp_path, PushConfig(exclude_dirs=("wandb",))) == ["keep/wandb2.py"]
def test_exclude_suffixes(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: 拡張子はどの階層でも小文字で比べ,.tar.gz も効く."""
_make_tree(
tmp_path,
["A.PT", "src/m/b.pt", "x.tar.gz", "y.gz", "z.tar", "p.pt.py", "deep/a/b/c.Tar.Gz"],
)
push = PushConfig(exclude_suffixes=(".pt", ".tar.gz"))
assert _sent(tmp_path, push) == ["p.pt.py", "y.gz", "z.tar"]
def test_exclude_suffixes_written_in_upper_case(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: 拡張子は小文字にして比べる(設定の側を大文字で書いても効く)."""
_make_tree(tmp_path, ["a.pt", "b.PT", "keep.py"])
assert _sent(tmp_path, PushConfig(exclude_suffixes=(".PT",))) == ["keep.py"]
def test_suffix_is_not_applied_to_directory_names(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: フォルダの名前には拡張子の除外を当てはめない(中は名前で判断)."""
_make_tree(tmp_path, ["models.onnx/readme.md", "models.onnx/w.onnx", "x.tar.gz/a.txt"])
push = PushConfig(exclude_suffixes=(".onnx", ".tar.gz"))
assert _sent(tmp_path, push) == ["models.onnx/readme.md", "x.tar.gz/a.txt"]
# ---------------------------------------------------------------------------
# partial(SPEC_02「`push`」)
# ---------------------------------------------------------------------------
class TestPartial:
def test_only_include_names_are_sent(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: path の直下のうち,include に書いた名前だけを送る."""
_make_tree(tmp_path, ["ext/Sub/src/a.py", "ext/Sub/README.md", "ext/Sub/docs/x.md"])
push = PushConfig(partial=(PartialPush(path="ext/Sub", include=("src", "README.md")),))
assert _sent(tmp_path, push) == ["ext/Sub/README.md", "ext/Sub/src/a.py"]
def test_include_is_case_sensitive(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: include は大文字小文字を区別する(src と書いて Src なら送らない)."""
_make_tree(tmp_path, ["ext/Sub/Src/a.py", "ext/Sub/readme.md", "keep.py"])
push = PushConfig(partial=(PartialPush(path="ext/Sub", include=("src", "README.md")),))
assert _sent(tmp_path, push) == ["keep.py"]
def test_path_is_compared_in_lower_case(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: partial の path は小文字にして比べる."""
_make_tree(tmp_path, ["Ext/SUB/src/a.py", "Ext/SUB/docs/x.md"])
push = PushConfig(partial=(PartialPush(path="ext/sub", include=("src",)),))
assert _sent(tmp_path, push) == ["Ext/SUB/src/a.py"]
def test_other_exclusions_apply_inside_include(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: include の中身にも固定の除外・exclude_dirs・exclude_suffixes."""
_make_tree(
tmp_path,
[
"ext/Sub/src/a.py",
"ext/Sub/src/w.pt",
"ext/Sub/src/cache/x.py",
"ext/Sub/src/__pycache__/a.pyc",
"ext/Sub/src/.env",
"ext/Sub/src/.git/HEAD",
],
)
push = PushConfig(
exclude_dirs=("cache",),
exclude_suffixes=(".pt",),
partial=(PartialPush(path="ext/Sub", include=("src",)),),
)
assert _sent(tmp_path, push) == ["ext/Sub/src/a.py"]
@pytest.mark.parametrize("case", ["missing", "file", "empty-include"])
def test_nothing_is_sent_without_error(self, tmp_path: Path, case: str) -> None:
"""SPEC_02「`push`」: path が無い・path がファイル・include が空なら何も送らない."""
_make_tree(tmp_path, ["keep.py"])
if case == "file":
_make_tree(tmp_path, ["ext/Sub"])
if case == "empty-include":
_make_tree(tmp_path, ["ext/Sub/src/a.py", "ext/Sub/README.md"])
include = () if case == "empty-include" else ("src",)
push = PushConfig(partial=(PartialPush(path="ext/Sub", include=include),))
assert _sent(tmp_path, push) == ["keep.py"]
@pytest.mark.parametrize(
("exclude_root", "path", "files"),
[
("ext", "ext/Sub", ["ext/Sub/src/a.py"]),
("data", "data", ["data/src/a.py"]),
("DATA", "data", ["data/src/a.py"]),
],
)
def test_exclude_root_wins_over_partial(
self, tmp_path: Path, exclude_root: str, path: str, files: list[str]
) -> None:
"""SPEC_02「`push`」: exclude_root と partial の path が重なる場合は,除外が優先."""
_make_tree(tmp_path, [*files, "keep.py"])
push = PushConfig(
exclude_root=(exclude_root,), partial=(PartialPush(path=path, include=("src",)),)
)
assert _sent(tmp_path, push) == ["keep.py"]
def test_multiple_partials_each_apply(self, tmp_path: Path) -> None:
"""SPEC_02「`push`」: 重ならない複数の partial が,それぞれ効く."""
_make_tree(
tmp_path,
["ext/A/src/a.py", "ext/A/docs/x.md", "ext/B/lib/b.py", "ext/B/src/c.py", "ext/C/x.py"],
)
push = PushConfig(
partial=(
PartialPush(path="ext/A", include=("src",)),
PartialPush(path="ext/B", include=("lib",)),
)
)
assert _sent(tmp_path, push) == ["ext/A/src/a.py", "ext/B/lib/b.py", "ext/C/x.py"]
# ---------------------------------------------------------------------------
# 設定を入れてもリンクは送らない(SPEC_01「送信」)
# ---------------------------------------------------------------------------
class TestLinksWithPushConfig:
@pytest.mark.parametrize("kind", ["symlink", "junction"])
def test_link_named_in_partial_include_is_not_walked(
self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str
) -> None:
"""SPEC_01「送信」: include に書いた名前がリンクでも,送らず中にも入らない."""
repo, outside = repo_and_outside
getattr(links, kind)(repo / "ext" / "Sub" / "src", outside)
push = PushConfig(partial=(PartialPush(path="ext/Sub", include=("src",)),))
selection = select_push_files(repo, push)
assert [e.arcname for e in selection.entries] == REPO_CODE
assert selection.skipped_links == ("ext/Sub/src",)
assert _nothing_from(outside, selection.entries)
@pytest.mark.parametrize("kind", ["symlink", "junction"])
def test_link_is_not_sent_with_permissive_config(
self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str
) -> None:
"""SPEC_01「送信」: push に何を書いても,リンクのフォルダは送らず中にも入らない."""
repo, outside = repo_and_outside
getattr(links, kind)(repo / "src" / "ext", outside)
push = PushConfig(
exclude_dirs=("unrelated",),
exclude_suffixes=(".pt",),
partial=(PartialPush(path="src", include=("ext", "demo_project")),),
)
selection = select_push_files(repo, push)
assert [e.arcname for e in selection.entries] == REPO_CODE
assert selection.skipped_links == ("src/ext",)
assert _nothing_from(outside, selection.entries)
def test_file_symlink_in_partial_include_is_not_sent(
self, repo_and_outside: tuple[Path, Path], links: LinkFactory
) -> None:
"""SPEC_01「送信」: include に書いた名前のファイルがリンクでも送らない."""
repo, outside = repo_and_outside
links.symlink(repo / "ext" / "Sub" / "README.md", outside / "secret.py")
push = PushConfig(partial=(PartialPush(path="ext/Sub", include=("README.md",)),))
selection = select_push_files(repo, push)
assert [e.arcname for e in selection.entries] == REPO_CODE
assert selection.skipped_links == ("ext/Sub/README.md",)
# ---------------------------------------------------------------------------
# 結果の置き場(設定の results.dir)は送信の固定の除外(SPEC_02「結果の置き場と送信」)
# ---------------------------------------------------------------------------
class TestResultsDirExclusion:
def test_changed_results_dir_is_not_sent(self, tmp_path: Path) -> None:
"""SPEC_02「結果の置き場と送信」: dir を変えると,除外される場所もその場所に変わる."""
_make_tree(
tmp_path,
[
"output/runs/r1/metrics.json",
"output/runs/_remote_logs/a.log",
"output/other.txt",
"runs/x.txt",
"src/a.py",
],
)
arcnames = [
e.arcname
for e in collect_push_entries(tmp_path, PushConfig(), results_dir="output/runs")
]
# 既定の runs はもう結果の置き場ではないので送る(大文字小文字の違いは下の is_excluded で.
# 大文字小文字だけが違う 2 つのフォルダは Windows で同じものになるため,ここでは作らない)
assert sorted(arcnames) == ["output/other.txt", "runs/x.txt", "src/a.py"]
def test_default_results_dir_is_not_sent(self, tmp_path: Path) -> None:
"""SPEC_02「`results`」: dir の既定は runs で,ルートの直下の runs/ は送らない."""
_make_tree(tmp_path, ["runs/x.txt", "src/runs/z.py", "src/a.py"])
arcnames = [e.arcname for e in collect_push_entries(tmp_path, PushConfig())]
assert sorted(arcnames) == ["src/a.py", "src/runs/z.py"]
@pytest.mark.parametrize(
("rel", "excluded"),
[
("output/runs", True),
("output/runs/x", True),
("OUTPUT/runs/x", True),
("output/RUNS/x/y", True),
("output", False),
("output/runs2/x", False),
("output/x/runs/y", False),
("runs/x", False),
("a/output/runs/x", False),
],
)
def test_is_excluded_follows_results_dir(self, rel: str, excluded: bool) -> None:
"""SPEC_02「結果の置き場と送信」.
<ルート>/<dir> とその中だけを送らない(小文字で比べる).
"""
rules = PushRules.from_push(PushConfig(), results_dir="output/runs")
assert is_excluded(rel, rules=rules) is excluded
@pytest.mark.parametrize("rel", ["runs", "runs/x", "Runs/x", "RUNS/a/b"])
def test_default_results_dir_ignores_case(self, rel: str) -> None:
"""SPEC_02「`push`」の名前の比べ方: 結果の置き場は小文字にして比べる(Runs も送らない)."""
assert is_excluded(rel, rules=PushRules.from_push(PushConfig()))