Newer
Older
LabRemote / src / labremote / testing.py
"""利用する側のプロジェクトのテストを短く書くための関数(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:
    """`<root>/labremote.yaml` を読んで,検証済みの設定を返す.

    親のフォルダは探さない(テストが,自分のリポジトリのルートを渡す).

    Args:
        root: プロジェクトのルート(`labremote.yaml` のあるフォルダ).

    Returns:
        検証済みの設定(`labremote` のコマンドが読むものと同じ).

    Raises:
        ValueError: `<root>/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)