Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

test: 测试域登记门槛与按改动文件选域的 auto 域

longmeidao17c272e5f1a8
diff --git a/.claude/skills/peach-worktree/SKILL.md b/.claude/skills/peach-worktree/SKILL.md
index 6e4683e2d..4cb9b8fb3 100644
--- a/.claude/skills/peach-worktree/SKILL.md
+++ b/.claude/skills/peach-worktree/SKILL.md
@@ -18,7 +18,7 @@ description: 在用户说并行、工作树、暂存、提交、ready、集成
1. 协调者在主目录创建隔离工作树:`& .\.venv\Scripts\python.exe scripts\agent_worktree.py create --agent claude --task <task>`。它建在 `peach-worktrees/`,Codex 和 Claude 共用这一个目录。**不要用 Claude Code 内置的工作树机制(`.claude/worktrees/`)**:它在分支被集成后会被回收,目录却留在原地。
2. 工作者只在自己的工作树内编辑。工作树不复制 `.venv`。
-3. 测试在当前工作树根目录运行,每个平台只有一个入口。日常开发先跑本功能域:Windows `& .\scripts\test.ps1 -Scope follow`,macOS/Linux `./scripts/test.sh follow`。可选域为 `follow`、`catalog`、`media`、`sync`、`metadata`、`tooling`、`web`;不传参数是 `full`。只改 `web/` 的文案、CSS 或页面脚本时跑 `-Scope web`:约 380 个用例、6 秒上下,`full` 要 30~45 分钟。域清单的真相在 `scripts/test_runner.py` 的 `SCOPES`,本行漏掉一个域,代价就是每次界面改动多等四十分钟。
+3. 测试在当前工作树根目录运行,每个平台只有一个入口。日常开发先跑本功能域:Windows `& .\scripts\test.ps1 -Scope follow`,macOS/Linux `./scripts/test.sh follow`。可选域为 `follow`、`catalog`、`media`、`sync`、`metadata`、`tooling`、`web`;不传参数是 `full`。只改 `web/` 的文案、CSS 或页面脚本时跑 `-Scope web`:约 380 个用例、6 秒上下,`full` 要 30~45 分钟。域清单的真相在 `scripts/test_runner.py` 的 `SCOPES`,本行漏掉一个域,代价就是每次界面改动多等四十分钟。不确定该跑哪个域就用 `-Scope auto`(macOS/Linux `./scripts/test.sh auto`),它按改动文件选域,映射不到才退化为 `full`。
两者契约相同:从 Git common directory 定位主项目 venv,强制 `PYTHONPATH=<当前工作树>/src`,
核对 `peach.__file__` 后运行标准库 `unittest`。禁止手工拼接 venv 路径或调用 pytest。
跨多个域、迁移、共享测试设施、依赖、构建/发布或大面积改动必须跑 `full`;局部功能只跑
diff --git a/README.en.md b/README.en.md
index f84797d96..792f851de 100644
--- a/README.en.md
+++ b/README.en.md
@@ -109,8 +109,10 @@ Each platform has exactly one official test entry point. The script locates the
During development, run the tests for the affected functional domain, for example
`& .\scripts\test.ps1 -Scope follow` on Windows and `./scripts/test.sh follow` on macOS/Linux.
-The available domains are `follow`, `catalog`, `media`, `sync`, `metadata` and `tooling`; with no
-argument the default `full` scope runs. Changes that span several domains, touch migrations, shared
+The available domains are `follow`, `catalog`, `media`, `sync`, `metadata`, `tooling` and `web`; with
+no argument the default `full` scope runs. `auto` picks domains from the changed files and falls back
+to `full` when a file maps to none or touches migrations, shared test infrastructure or a dependency
+manifest. Changes that span several domains, touch migrations, shared
test infrastructure or dependencies, prepare a release or have a large footprint must run the full
scope; a single local change does not need to rerun unrelated tests over and over.
diff --git a/README.md b/README.md
index d6a47e41b..bbff0d978 100644
--- a/README.md
+++ b/README.md
@@ -104,7 +104,8 @@ peach-app/
开发时按功能域运行必要测试,例如 Windows 用 `& .\scripts\test.ps1 -Scope follow`,
macOS/Linux 用 `./scripts/test.sh follow`。可选域为 `follow`、`catalog`、`media`、`sync`、
-`metadata`、`tooling`;不传参数仍跑 `full`。跨多个域、修改迁移/共享测试设施/依赖、准备发布或
+`metadata`、`tooling`、`web`;不传参数仍跑 `full`。`auto` 按改动文件选域,映射不到或触及迁移、
+共享测试设施、依赖清单时退化为 `full`。跨多个域、修改迁移/共享测试设施/依赖、准备发布或
改动影响面较大时必须跑全量,单一局部功能不再反复跑无关测试。
## 依赖维护
diff --git a/scripts/test.ps1 b/scripts/test.ps1
index 531b14d5f..d4e8b5607 100644
--- a/scripts/test.ps1
+++ b/scripts/test.ps1
@@ -1,6 +1,6 @@
[CmdletBinding()]
param(
- [ValidateSet('full', 'follow', 'catalog', 'media', 'sync', 'metadata', 'tooling', 'web')]
+ [ValidateSet('full', 'auto', 'follow', 'catalog', 'media', 'sync', 'metadata', 'tooling', 'web')]
[string]$Scope = 'full'
)
diff --git a/scripts/test.sh b/scripts/test.sh
index 5aa5c9152..d19be483c 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -5,6 +5,13 @@
set -euo pipefail
SCOPE="${1:-full}"
+case "$SCOPE" in
+ full|auto|follow|catalog|media|sync|metadata|tooling|web) ;;
+ *)
+ echo "未知测试域:$SCOPE(可选 full、auto、follow、catalog、media、sync、metadata、tooling、web)" >&2
+ exit 2
+ ;;
+esac
WORKTREE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 5ab3f8f3a..5f07caef5 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -2,9 +2,12 @@
from __future__ import annotations
import argparse
+import fnmatch
import importlib
+import subprocess
import sys
import unittest
+from collections.abc import Iterable
from pathlib import Path
@@ -75,6 +78,42 @@ SCOPE_TEST_IDS: dict[str, tuple[str, ...]] = {
),
}
+# `auto` 域按改动文件选域:每个文件按下面这张「路径前缀 → 域」表取第一个命中的前缀,
+# 多个文件取并集。表里没有的 `tests/test_*.py` 直接按文件名归域,`src/peach/` 下的
+# 其余模块按「模块名 ↔ 测试文件名」推断(`media.py` → `test_media.py` → media)。
+# 仓库根的 Markdown 归 tooling:入口文件、README 与待办的门槛都在那个域里。
+AUTO_SCOPE_PREFIXES: tuple[tuple[str, str], ...] = (
+ ("src/peach/follow", "follow"),
+ ("src/peach/fanbox.py", "follow"),
+ ("src/peach/web_follow.py", "follow"),
+ ("src/peach/sync", "sync"),
+ ("src/peach/platform.py", "sync"),
+ ("src/peach/mount.py", "sync"),
+ ("src/peach/tray.py", "sync"),
+ ("src/peach/mdns.py", "sync"),
+ ("src/peach/netwatch.py", "sync"),
+ ("src/peach/certs.py", "sync"),
+ ("src/peach/web_", "catalog"),
+ ("src/peach/routes_", "catalog"),
+ ("web/", "web"),
+ ("frontend/", "web"),
+ ("scripts/", "tooling"),
+ ("pyproject.toml", "tooling"),
+ (".github/", "tooling"),
+ ("docs/", "tooling"),
+ (".claude/", "tooling"),
+)
+
+# AGENTS.md 规定必须跑 `full` 的面:迁移、共享测试设施、依赖清单。命中任一个就不再选域。
+FULL_ONLY_PREFIXES: tuple[str, ...] = (
+ "migrations/",
+ "tests/support/",
+ "package.json",
+ "package-lock.json",
+ "frontend/package.json",
+ "frontend/package-lock.json",
+)
+
def selected_files(scope: str) -> tuple[Path, ...]:
if scope == "full":
@@ -85,6 +124,23 @@ def selected_files(scope: str) -> tuple[Path, ...]:
return tuple(sorted(found))
+def scopes_of_test_file(name: str) -> tuple[str, ...]:
+ """一个 `tests/test_*.py` 文件名登记在哪些域里;公共门槛文件归 tooling。"""
+ scopes = tuple(scope for scope, patterns in SCOPES.items()
+ if any(fnmatch.fnmatch(name, pattern) for pattern in patterns))
+ if not scopes and any(fnmatch.fnmatch(name, pattern) for pattern in COMMON_PATTERNS):
+ return ("tooling",)
+ return scopes
+
+
+def scopes_of_module(stem: str) -> tuple[str, ...]:
+ """`src/peach/<stem>.py` 按测试文件名推断域:`test_<stem>.py` 或 `test_<stem>_*.py`。"""
+ exact, prefix = f"test_{stem}.py", f"test_{stem}_"
+ return tuple(scope for scope, patterns in SCOPES.items()
+ if any(fnmatch.fnmatch(exact, pattern) or pattern.startswith(prefix)
+ for pattern in patterns))
+
+
def unclassified_files() -> tuple[Path, ...]:
classified = set()
for scope in SCOPES:
@@ -92,15 +148,81 @@ def unclassified_files() -> tuple[Path, ...]:
return tuple(sorted(set(TESTS.glob("test_*.py")) - classified))
-def build_suite(scope: str) -> unittest.TestSuite:
+def scopes_for_changes(paths: Iterable[str]) -> tuple[tuple[str, ...], str]:
+ """纯函数:改动文件清单 → (要跑的域, 一行说明)。
+
+ 退化为 `full` 的条件只有两个:某个文件映射不到任何域,或改动触及必须 full 的面。
+ """
+ picked: dict[str, list[str]] = {}
+ full_reasons: list[str] = []
+ for raw in paths:
+ path = raw.replace("\\", "/").strip("/")
+ if not path:
+ continue
+ name = path.rsplit("/", 1)[-1]
+ if name == "conftest.py" or any(path.startswith(p) for p in FULL_ONLY_PREFIXES):
+ full_reasons.append(f"{path} 属于必须 full 的面")
+ continue
+ scopes: tuple[str, ...] = ()
+ if path.startswith("tests/test_") and path.endswith(".py"):
+ scopes = scopes_of_test_file(name)
+ elif "/" not in path and path.endswith(".md"):
+ scopes = ("tooling",)
+ else:
+ for prefix, scope in AUTO_SCOPE_PREFIXES:
+ if path.startswith(prefix):
+ scopes = (scope,)
+ break
+ if not scopes and path.startswith("src/peach/") and path.endswith(".py"):
+ scopes = scopes_of_module(name.removesuffix(".py"))
+ if not scopes:
+ full_reasons.append(f"{path} 映射不到任何域")
+ continue
+ for scope in scopes:
+ picked.setdefault(scope, []).append(path)
+ if full_reasons:
+ return ("full",), "Peach auto scope: full <- " + "; ".join(full_reasons)
+ if not picked:
+ return ("full",), "Peach auto scope: full <- 没有改动文件"
+ ordered = tuple(scope for scope in SCOPES if scope in picked)
+ detail = "; ".join(f"{scope}: {', '.join(picked[scope])}" for scope in ordered)
+ return ordered, f"Peach auto scope: {', '.join(ordered)} <- {detail}"
+
+
+def changed_files(root: Path = ROOT, base: str = "master") -> list[str]:
+ """分支相对 `base` 的提交、工作区已改动的文件和未跟踪文件,三者并集。"""
+ commands = (
+ ("git", "diff", "--name-only", "-z", f"{base}...HEAD"),
+ ("git", "diff", "--name-only", "-z", "HEAD"),
+ ("git", "ls-files", "--others", "--exclude-standard", "-z"),
+ )
+ found: set[str] = set()
+ for command in commands:
+ output = subprocess.run(command, cwd=root, capture_output=True, text=True,
+ encoding="utf-8", check=True).stdout
+ found.update(part for part in output.split("\0") if part)
+ return sorted(found)
+
+
+def resolve_auto_scope() -> tuple[tuple[str, ...], str]:
+ try:
+ paths = changed_files()
+ except (OSError, subprocess.CalledProcessError) as error:
+ return ("full",), f"Peach auto scope: full <- git 不可用({error})"
+ return scopes_for_changes(paths)
+
+
+def build_suite(*scopes: str) -> unittest.TestSuite:
loader = unittest.defaultTestLoader
suite = unittest.TestSuite()
+ files = sorted({path for scope in scopes for path in selected_files(scope)})
sys.path[:0] = [str(ROOT), str(TESTS)]
try:
- for path in selected_files(scope):
+ for path in files:
suite.addTests(loader.loadTestsFromModule(importlib.import_module(path.stem)))
- for test_id in SCOPE_TEST_IDS.get(scope, ()):
- suite.addTests(loader.loadTestsFromName(test_id))
+ for scope in scopes:
+ for test_id in SCOPE_TEST_IDS.get(scope, ()):
+ suite.addTests(loader.loadTestsFromName(test_id))
finally:
del sys.path[:2]
return suite
@@ -108,15 +230,19 @@ def build_suite(scope: str) -> unittest.TestSuite:
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser()
- parser.add_argument("--scope", choices=("full", *SCOPES), default="full")
+ parser.add_argument("--scope", choices=("full", "auto", *SCOPES), default="full")
parser.add_argument("--list-scopes", action="store_true")
args = parser.parse_args(argv)
if args.list_scopes:
- print("\n".join(("full", *SCOPES)))
+ print("\n".join(("full", "auto", *SCOPES)))
return 0
- files = selected_files(args.scope)
- print(f"Peach test scope: {args.scope} ({len(files)} files)", flush=True)
- result = unittest.TextTestRunner(verbosity=2).run(build_suite(args.scope))
+ scopes: tuple[str, ...] = (args.scope,)
+ if args.scope == "auto":
+ scopes, explanation = resolve_auto_scope()
+ print(explanation, flush=True)
+ files = {path for scope in scopes for path in selected_files(scope)}
+ print(f"Peach test scope: {' '.join(scopes)} ({len(files)} files)", flush=True)
+ result = unittest.TextTestRunner(verbosity=2).run(build_suite(*scopes))
return 0 if result.wasSuccessful() else 1
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index a7409ad8f..3d3aee1e6 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -242,7 +242,7 @@ class OperationalScriptTests(unittest.TestCase):
self.assertIn("$env:PYTHONPATH = $SourceRoot", windows)
self.assertIn("peach.__file__", windows)
self.assertIn("scripts\\test_runner.py --scope $Scope", windows)
- self.assertIn("ValidateSet('full', 'follow'", windows)
+ self.assertIn("ValidateSet('full', 'auto', 'follow'", windows)
self.assertNotIn("pytest", windows.lower())
# 两个平台各有一个入口,契约必须相同——否则「两边都要绿」只是句口号。
posix = (ROOT / "scripts" / "test.sh").read_text(encoding="utf-8")
@@ -251,6 +251,7 @@ class OperationalScriptTests(unittest.TestCase):
self.assertIn("peach.__file__", posix)
self.assertIn('scripts/test_runner.py --scope "$SCOPE"', posix)
self.assertIn('SCOPE="${1:-full}"', posix)
+ self.assertIn("full|auto|follow|catalog|media|sync|metadata|tooling|web)", posix)
self.assertNotIn("pytest", posix.lower())
# 文档里可以「提到」裸命令来说明它为什么不可信,但绝不能让它单独出现成为一条可照抄的指令。
# 判据因此不是黑名单,而是:凡出现该命令的行,必须在同一行指向某个正式入口。
@@ -290,8 +291,61 @@ class OperationalScriptTests(unittest.TestCase):
self.assertIn("test_migrations.py", follow)
self.assertNotIn("test_media.py", follow)
self.assertGreater(len(full), len(follow))
- self.assertEqual(runner.unclassified_files(), (),
- "每个测试文件都应属于至少一个功能域")
+ with redirect_stdout(io.StringIO()) as listed:
+ self.assertEqual(runner.main(["--list-scopes"]), 0)
+ self.assertEqual(listed.getvalue().split(), ["full", "auto", *runner.SCOPES])
+
+ def test_every_test_file_is_registered_in_a_scope(self):
+ """新测试文件必须登记进 `scripts/test_runner.py` 的域,否则只有 `full` 才跑到它。"""
+ runner = load_script("test_runner")
+ patterns = (*runner.COMMON_PATTERNS,
+ *(pattern for scopes in runner.SCOPES.values() for pattern in scopes))
+ orphans = sorted(
+ path.name for path in (ROOT / "tests").glob("test_*.py")
+ if not any(path.match(pattern) for pattern in patterns))
+ self.assertEqual(
+ orphans, [],
+ "这些测试文件不属于任何域,把它们登记进 scripts/test_runner.py 的 SCOPES"
+ "(或 COMMON_PATTERNS),否则只有 full 才跑到它们:\n " + "\n ".join(orphans))
+ self.assertEqual(runner.unclassified_files(), ())
+
+ def test_auto_scope_maps_changed_files_and_falls_back_to_full(self):
+ """`auto` 的选域是纯函数:喂文件清单,不碰 git。"""
+ runner = load_script("test_runner")
+ pick = runner.scopes_for_changes
+ # 前缀表:多个文件取并集,反斜杠路径也认。
+ self.assertEqual(pick(["src/peach/follow_store.py", "web/app.js"])[0], ("follow", "web"))
+ self.assertEqual(pick(["src\\peach\\tray.py"])[0], ("sync",))
+ self.assertEqual(pick(["scripts/probe.py", "pyproject.toml", ".github/workflows/test.yml"])[0],
+ ("tooling",))
+ self.assertEqual(pick(["README.md", "docs/STATUS.md", ".claude/skills/x/SKILL.md"])[0],
+ ("tooling",))
+ self.assertEqual(pick(["src/peach/web_entity.py", "src/peach/routes_pages.py"])[0],
+ ("catalog",))
+ self.assertEqual(pick(["src/peach/web_follow.py"])[0], ("follow",))
+ # 模块名 ↔ 测试文件名推断,登记在几个域就跑几个域。
+ self.assertEqual(pick(["src/peach/media.py"])[0], ("media",))
+ self.assertEqual(pick(["src/peach/jobs.py"])[0], ("media", "tooling"))
+ self.assertEqual(pick(["src/peach/metadata.py"])[0], ("metadata",))
+ # 测试文件按自己的文件名归域;公共门槛文件归 tooling。
+ self.assertEqual(pick(["tests/test_certs.py"])[0], ("sync", "tooling"))
+ self.assertEqual(pick(["tests/test_context_budget.py"])[0], ("tooling",))
+ scopes, why = pick(["src/peach/follow.py", "web/app.js"])
+ self.assertTrue(why.startswith("Peach auto scope: follow, web <- "), why)
+ self.assertIn("web: web/app.js", why)
+ # 退化为 full:必须 full 的面、映射不到的文件、没有改动。
+ for paths, fragment in ((["migrations/0099_next.sql"], "必须 full"),
+ (["tests/support/ledger.py"], "必须 full"),
+ (["tests/conftest.py"], "必须 full"),
+ (["package-lock.json"], "必须 full"),
+ (["frontend/package.json"], "必须 full"),
+ (["LICENSE"], "映射不到"),
+ (["src/peach/kanji.py", "web/app.js"], "映射不到"),
+ ([], "没有改动文件")):
+ scopes, why = pick(paths)
+ self.assertEqual(scopes, ("full",), paths)
+ self.assertTrue(why.startswith("Peach auto scope: full <- "), why)
+ self.assertIn(fragment, why)
def test_the_full_runner_can_import_repository_scripts(self):
runner = load_script("test_runner")