diff --git a/.claude/rules/project-structure.md b/.claude/rules/project-structure.md index 5e4fdca..e7ed361 100644 --- a/.claude/rules/project-structure.md +++ b/.claude/rules/project-structure.md @@ -20,7 +20,8 @@ ├── gpu.py # GPU の状態の解析・判定・選択 ├── observe.py # 観測の結果の集計 ├── report.py # 表示の組み立て -└── cleanup.py # サーバに残っているものの一覧と,照合・削除 +├── cleanup.py # サーバに残っているものの一覧と,照合・削除 +└── testing.py # 利用する側のテストが使う入口(判定の規則は書かず,上のモジュールを呼ぶだけ) tests/ # src/labremote/ のモジュールに対応させる docs/ # 仕様・手順・決まり @@ -31,6 +32,7 @@ - **1 モジュール 1 責務**: 新しい機能は,責務に合うモジュールに置く.合うものが無ければ新しいモジュールを作る(`cli.py` に判定のロジックを足さない) - **副作用を縁に寄せる**: ssh の実行・ファイルの読み書き・表示は `cli` に寄せる.判定と組み立て(GPU の判定,回収・送信・削除の対象の判定,コマンドの文字列)は,入力から出力を返す純関数として書く - **依存の向き**: `cli` → 各モジュールの一方向を保つ.各モジュールから `cli` を import しない +- **`testing.py` は入口だけ**: 利用する側のテストが頼るので,公開の名前と引数を変えるときは,利用する側のテストも直す.判定の規則をここに書き写さない.pytest を import しない - **外を読み込まない**: 利用する側のプロジェクトのコードと,重い依存(torch・numpy 等)を import しない - **設定の既定値は `config.py` の 1 か所に置く**.他のモジュールに既定値を散らさない - **固定の規則は定数として 1 か所に置く**: 固定の除外・予約の環境変数・ログの置き場の名前は,それを使うモジュールの先頭の定数にし,設定のスキーマに入れない diff --git a/CLAUDE.md b/CLAUDE.md index b066f77..a39df1a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ ## 開発進捗 -最新: PLAN_02 のステップ 1-5(`run.exclude_groups`)完了.次はステップ 1-6(プロジェクトの側のテストを短く書くための関数) +最新: PLAN_02 のステップ 1-6(プロジェクトの側のテスト用の関数)完了.次はステップ 1-7(表示の文言の一般化・`kill` の対象の限定・文字コードの対処) ※ 本欄は**最新ステップ 1 行のみ上書き更新**.詳細な進捗履歴(動機・設計判断・失敗パターン)は [docs/PROGRESS.md](docs/PROGRESS.md) に追記する.運用ルールは `.claude/rules/progress-log.md` を参照(該当ファイル編集時に自動ロードされる). ## 必須ルール(コード実装時) diff --git "a/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" "b/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" index c33227b..8c1f554 100644 --- "a/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" +++ "b/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" @@ -39,7 +39,7 @@ | 直すステップ | 内容 | | --- | --- | | 3-3 | 学習側のコードと git のハッシュの環境変数名を突き合わせるテスト(`test_whitelist.py`)は,名前を `LABREMOTE_GIT_COMMIT` に置き換えたため,TongueSegModel の今のコード(`TSM_GIT_COMMIT`)とは合わない.`project.git_commit_env` は 1-2 で入ったので,利用する側のテスト(3-3)で「設定の `git_commit_env` と,学習側のコードが読む名前が同じ」ことを確かめる形に移す | -| 1-6・3-3 | LabRemote の中では動かせないテストが 18 件あり,スキップにしてある(学習側の実験 ID の作り方と突き合わせる 15 件,実際の `configs/remote.yaml` を読む 2 件,サブモジュールの 1 件).利用する側のテストへ移す | +| 3-3 | LabRemote の中では動かせないテストが 17 件あり(当初は 18 件.サブモジュールの 1 件は 1-3 で動くようになった),スキップにしてある(学習側の実験 ID の作り方と突き合わせる 15 件,実際の `configs/remote.yaml` を読む 2 件,サブモジュールの 1 件).利用する側のテストへ移す | | 1-7 | 表示・help の使用例・コメントに,TongueSegModel の言葉(「学習データのバンドル」,`tsm-train`・`tsm-export`,`TIAS_DATA_ROOT` の経緯)が残っている.テストの名前にも `tsm` が残っている(`test_markers_use_tsm_prefix`・`TestRunIdOfTsmTrain`) | | 1-7 | コメント・docstring の SPEC の参照(約 36 行)は,移す元の文書を指している.該当のコードを書き換えるステップで,LabRemote の SPEC を指す形に直す | | 1-7 | `cli.py` は約 1200 行あり,GPU の選択の流れ・git の状態の取得・tar の受け取りを抱えている.設定に出すときに,判定を各モジュールへ分ける(`.claude/rules/project-structure.md`) | @@ -64,7 +64,7 @@ | 直すステップ | 内容 | | --- | --- | -| 1-6 | 固定の除外を名前で判定する処理が,設定の検証(`config.py`)と選別(`files.py`)の 2 か所にある.「当たった部分の位置と種類」を返す関数 1 つにまとめられる.テスト用の関数は,`PushRules.from_push(設定の push).is_excluded(名前)` を包むだけで作れる | +| 1-7 | 固定の除外を名前で判定する処理が,設定の検証(`config.py`)と選別(`files.py`)の 2 か所にある.「当たった部分の位置と種類」を返す関数 1 つにまとめられる | | 3-1 | **`data`・`legacy`・重みの拡張子は,もう固定の除外ではない**.TongueSegModel の `labremote.yaml` に `push.exclude_root: [data, legacy]`・`push.exclude_suffixes`・`push.partial`(`external/TIASDataHub`)を必ず書き,3-3 のテストで確かめる.`push` の節が無い設定は,読む時点でエラーになる | | 3-1 | LabRemote 自身のフォルダの場所は,「`labremote` パッケージの 2 つ上」で求めている(`src/` の形を前提にしている).サブモジュールとして編集可能インストールで入れる前提なら合う.別の入れ方にするなら見直す | | 1-7 | テスト(`tests/test_files.py`)に,TongueSegModel の言葉(`original_tongue_seg_dataset.py`・`legacy`)が残っている.サブモジュールのテスト群と `TestPartial` は,確かめている内容が重なっている | @@ -75,7 +75,6 @@ | 直すステップ | 内容 | | --- | --- | -| 1-6 | プロジェクトの側のテスト用の関数は,`is_pull_allowed(名前, 設定の results, with_checkpoints=...)` を包むだけで作れる | | 1-7 | 設定の名前の検証は,送信(`push`)と回収(`results`)で前半(空・前後の空白・使えない文字)が同じだが,エラーの文言が少し違うので別の関数のままにしてある.文言をそろえるときに 1 つにまとめる.絶対パスの検査も同じ | | 1-7 | `__init__.py` の docstring・`run` のコメント・help の使用例に,TongueSegModel の言葉が残っている | | 2-2 | `discard` は,読み込みと検証だけが入っている.`clean` の判定を書くときは,回収と同じく大文字と小文字を区別して比べる.設定の検証用の「小文字にして比べる」関数を,判定に使わない | @@ -93,6 +92,16 @@ | 3-2 | サーバに LabRemote のフォルダが無い状態で,`uv run --no-group remote` がロックファイルの確認を通るかは,まだ確かめていない(実サーバとサブモジュールが要る).通らなければ,`--frozen` を足すか,導入に要るものだけを送る形に仕様を直す.今の実装が `uv run` へ渡せるのは `--no-group <名前>` だけである | | 1-7 | 依存グループの名前の検証は,`a.`・`a-` のように末尾が記号の名前も通す.依存グループの名前の決まり(末尾は英数字)より緩い.害は無い(uv が拒否する)が,そろえるなら仕様を先に直す | +### 1-6 で分かったこと (Findings from Step 1-6) + +1-6 は完了した(2026-11-20).前の表のうち,1-6 に回してあった項目は,済んだものを消し,残りを直すステップに付け替えた. + +| 直すステップ | 内容 | +| --- | --- | +| 3-3 | TongueSegModel の側のテストは,`labremote.testing` の `load_config`・`is_pushed`・`is_pulled` で書く([SPEC_01](../04_SPEC/SPEC_01_アーキテクチャ設計.md)「プロジェクトの側のテスト」に例がある).`is_pushed` は実際のフォルダの中を見ないので,「送られるファイルの一覧」を使うテストは書かない(データのフォルダの中身を,テストの出力に出さないため) | +| 3-3 | LabRemote の `tests/` に残っている,TongueSegModel の側に頼るテスト 17 件(スキップされている)は,TongueSegModel の側へ移した時点で,LabRemote から消す | +| 文書 | `tests/test_testing.py` は,[SPEC_02](../04_SPEC/SPEC_02_設定ファイル仕様.md) の冒頭の例を仕様のファイルから読んで確かめている.例を書き換えて実装と合わなくなると,このテストが失敗する(仕様の例と実装のずれに気づくための仕組み) | + ## M2: 新しい機能 (New Features) | ステップ | 内容 | 確かめること | diff --git "a/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" "b/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" index 95b6dbf..1294170 100644 --- "a/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" +++ "b/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" @@ -130,7 +130,44 @@ - 自分の `labremote.yaml` を読み,回収してはならない名前(画像・manifest・指定の無い重み等)が弾かれること - 自分の `labremote.yaml` で,送ってはならないフォルダ(データ・原本等)が送信の対象に入らないこと -LabRemote は,このテストを短く書くための関数(設定を読んで,名前が回収・送信の対象かを返す)を用意する. +LabRemote は,このテストを短く書くための関数を,`labremote.testing` に用意する.利用する側のテストが頼る入口なので,名前と引数を変えるときは,利用する側のテストも一緒に直す. + +| 関数 | 内容 | +| --- | --- | +| `load_config(root)` | `/labremote.yaml` を読んで,検証済みの設定を返す.親のフォルダは探さない(テストが,自分のリポジトリのルートを渡す) | +| `is_pushed(config, rel_path, *, is_dir=False)` | ルートからの相対パス `rel_path` が,`push` で送られるかを返す | +| `is_pulled(config, rel_path, *, with_checkpoints=False)` | 実験フォルダからの相対パス `rel_path` が,`pull` で回収されるかを返す | + +- **判定は,`push`・`pull` が実際に使う関数をそのまま呼ぶ**.テスト用に別の判定を書かない(テストは通るのに,実際には送られる・回収される,という食い違いを作らない) +- `is_pushed` は,名前で決まる除外(固定の除外,設定の `push`,結果の置き場,ルートの直下の `labremote.yaml`)を見る.途中のフォルダが除外されていれば,その下のパスも送られないと答える.**実際のフォルダの中は見ない**ので,リンクの除外と,場所で決まる除外(LabRemote 自身のフォルダ)は判定に入らない(これらは設定に関わらず効き,LabRemote の側のテストで確かめてある) +- どの関数も,手元のファイルを一覧しない・サーバに接続しない.渡した名前についてだけ答える.データのフォルダの中身(ファイル名)を,テストの出力に出さないためである +- `rel_path` は `/` 区切りで書く.次は `ValueError` にする(別の名前として判定して,誤って「送られる」「回収されない」と答えないため): 文字列でない値,空,絶対パス(`/x`・`C:/x`・`C:x`),`..`・`.`・空の部分を含むパス(`../x`・`./a`・`a//b`・末尾の `/`),`\` を含むパス,NUL を含むパス +- `is_pushed` が見る設定ファイルの除外は,ルートの直下の `labremote.yaml` だけである.`--config` で別の名前・別の場所の設定ファイルを使う場合の,そのファイル自体の除外は,場所で決まる除外なので判定に入らない +- `load_config` は,設定ファイルが無いときは `ValueError`,設定の内容が不正なときは pydantic の `ValidationError` を送出する.どちらの場合も,テストは失敗する(不正な設定のまま,テストが黙って通らない) +- `labremote.testing` は pytest に頼らない(実行時の依存を増やさない) +- 公開する名前は,上の 3 つだけである.除外や一覧を書き換える・無効にする関数は置かない + +利用する側のテストの例. + +```python +from pathlib import Path + +import pytest + +from labremote.testing import is_pulled, is_pushed, load_config + +CONFIG = load_config(Path(__file__).resolve().parents[1]) + + +@pytest.mark.parametrize("name", ["data", "legacy", "runs", ".claude"]) +def test_folders_that_must_not_be_sent(name: str) -> None: + assert not is_pushed(CONFIG, name, is_dir=True) + + +@pytest.mark.parametrize("name", ["images/a.png", "manifest.csv", "checkpoints/best.pth"]) +def test_names_that_must_not_be_pulled(name: str) -> None: + assert not is_pulled(CONFIG, name) +``` ## モジュールの構成 (Modules) @@ -147,6 +184,7 @@ | `gpu`・`observe` | GPU の状態の解析・判定・選択 | | `report` | 表示の組み立て | | `cleanup` | サーバに残っているものの一覧と,照合・削除(新規) | +| `testing` | 利用する側のテストが使う入口(設定を読んで,名前が送信・回収の対象かを返す) | - 実行時の依存は pydantic と PyYAML だけにする.利用する側のプロジェクトのコードと,torch 等の重い依存を読み込まない(別プロセスで確かめるテストを置く) - ssh を呼ぶ部分と,判定・組み立ての部分を分ける.判定・組み立ては ssh を呼ばずに単体テストできる形にする diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 2fb21d3..b8ae508 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -49,3 +49,7 @@ - [x] **ステップ 1-5(`run.exclude_groups`)**: 設定に書いた依存グループを,サーバの `uv run` で `--no-group <名前>` として外すようにした(LabRemote をサーバの環境に入れないため). - 設計判断: `uv run` へ渡せるのは `--no-group <名前>` だけにし,任意の引数を渡す設定は作らなかった.名前は検証と引用を通してから埋め込む - 後段: LabRemote のフォルダが無いサーバで,実際に `uv run --no-group` が通るかは未検証(3-2 で実サーバで確かめる) +- [x] **ステップ 1-6(プロジェクトの側のテスト用の関数)**: `labremote.testing` に `load_config`・`is_pushed`・`is_pulled` を用意した.利用する側は,自分の `labremote.yaml` で「送ってはならないものが送られない」「回収してはならないものが回収されない」ことを,数行のテストで確かめられる. + - 設計判断: 判定は,`push`・`pull` が実際に使う関数をそのまま呼ぶ(テスト用の別の判定を作ると,テストは通るのに実際には送られる,という食い違いが起きうる) + - 設計判断: 実際のフォルダをたどって「送られるファイルの一覧」を返す関数は入れなかった.設定を誤っているときに,データのフォルダの中身(ファイル名)をテストの出力に出してしまうため.渡した名前についてだけ答える + - 後段: TongueSegModel の側のテスト(3-3)はこの入口で書く.LabRemote に残っている TongueSegModel 頼みのテスト 17 件は,そのときに移して消す diff --git a/src/labremote/testing.py b/src/labremote/testing.py new file mode 100644 index 0000000..9ccfefb --- /dev/null +++ b/src/labremote/testing.py @@ -0,0 +1,155 @@ +"""利用する側のプロジェクトのテストを短く書くための関数(SPEC_01「プロジェクトの側のテスト」). + +各プロジェクトは,自分の `labremote.yaml` について次を自分のテストで確かめる. + +- 送ってはならないフォルダ(データ・原本等)が `push` で送られないこと(`is_pushed`) +- 回収してはならない名前(画像・manifest・指定の無い重み等)が `pull` で回収されないこと + (`is_pulled`) + +利用する側のテストが頼る入口なので,名前と引数を変えるときは利用する側のテストも直す. + +判定は,`push`・`pull` が実際に使う関数(`labremote.files.PushRules.is_excluded`・ +`labremote.whitelist.is_pull_allowed`)をそのまま呼ぶ.テスト用に別の(緩い・厳しい)判定を +書かない(テストは通るのに,実際には送られる・回収される,という食い違いを作らないため). + +どの関数も,設定ファイルを読む以外に手元のファイルを見ない(一覧しない)・サーバに接続しない. +渡した名前についてだけ答える.データのフォルダの中身(ファイル名)を,テストの出力に出さない +ためである.このモジュールは pytest に頼らない(実行時の依存は pydantic と PyYAML だけ). + +例:: + + from pathlib import Path + + from labremote.testing import is_pulled, is_pushed, load_config + + CONFIG = load_config(Path(__file__).resolve().parents[1]) + + assert not is_pushed(CONFIG, "data", is_dir=True) + assert not is_pulled(CONFIG, "images/a.png") +""" + +from __future__ import annotations + +import re +from pathlib import Path + +from labremote.config import CONFIG_FILE_NAME, RemoteConfig, load_remote_config +from labremote.files import PushRules +from labremote.whitelist import is_pull_allowed + +__all__ = ["is_pulled", "is_pushed", "load_config"] + +# 絶対パスとみなす先頭(`C:/x`・`C:x` 等のドライブ文字) +_DRIVE_RE = re.compile(r"[A-Za-z]:") + + +def load_config(root: Path | str) -> RemoteConfig: + """`/labremote.yaml` を読んで,検証済みの設定を返す. + + 親のフォルダは探さない(テストが,自分のリポジトリのルートを渡す). + + Args: + root: プロジェクトのルート(`labremote.yaml` のあるフォルダ). + + Returns: + 検証済みの設定(`labremote` のコマンドが読むものと同じ). + + Raises: + ValueError: `/labremote.yaml` が無い(ファイルでない),YAML として読めない, + またはトップレベルがマッピングでない場合. + pydantic.ValidationError: 設定値が不正な場合. + """ + return load_remote_config(Path(root) / CONFIG_FILE_NAME) + + +def _split_rel_path(rel_path: str) -> list[str]: + """`/` 区切りの相対パスを検証して,部分に分ける. + + `\\` 区切りは受け付けない(`data\\x` を 1 つの名前として判定し「送られる」と答えるのを + 避けるため).`./a`・末尾の `/`・`a//b` のような書き方も,意図が曖昧なため拒否する. + + Raises: + ValueError: 文字列でない・空・絶対パス・`..`・`.`・空の部分・`\\`・NUL を含む場合. + """ + if not isinstance(rel_path, str) or not rel_path: + raise ValueError(f"rel_path は空でない文字列で書く: {rel_path!r}") + if "\\" in rel_path: + raise ValueError(f"rel_path は / 区切りで書く(\\ は使えない): {rel_path!r}") + if "\0" in rel_path: + raise ValueError(f"rel_path に NUL は使えない: {rel_path!r}") + if rel_path.startswith("/") or _DRIVE_RE.match(rel_path): + raise ValueError(f"rel_path に絶対パスは書けない: {rel_path!r}") + parts = rel_path.split("/") + for part in parts: + if part in ("", ".", ".."): + raise ValueError( + f"rel_path に空の部分・.・.. は書けない(./ や末尾の / も不可): {rel_path!r}" + ) + return parts + + +def is_pushed(config: RemoteConfig, rel_path: str, *, is_dir: bool = False) -> bool: + """ルートからの相対パスが,`push` で送られるかを返す. + + 名前で決まる除外(固定の除外,設定の `push`,結果の置き場 `results.dir`,ルートの直下の + `labremote.yaml`)を,実際の `push` と同じ `PushRules.is_excluded` で判定する.実際の `push` は + フォルダを上からたどり,除外したフォルダの中に入らないため,ここでも途中のフォルダを上から順に + フォルダとして確かめ,どれかが除外されていれば送られないと答える. + + 実際のフォルダの中は見ない(データのフォルダの中身をテストの出力に出さないため).そのため, + リンク(シンボリックリンク・ジャンクション)の除外と,場所で決まる除外(LabRemote 自身の + フォルダ・`--config` で読んだ別の場所の設定ファイル)は判定に入らない.これらは設定に関わらず + 効き,LabRemote の側のテストで確かめてある. + + Args: + config: `load_config` で読んだ設定. + rel_path: ルートからの相対パス(`/` 区切り.例: `data`・`src/model.py`). + is_dir: `rel_path` がフォルダなら True(拡張子・`.env` の除外はファイルにだけかかる). + + Returns: + 送られるなら True,送られないなら False. + + Raises: + ValueError: `rel_path` が空・絶対パス・`..` を含む・`\\` 区切り等の場合. + + Example: + >>> assert not is_pushed(config, "data", is_dir=True) # doctest: +SKIP + >>> assert not is_pushed(config, "data/train/a.png") # doctest: +SKIP + """ + parts = _split_rel_path(rel_path) + # 実際の push(`labremote.cli` → `select_push_files`)と同じ設定の値から規則を作る. + # ルートの直下の labremote.yaml は固定の除外の定数でかかる.場所で決まる除外は渡さない + # (手元のファイルシステムを見ないため) + rules = PushRules.from_push(config.push, results_dir=config.results.dir) + # 実際の push はフォルダを上からたどり,除外したフォルダの中に入らない.その結果に合わせる + for depth in range(1, len(parts)): + if rules.is_excluded("/".join(parts[:depth]), is_dir=True): + return False + return not rules.is_excluded(rel_path, is_dir=is_dir) + + +def is_pulled(config: RemoteConfig, rel_path: str, *, with_checkpoints: bool = False) -> bool: + """実験フォルダからの相対パスが,`pull` で回収されるかを返す. + + 実際の `pull` の二重の確認(サーバの一覧の絞り込みと,受け取った tar の検査)が使う + `labremote.whitelist.is_pull_allowed` を,同じ設定の `results` でそのまま呼ぶ. + 名前は大文字小文字を区別して完全一致で比べる. + + Args: + config: `load_config` で読んだ設定. + rel_path: 実験フォルダ(`<結果の置き場>/<実験 ID>/`)からの相対パス + (`/` 区切り.例: `metrics.json`・`checkpoints/best.pth`). + with_checkpoints: `--with-checkpoints` を付けたときの判定にするなら True. + + Returns: + 回収されるなら True,回収されないなら False. + + Raises: + ValueError: `rel_path` が空・絶対パス・`..` を含む・`\\` 区切り等の場合. + + Example: + >>> assert not is_pulled(config, "images/a.png") # doctest: +SKIP + >>> assert not is_pulled(config, "checkpoints/best.pth") # doctest: +SKIP + """ + _split_rel_path(rel_path) + return is_pull_allowed(rel_path, config.results, with_checkpoints=with_checkpoints) diff --git a/tests/test_imports.py b/tests/test_imports.py index bf9f674..44a4f57 100644 --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -50,6 +50,7 @@ "labremote.report", "labremote.transfer", "labremote.whitelist", + "labremote.testing", "labremote.cli", ], ) @@ -60,6 +61,14 @@ assert name not in loaded, f"{module} が {name} を読み込んだ" +def test_testing_module_does_not_import_pytest() -> None: + """SPEC_01: `labremote.testing` は pytest に頼らない(実行時の依存を増やさない).""" + loaded = _loaded_modules("labremote.testing") + assert "labremote.testing" in loaded + for name in ("pytest", "_pytest"): + assert name not in loaded, f"labremote.testing が {name} を読み込んだ" + + def test_help_runs_without_torch() -> None: """`labremote --help` が torch を読み込まずに終わる(ENV_04).""" script = ( diff --git a/tests/test_testing.py b/tests/test_testing.py new file mode 100644 index 0000000..503fc3b --- /dev/null +++ b/tests/test_testing.py @@ -0,0 +1,456 @@ +"""利用する側のテストのための関数(`labremote.testing`)のテスト(SPEC_01「プロジェクトの側のテスト」). + +送信・回収の規則そのもの(何が除外されるか)は `test_files.py`・`test_whitelist.py`・ +`test_config.py` が確かめている.ここでは,この入口が実際の `push`・`pull` と同じ答えを返すことと, +入口に固有の決まり(`rel_path` の検証・途中のフォルダ・親を探さない・ファイルを見ない)を確かめる. +""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +from pathlib import Path + +import pytest +import yaml +from pydantic import ValidationError +from results_helpers import OTHER_RESULTS_YAML, SAMPLE_RESULTS_YAML + +import labremote +import labremote.testing as testing_module +from labremote.config import RemoteConfig +from labremote.files import select_push_files +from labremote.testing import is_pulled, is_pushed, load_config +from labremote.whitelist import is_pull_allowed + +# 接続先は架空の Host 名(.claude/rules/testing.md) +_BASE_YAML = """\ +project: + name: Sample +servers: + - name: hostA + priority: 1 + remote_dir: ~/work/Sample +""" + +_PUSH_YAML = """\ +push: + exclude_root: [data, legacy] + exclude_dirs: [scratch] + exclude_suffixes: [.pth] + partial: + - path: external/Hub + include: [pyproject.toml, src] +""" + +# 実際の選別にかける,小さいプロジェクトのファイル(リンクと LabRemote 自身のフォルダは作らない) +_PROJECT_FILES = [ + # 送られるもの + "README.md", + "src/model.py", + "src/data/x.py", # exclude_root は直下だけ + "src/legacy.py", + "sub/labremote.yaml", # 設定ファイルの除外はルートの直下だけ + "models.pth/inner.py", # フォルダには拡張子の除外を当てない + "external/Hub/pyproject.toml", + "external/Hub/src/a.py", + "output/other.txt", + # 固定の除外 + "labremote.yaml", + ".git/config", + "src/.git/x", + "a/b/.venv/y", + "src/__pycache__/m.pyc", + ".claude/settings.json", + ".env", + "src/.env.local", + # exclude_root + "data/train/a.png", + "legacy/old.txt", + # exclude_dirs + "src/scratch/tmp.py", + "lib/scratch", # 同じ名前のファイル + # exclude_suffixes + "src/w.pth", + # partial の include に無いもの + "external/Hub/README.md", + "external/Hub/data/x.csv", + # 結果の置き場(既定の runs と,output/runs) + "runs/exp1/metrics.json", + "output/runs/exp1/metrics.json", +] + + +def _write_config(root: Path, *sections: str) -> Path: + root.mkdir(parents=True, exist_ok=True) + path = root / "labremote.yaml" + path.write_text(_BASE_YAML + "".join(sections), encoding="utf-8") + return path + + +def _make_project(root: Path, *sections: str) -> RemoteConfig: + for rel in _PROJECT_FILES: + if rel == "labremote.yaml": + continue + target = root / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("x", encoding="utf-8") + _write_config(root, *sections) + return load_config(root) + + +def _actual_push(root: Path, config: RemoteConfig) -> set[str]: + # cli._collect_entries と同じ引数(LabRemote 自身のフォルダは cli._labremote_repo_dir と同じ) + selection = select_push_files( + root, + config.push, + config_path=root / "labremote.yaml", + labremote_dir=Path(labremote.__file__).resolve().parent.parent.parent, + results_dir=config.results.dir, + ) + return {entry.arcname for entry in selection.entries} + + +def _all_files(root: Path) -> list[str]: + return sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()) + + +class TestSameAnswerAsPush: + """SPEC_01: 判定は,`push` が実際に使う関数をそのまま呼ぶ(食い違いを作らない).""" + + @pytest.mark.parametrize( + "sections", + [ + pytest.param((_PUSH_YAML,), id="push-rules"), + pytest.param((_PUSH_YAML, "results:\n dir: output/runs\n"), id="results-dir"), + pytest.param(("push: {}\n",), id="empty-push"), + ], + ) + def test_is_pushed_matches_select_push_files( + self, tmp_path: Path, sections: tuple[str, ...] + ) -> None: + """SPEC_01: `is_pushed` の答えが,実際の選別が選んだファイルの集合と一致する.""" + config = _make_project(tmp_path, *sections) + files = _all_files(tmp_path) + actual = _actual_push(tmp_path, config) + predicted = {rel for rel in files if is_pushed(config, rel)} + assert predicted == actual + # 前提: 送られるものと送られないものの両方がある + assert actual + assert set(files) - actual + + +# 回収の判定にかける名前(回収される名前・されない名前・重み) +_PULL_NAMES = [ + "config.yaml", + "metrics.json", + "figures/loss.png", + "figures/sub/a.png", + "images/a.png", + "manifest.csv", + "split.json", + "Config.yaml", + "checkpoints/best.pth", + "checkpoints/last.pth", + "summary.txt", + "out/plots/a.svg", + "weights/final.ckpt", + "debug/a.png", +] + + +class TestSameAnswerAsPull: + """SPEC_01: 判定は,`pull` が実際に使う関数をそのまま呼ぶ.""" + + @pytest.mark.parametrize("results_yaml", [SAMPLE_RESULTS_YAML, OTHER_RESULTS_YAML]) + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_is_pulled_matches_is_pull_allowed( + self, tmp_path: Path, results_yaml: str, with_checkpoints: bool + ) -> None: + """SPEC_01: `is_pulled` の答えが,設定の `results` で呼んだ `is_pull_allowed` と一致する.""" + _write_config(tmp_path, "push: {}\n", results_yaml) + config = load_config(tmp_path) + answers = [] + for name in _PULL_NAMES: + expected = is_pull_allowed(name, config.results, with_checkpoints=with_checkpoints) + got = is_pulled(config, name, with_checkpoints=with_checkpoints) + assert got == expected, name + answers.append(got) + # 前提: 回収される名前とされない名前の両方がある + assert any(answers) + assert not all(answers) + + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_results_omitted_pulls_nothing(self, tmp_path: Path, with_checkpoints: bool) -> None: + """SPEC_02: `results` を省略した設定では,何も回収されない.""" + _write_config(tmp_path, "push: {}\n") + config = load_config(tmp_path) + for name in _PULL_NAMES: + assert not is_pulled(config, name, with_checkpoints=with_checkpoints), name + + +@pytest.fixture +def push_config(tmp_path: Path) -> RemoteConfig: + _write_config(tmp_path, _PUSH_YAML) + return load_config(tmp_path) + + +class TestParentFolderExclusion: + """SPEC_01: 途中のフォルダが除外されていれば,その下のパスも送られないと答える.""" + + @pytest.mark.parametrize( + "rel_path", + [ + "data/train/a.png", # exclude_root + "src/.git/x", # 固定の除外のフォルダ + "a/b/.venv/y", + "src/scratch/deep/tmp.py", # exclude_dirs + "external/Hub/data/x.csv", # partial の include に無いフォルダの下 + "runs/exp1/metrics.json", # 結果の置き場 + ], + ) + def test_path_under_excluded_folder_is_not_pushed( + self, push_config: RemoteConfig, rel_path: str + ) -> None: + """SPEC_01: 除外されたフォルダの下のパスは送られない.""" + assert not is_pushed(push_config, rel_path) + + @pytest.mark.parametrize( + ("rel_path", "expected"), + [ + ("data", False), + ("legacy", False), + ("src/scratch", False), + ("external/Hub/data", False), + ("runs", False), + ("src", True), + ("external/Hub/src", True), + ("models.pth", True), + ], + ) + def test_folder_itself(self, push_config: RemoteConfig, rel_path: str, expected: bool) -> None: + """SPEC_01: `is_dir=True` でフォルダそのものを尋ねても同じ答えになる.""" + assert is_pushed(push_config, rel_path, is_dir=True) is expected + + @pytest.mark.parametrize( + "rel_path", + ["src/data/x.py", "sub/labremote.yaml", "src/legacy/a.py", "external/Hub/src/a.py"], + ) + def test_exclusion_does_not_spread(self, push_config: RemoteConfig, rel_path: str) -> None: + """SPEC_01/SPEC_02: 直下だけの除外・ルートの直下の設定ファイルの除外が,下に広がらない.""" + assert is_pushed(push_config, rel_path) + + +_BAD_REL_PATHS = [ + "", + "/x", + "C:/x", + "C:x", + "../x", + "a/../b", + "..", + "./a", + ".", + "a//b", + "a/", + "data\\x", + "data/x\x00.png", +] + + +class TestRelPathValidation: + """SPEC_01: `rel_path` の書き方の誤りは `ValueError` にする.""" + + @pytest.mark.parametrize("rel_path", _BAD_REL_PATHS) + def test_is_pushed_rejects(self, push_config: RemoteConfig, rel_path: str) -> None: + """SPEC_01: 空・絶対パス・`..`・`.`・空の部分・`\\`・NUL を含むと `ValueError`(push).""" + with pytest.raises(ValueError): + is_pushed(push_config, rel_path) + with pytest.raises(ValueError): + is_pushed(push_config, rel_path, is_dir=True) + + @pytest.mark.parametrize("rel_path", _BAD_REL_PATHS) + def test_is_pulled_rejects(self, push_config: RemoteConfig, rel_path: str) -> None: + """SPEC_01: 空・絶対パス・`..`・`.`・空の部分・`\\`・NUL を含むと `ValueError`(pull).""" + with pytest.raises(ValueError): + is_pulled(push_config, rel_path) + with pytest.raises(ValueError): + is_pulled(push_config, rel_path, with_checkpoints=True) + + @pytest.mark.parametrize("rel_path", ["src/model.py", "a.b/c", "..a/b", "a../b"]) + def test_normal_paths_are_accepted(self, push_config: RemoteConfig, rel_path: str) -> None: + """SPEC_01: `/` 区切りの相対パスは受け付ける(`..` を含む名前は部分でなければよい).""" + assert isinstance(is_pushed(push_config, rel_path), bool) + assert isinstance(is_pulled(push_config, rel_path), bool) + + @pytest.mark.parametrize("value", [None, Path("src/model.py"), 1]) + def test_non_string_is_error(self, push_config: RemoteConfig, value: object) -> None: + """仕様に無い: 文字列でない値はエラーになる(黙って判定しない).""" + with pytest.raises((ValueError, TypeError)): + is_pushed(push_config, value) # type: ignore[arg-type] + with pytest.raises((ValueError, TypeError)): + is_pulled(push_config, value) # type: ignore[arg-type] + + +class TestLoadConfig: + """SPEC_01: `load_config(root)` は `/labremote.yaml` を読む.親のフォルダは探さない.""" + + @pytest.mark.parametrize("as_str", [False, True]) + def test_reads_root_config(self, tmp_path: Path, as_str: bool) -> None: + """SPEC_01: `/labremote.yaml` を読んで検証済みの設定を返す(root は Path・str).""" + _write_config(tmp_path, _PUSH_YAML) + config = load_config(str(tmp_path) if as_str else tmp_path) + assert isinstance(config, RemoteConfig) + assert config.project.name == "Sample" + assert tuple(config.push.exclude_root) == ("data", "legacy") + + def test_does_not_search_parent(self, tmp_path: Path) -> None: + """SPEC_01: 親のフォルダは探さない(親にあっても root に無ければエラー).""" + _write_config(tmp_path, "push: {}\n") + child = tmp_path / "child" + child.mkdir() + with pytest.raises(ValueError): + load_config(child) + + def test_missing_file_is_error(self, tmp_path: Path) -> None: + """SPEC_01: 設定ファイルが無ければエラー.""" + with pytest.raises(ValueError): + load_config(tmp_path) + + def test_folder_with_config_name_is_error(self, tmp_path: Path) -> None: + """SPEC_01: `labremote.yaml` という名前のフォルダは設定ファイルとみなさない.""" + (tmp_path / "labremote.yaml").mkdir() + with pytest.raises(ValueError): + load_config(tmp_path) + + def test_config_without_push_is_error(self, tmp_path: Path) -> None: + """SPEC_02: `push` の節は省略できない(検証を通らない設定で,テストが黙って通らない).""" + _write_config(tmp_path) + with pytest.raises(ValidationError): + load_config(tmp_path) + + def test_unknown_key_is_error(self, tmp_path: Path) -> None: + """SPEC_02: 未知のキーは拒否する(`load_config` も同じ検証を通す).""" + _write_config(tmp_path, "push:\n exclude_rot: [data]\n") + with pytest.raises(ValidationError): + load_config(tmp_path) + + +def _fail(*_args: object, **_kwargs: object) -> None: + raise AssertionError("ファイルシステム・subprocess を見てはならない") + + +class TestDoesNotTouchFiles: + """SPEC_01: 手元のファイルを一覧しない・サーバに接続しない.渡した名前についてだけ答える.""" + + _CASES = [ + ("data", True), + ("data/train/a.png", False), + ("src/model.py", False), + ("src", True), + ("runs/exp1/metrics.json", False), + ] + _PULLS = ["config.yaml", "images/a.png", "checkpoints/best.pth", "figures/loss.png"] + + def _answers(self, config: RemoteConfig) -> tuple[list[bool], list[bool]]: + pushed = [is_pushed(config, rel, is_dir=is_dir) for rel, is_dir in self._CASES] + pulled = [ + is_pulled(config, rel, with_checkpoints=flag) + for rel in self._PULLS + for flag in (False, True) + ] + return pushed, pulled + + def test_same_answers_after_project_is_removed(self, tmp_path: Path) -> None: + """SPEC_01: 設定のオブジェクトだけで答える(読んだ後にプロジェクトを消しても同じ答え).""" + root = tmp_path / "proj" + _write_config(root, _PUSH_YAML, SAMPLE_RESULTS_YAML) + (root / "src").mkdir() + (root / "src" / "model.py").write_text("x", encoding="utf-8") + config = load_config(root) + before = self._answers(config) + shutil.rmtree(root) + assert self._answers(config) == before + + def test_does_not_call_filesystem_or_subprocess( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """SPEC_01: 判定の実行中に,ファイルシステムを見る関数と subprocess が呼ばれない.""" + _write_config(tmp_path, _PUSH_YAML, SAMPLE_RESULTS_YAML) + config = load_config(tmp_path) + expected = self._answers(config) + with monkeypatch.context() as m: + for name in ("scandir", "listdir", "stat", "lstat", "walk"): + m.setattr(os, name, _fail) + for name in ("iterdir", "exists", "stat", "lstat", "resolve", "is_file", "is_dir"): + m.setattr(Path, name, _fail) + for name in ("run", "Popen", "call", "check_output"): + m.setattr(subprocess, name, _fail) + got = self._answers(config) + assert got == expected + + +def test_public_api_is_only_three_functions() -> None: + """SPEC_01: 公開の入口は `load_config`・`is_pushed`・`is_pulled` の 3 つだけ.""" + assert sorted(testing_module.__all__) == ["is_pulled", "is_pushed", "load_config"] + public = sorted( + name + for name, value in vars(testing_module).items() + if not name.startswith("_") + and callable(value) + and getattr(value, "__module__", None) == testing_module.__name__ + ) + assert public == ["is_pulled", "is_pushed", "load_config"] + + +# SPEC_02 の冒頭の例(TongueSegModel を想定).例と実装の食い違いを見つけるため,文書から読む +_SPEC02_PATH = ( + Path(__file__).resolve().parents[1] / "docs" / "04_SPEC" / "SPEC_02_設定ファイル仕様.md" +) +_SPEC02_EXAMPLE_RE = re.compile(r"## 例 \(Example\).*?```yaml\n(.*?)```", re.DOTALL) + + +def _spec02_example() -> str: + match = _SPEC02_EXAMPLE_RE.search(_SPEC02_PATH.read_text(encoding="utf-8")) + assert match, "SPEC_02 の冒頭に yaml の例が無い" + return match.group(1) + + +class TestSpecExample: + """SPEC_01「プロジェクトの側のテスト」の例が,SPEC_02 の冒頭の例の設定でそのまま動く.""" + + @pytest.fixture + def config(self, tmp_path: Path) -> RemoteConfig: + example = _spec02_example() + # 前提: 例が YAML として正しく,push・results・run を含む + raw = yaml.safe_load(example) + assert {"push", "results", "run"} <= set(raw) + (tmp_path / "labremote.yaml").write_text(example, encoding="utf-8") + return load_config(tmp_path) + + @pytest.mark.parametrize("name", ["data", "legacy", "runs", ".claude"]) + def test_folders_that_must_not_be_sent(self, config: RemoteConfig, name: str) -> None: + """SPEC_01 の例: `data`・`legacy`・`runs`・`.claude` は送られない.""" + assert not is_pushed(config, name, is_dir=True) + + @pytest.mark.parametrize("name", ["src", "external/TIASDataHub/src", "README.md"]) + def test_code_is_sent(self, config: RemoteConfig, name: str) -> None: + """SPEC_01 の例の前提: 送るべきコードは送られる(全部を拒否して通るのではない).""" + assert is_pushed(config, name, is_dir=not name.endswith(".md")) + + @pytest.mark.parametrize("name", ["images/a.png", "manifest.csv", "checkpoints/best.pth"]) + def test_names_that_must_not_be_pulled(self, config: RemoteConfig, name: str) -> None: + """SPEC_01 の例: `images/a.png`・`manifest.csv`・`checkpoints/best.pth` は回収されない.""" + assert not is_pulled(config, name) + + @pytest.mark.parametrize("name", ["config.yaml", "figures/loss.png"]) + def test_names_that_are_pulled(self, config: RemoteConfig, name: str) -> None: + """SPEC_02 の例: 一覧の名前(`config.yaml`・`figures/loss.png`)は回収される.""" + assert is_pulled(config, name) + + def test_checkpoint_pulled_only_with_flag(self, config: RemoteConfig) -> None: + """SPEC_01/SPEC_02: 重みは `with_checkpoints=True` のときだけ回収される.""" + assert not is_pulled(config, "checkpoints/best.pth") + assert is_pulled(config, "checkpoints/best.pth", with_checkpoints=True)