Peach: Local-first video metadata scraper and media manager.
fix(tooling): 测试入口自动准备隔离工作树依赖
longmeidaoa305b34f0806
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.mdindex 5e3959cad..8c303336b 100644--- a/docs/PRODUCT_BACKLOG.md+++ b/docs/PRODUCT_BACKLOG.md@@ -8,7 +8,7 @@| 顺序 | 优先级与范围 | 剩余工作与依赖 || --- | --- | --- |-| 1 | P1 开发流程 | 测试入口同步依赖;commit-msg 校验 trailer;操作 40 的首次导入超时 |+| 1 | P1 开发流程 | commit-msg 校验 trailer;操作 40 的首次导入超时 || 2 | P1 搜索与下载 | 43 的资源搜索接已有云下载,同批做 64 的来源性质标注;42 与 57 的本地下载、续传依赖操作 12 的流量与磁盘预算;骨架 1 还缺 51 的相似匹配、去重与人工替换确认 || 3 | P1 诊断 | 46 挂载探测 → 21 doctor 与分级健康检查 → 26 诊断页;12 的生产异常场景验收单列 || 4 | P2 元数据质量 | 44 → 操作 36 → 54 → 29;45 的回放与 58 的来源缺陷记录随解析器做;65、61 先核对成本与预算 |@@ -22,7 +22,7 @@| 项目 | 核对结果 | 证据 || --- | --- | --- |-| 测试入口 | 仍需处理:入口无依赖同步,commit-msg 钩子未设置 | `scripts/test.ps1`、`scripts/test.sh`、`scripts/githooks/` |+| 测试入口 | 隔离工作树自动同步 Python 依赖,主检出只读核对;commit-msg 钩子仍待设置 | `scripts/test_environment.py`、`scripts/test.ps1`、`scripts/test.sh`、`scripts/githooks/` || 操作 40 | 首次导入没有单独超时;本轮未重新触发偶发超时 | `frontend/test/islands.test.ts` 的三个 beforeAll || 42、43、64 | 云下载模型已具备;本地下载器、资源搜索与来源性质标注仍待接入 | `src/peach/downloads.py`、`src/peach/web_downloads.py`、前端下载设置 || 21、26、46 | 已有数据库就绪检查;doctor、统一诊断页与周期挂载探测仍待实现 | `src/peach/health.py`、CLI 与路由登记 |diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 2ac92246a..b4525fe64 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -88,7 +88,7 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/文档检查用 seiso(MIT,开发依赖),[文案门槛](../tests/test_copy_final_state.py) 调用其稳定规则;文件分类与第三方原文边界见 [seiso 配置](../seiso.toml),表达与人工复核见 [文档与界面文案](WRITING.md)。不自建 Markdown 文档职责解析器。-测试与集成用 `test_runner.py`、`agent_worktree.py`,进程互斥用开发依赖 `filelock` 的 [`FileLock`](https://py-filelock.readthedocs.io/en/stable/tutorials.html)。全量验证与集成共用一把锁、最多等待 30 分钟;验证持锁至记录写入完成。临时 Git 仓库回归覆盖互斥、等待和释放;代码、环境和范围记录属于 Peach 的集成约束。记录失效返回 `4`,Windows 托盘据此最多重试三轮,用例失败返回 `1`。+测试与集成用 `test_runner.py`、`agent_worktree.py`,进程互斥用开发依赖 `filelock` 的 [`FileLock`](https://py-filelock.readthedocs.io/en/stable/tutorials.html)。全量验证与集成共用一把锁、最多等待 30 分钟;验证持锁至记录写入完成。临时 Git 仓库回归覆盖互斥、等待和释放;代码、环境和范围记录属于 Peach 的集成约束。记录失效返回 `4`,Windows 托盘据此最多重试三轮,用例失败返回 `1`。两端测试入口通过 `test_environment.py` 复用现有 `find_uv` 与主检出 `Dependencies.check`;隔离工作树使用 uv 官方锁文件同步,不新增包管理实现或运行依赖。同步失败停止测试,主检出只读检查;策略与行为回归见 `test_test_environment.py`。### 播放、采集、发布与打包diff --git a/docs/TESTING.md b/docs/TESTING.mdindex afcc8532d..772cf8fed 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -107,7 +107,9 @@ macOS 按影响域验证:./scripts/test.sh```-显式全量用 Windows `-Scope full` 或 macOS 首参数 `full`。入口优先当前工作树环境、核对源码位置,并记录慢测试。依赖、代码在测试中变化会使证据失效;完成安装和编辑后再启动最终验证。+显式全量用 Windows `-Scope full` 或 macOS 首参数 `full`。入口通过 `scripts/test_environment.py` 准备 Python 依赖,再核对源码位置、选测并记录慢测试。隔离工作树按 `uv sync --locked --all-extras` 同步自己的 `.venv`;缺少本地环境时用主检出的 Python 启动准备,测试仍在新建的本地环境里运行。同步保留启动解释器的 Python 版本,忽略外部 `VIRTUAL_ENV` 和 `UV_PROJECT_ENVIRONMENT`,拒绝工作树环境指向主检出。++主检出只按 ADR-0091 只读检查依赖;缺包或检查失败时以 `3` 退出,依赖变更由重启流程执行。找不到 uv、锁文件过期或同步失败也会停止测试。前端依赖与构建仍按上文安装。依赖、代码在测试中变化会使证据失效;完成安装和编辑后再启动最终验证。本机全量验证与 `integrate` 共用 `full-suite.lock`,从取得代码和环境快照一直持有到记录写入完成。锁忙时打印持有者并等待,最长 30 分钟;超时退出且不执行测试或合并。集成事务本身仍由diff --git a/scripts/test.ps1 b/scripts/test.ps1index 6693098a8..b4b268ef1 100644--- a/scripts/test.ps1+++ b/scripts/test.ps1@@ -49,6 +49,9 @@ if (-not (Get-Command openssl.exe -ErrorAction SilentlyContinue)) {Push-Location $WorktreeRoottry {+ & $Python -X utf8 scripts\test_environment.py $WorktreeRoot $MainRoot+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+ $Python = $LocalPython$LoadedModule = (& $Python -c 'import peach; print(peach.__file__)').Trim()if ($LASTEXITCODE -ne 0 -or -not $LoadedModule) {throw '无法导入当前工作树中的 peach。'diff --git a/scripts/test.sh b/scripts/test.shindex 9fa88ee08..a0c6426a8 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -53,6 +53,8 @@ export PYTHONPATH="$SOURCE_ROOT"export PYTHONIOENCODING=utf-8cd "$WORKTREE_ROOT"+"$PYTHON" -X utf8 scripts/test_environment.py "$WORKTREE_ROOT" "$MAIN_ROOT"+PYTHON="$WORKTREE_ROOT/.venv/bin/python"LOADED_MODULE="$("$PYTHON" -c 'import peach; print(peach.__file__)')"if [[ "$LOADED_MODULE" != "$SOURCE_ROOT/"* ]]; thenecho "测试加载了错误源码:$LOADED_MODULE;预期位于 $SOURCE_ROOT" >&2diff --git a/scripts/test_environment.py b/scripts/test_environment.pynew file mode 100644index 000000000..dab5e5554--- /dev/null+++ b/scripts/test_environment.py@@ -0,0 +1,60 @@+"""正式测试入口的依赖准备,只在隔离工作树自动同步环境。"""+from __future__ import annotations++import os+import shutil+import subprocess+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+if str(ROOT / "src") not in sys.path:+ sys.path.insert(0, str(ROOT / "src"))++from peach.runtime_prepare import Dependencies, find_uv+++def prepare(root: Path, main: Path, *, run=subprocess.run, which=shutil.which,+ environ=None) -> None:+ """准备完成才允许加载测试运行器;主检出依赖只读检查。"""+ root, main = root.resolve(), main.resolve()+ if not (root / "uv.lock").is_file():+ raise RuntimeError(f"未取得测试依赖锁文件:{root / 'uv.lock'}")+ environment = dict(os.environ if environ is None else environ)+ for name in ("VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT"):+ environment.pop(name, None)+ if root == main:+ step = Dependencies(root, run=run, which=which, environ=environment, frozen=False).check()+ if step.state != "current":+ raise RuntimeError(f"主检出依赖未就绪:{step.message};请在隔离工作树测试,主检出依赖由重启流程同步。")+ print(step.message, flush=True)+ return+ if (root / ".venv").resolve() != root / ".venv":+ raise RuntimeError("工作树 .venv 指向外部目录;不能同步主检出或其他工作树的环境。")+ uv = find_uv(which=which, environ=environment)+ if uv is None:+ raise RuntimeError("未取得 uv:PATH 与 WinGet 安装目录里都没有。")+ print(f"按 uv.lock 同步测试环境:{root / '.venv'}", flush=True)+ result = run([str(uv), "sync", "--locked", "--all-extras", "--python", sys.executable,+ "--project", str(root)], cwd=str(root), env=environment, check=False)+ if result.returncode:+ raise RuntimeError(f"测试依赖同步失败(退出码 {result.returncode});未启动测试。")+++def main(argv=None) -> int:+ import argparse++ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("root", type=Path)+ parser.add_argument("main_root", type=Path)+ args = parser.parse_args(argv)+ try:+ prepare(args.root, args.main_root)+ except (RuntimeError, OSError) as error:+ print(str(error), file=sys.stderr, flush=True)+ return 3+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex d53fd1bad..afe53aadd 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -101,7 +101,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_seed_pack.py", "test_seed_followup.py"),"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_script_policy.py","test_scan.py", "test_record_rehome.py", "test_wants.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",- "test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py",+ "test_agent_worktree.py", "test_test_evidence.py", "test_test_environment.py", "test_dependency_policy.py","test_version_bump.py", "test_changelog.py", "test_release_due.py","test_restart_windows_tray.py", "test_deploy_windows_tray.py", "test_runtime_prepare.py","test_buildinfo.py", "test_versioning.py",@@ -304,7 +304,7 @@ AUTO_SCOPE_PREFIXES: tuple[tuple[str, str | tuple[str, ...]], ...] = (FULL_ONLY_PREFIXES: tuple[str, ...] = ("pyproject.toml","scripts/test_runner.py", "scripts/test_evidence.py", "scripts/test.ps1", "scripts/test.sh",- "scripts/ci_plan.py", "uv.lock",+ "scripts/ci_plan.py", "scripts/test_environment.py", "uv.lock","migrations/","tests/support/","package.json",diff --git a/tests/test_test_environment.py b/tests/test_test_environment.pynew file mode 100644index 000000000..fd2c39576--- /dev/null+++ b/tests/test_test_environment.py@@ -0,0 +1,128 @@+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++from scripts import test_environment+from support.gitrepo import seed_repository+++class TestEnvironmentTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.folder = Path(temporary.name).resolve()+ self.main = self.folder / "main"+ self.worker = self.folder / "worker"+ for root in (self.main, self.worker):+ root.mkdir()+ (root / "uv.lock").write_text("version = 1\n", encoding="utf-8")+ (self.main / ".venv").mkdir()+ (self.main / ".venv" / "pyvenv.cfg").write_text("home = python\n", encoding="utf-8")++ def prepare(self, root, run, **kwargs):+ return test_environment.prepare(+ root, self.main, run=run, which=lambda name: "uv",+ environ={"VIRTUAL_ENV": str(self.main / ".venv"),+ "UV_PROJECT_ENVIRONMENT": str(self.main / ".venv")}, **kwargs)++ def test_worktree_sync_creates_its_own_environment_and_ignores_external_overrides(self):+ def install(command, **kwargs):+ destination = Path(command[command.index("--project") + 1])+ (destination / ".venv").mkdir()+ (destination / ".venv" / "installed").touch()+ self.assertNotIn("VIRTUAL_ENV", kwargs["env"])+ self.assertNotIn("UV_PROJECT_ENVIRONMENT", kwargs["env"])+ self.assertIn("--locked", command)+ self.assertIn("--all-extras", command)+ self.assertNotIn("--check", command)+ return subprocess.CompletedProcess(command, 0)+ self.prepare(self.worker, install)+ self.assertTrue((self.worker / ".venv" / "installed").is_file())+ self.assertFalse((self.main / ".venv" / "installed").exists())++ def test_main_checkout_only_checks_the_running_environment(self):+ run = mock.Mock(return_value=subprocess.CompletedProcess([], 0, "", ""))+ self.prepare(self.main, run)+ self.assertEqual(run.call_count, 1)+ self.assertIn("--check", run.call_args.args[0])+ self.assertIn("--no-install-project", run.call_args.args[0])++ def test_outdated_main_environment_stops_before_any_sync(self):+ run = mock.Mock(return_value=subprocess.CompletedProcess(+ [], 1, "The environment is outdated", ""))+ with self.assertRaisesRegex(RuntimeError, "重启流程"):+ self.prepare(self.main, run)+ self.assertEqual(run.call_count, 1)+ self.assertIn("--check", run.call_args.args[0])++ def test_failed_sync_does_not_report_ready(self):+ run = mock.Mock(return_value=subprocess.CompletedProcess([], 2))+ with self.assertRaisesRegex(RuntimeError, "依赖同步失败"):+ self.prepare(self.worker, run)++ def test_missing_lock_or_uv_stops_before_starting_tests(self):+ run = mock.Mock()+ (self.worker / "uv.lock").unlink()+ with self.assertRaisesRegex(RuntimeError, "uv.lock"):+ self.prepare(self.worker, run)+ with self.assertRaisesRegex(RuntimeError, "uv"):+ test_environment.prepare(self.main, self.main, run=run,+ which=lambda name: None, environ={})+ run.assert_not_called()++ def test_entrypoint_requires_successful_preparation_before_loading_the_runner(self):+ shell = shutil.which("pwsh" if os.name == "nt" else "bash")+ if shell is None:+ self.skipTest("本机未取得测试入口所需 shell")+ root = seed_repository(self.folder / "entry", {+ "src/peach/__init__.py": "",+ "scripts/test_environment.py": (+ "from pathlib import Path\n"+ "Path('prepared').touch()\n"+ "raise SystemExit(int(Path('prepare-exit').read_text()))\n"),+ "scripts/test_runner.py": (+ "import json, sys\nfrom pathlib import Path\n"+ "assert Path('prepared').exists()\n"+ "Path('runner-args').write_text(json.dumps(sys.argv[1:]))\n"),+ }, "seed")+ subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(root / ".venv")],+ check=True, capture_output=True, text=True, encoding="utf-8")+ script = "test.ps1" if os.name == "nt" else "test.sh"+ shutil.copy2(test_environment.ROOT / "scripts" / script, root / "scripts" / script)+ command = ([shell, "-NoProfile", "-File", str(root / "scripts" / script),+ "-Scope", "checks", "-Base", "branch with space", "-Jobs", "1"]+ if os.name == "nt" else+ [shell, str(root / "scripts" / script), "checks", "--base", "branch with space",+ "--jobs", "1"])+ for code in (3, 0):+ with self.subTest(preparation_exit=code):+ (root / "prepare-exit").write_text(str(code), encoding="utf-8")+ result = subprocess.run(command, cwd=root, capture_output=True, text=True,+ encoding="utf-8", check=False)+ self.assertEqual(result.returncode, code, result.stdout + result.stderr)+ if code:+ self.assertFalse((root / "runner-args").exists())+ else:+ arguments = json.loads((root / "runner-args").read_text())+ self.assertEqual(arguments[arguments.index("--base") + 1], "branch with space")+ self.assertEqual(arguments[arguments.index("--scope") + 1], "checks")++ def test_worktree_environment_cannot_resolve_to_the_production_environment(self):+ # 路径解析也覆盖 Windows junction;不要求运行测试的账户能建立符号链接。+ resolve = Path.resolve+ shared = self.main / ".venv"+ def resolved(path, *args, **kwargs):+ return shared if path == self.worker / ".venv" else resolve(path, *args, **kwargs)+ run = mock.Mock()+ with mock.patch.object(Path, "resolve", resolved):+ with self.assertRaisesRegex(RuntimeError, "主检出"):+ self.prepare(self.worker, run)+ run.assert_not_called()