Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(test): 统一测试覆盖检查点与结果复用

longmeidao676a7f63c523
diff --git a/docs/REUSE.md b/docs/REUSE.md
index c26bb264e..627c3c896 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -1,5 +1,13 @@
# 复用清单
+## 正式测试记录与中断恢复
+
+测试结果继续复用 Python ≥3.14 标准库 `unittest`、`hashlib`、`json` 和项目的内容快照、影响域映射与外部测试结果。互斥复用既有 `filelock 4.2.0`,分片退出后回收其进程树复用开发依赖 `psutil 7.2.2`;版本与许可沿用锁定依赖及第三方许可清单,不新增运行时依赖。Peach 保留输入身份、逐文件覆盖、完成报告、批次来源和 `ready`/`integrate` 验收规则;串行、并行、浏览器与 Vitest 使用同一个恢复模型。
+
+候选比较包括官方 [pytest 缓存文档](https://doc.pytest.org/en/stable/how-to/cache.html) 与 [Turborepo 缓存文档](https://turborepo.dev/docs/crafting-your-repository/caching)。pytest 的失败项选择不能替代当前内容绑定的成功覆盖,不迁移测试框架;Turborepo 的任务缓存不能直接接管 Python 用例结果及集成门槛,不引入其运行时或源码。外部源码版本与许可证未作为采用依据,本次未复制这些项目的实现。
+
+临时输入实证覆盖跨工作树运行时、安装锁 JSON、CI 运行信息、多域混合失败及多份记录搜索;行为回归覆盖失败与中断恢复、旧失败阻止成功恢复、原时间继承、外部文件完成证明、Python 容器后置检查及全量来源约束。运行时、实际依赖、共享夹具、未知输入、执行模式、过期或未来时间变化仍使相关证明失效。测试设施不读写真实 ledger。
+
## 媒体目录与整理路径映射
PikPak 整理复用项目已有 `PushDiscoverySettings`、`CloudPrefix` 与 `map_cloud_path`,与推送发现共用配置,不引入第二份盘符或 CloudDrive 路径表。CloudDrive RPC 继续使用现有固定版本的 gRPC/protobuf;路径归属与账号内 WebDAV 目录核验属于 Peach 的写入边界。不同盘符、子目录、云端名称、越界与冲突由临时夹具和模拟 RPC 验证,不触碰真实账号或账本。
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 4395df0ca..a5b60e632 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -210,7 +210,13 @@ Windows Release 工作流使用 `uv sync --locked --all-extras` 准备完整依
macOS Release 使用 `macos-15`(Apple Silicon)和 `macos-15-intel`(Intel)分别构建,解释器、依赖与目标架构必须一致。独立验收任务只下载候选制品与冒烟脚本,挂载只读 DMG,核对 Applications 链接、许可证、签名与原生架构,再执行 `scripts/smoke_macos.py`。该脚本将应用移到源码树外,在移除开发工具的 PATH 下验证首次设置、迁移、单机账本、登录、前端资源与配置保存,数据全部使用临时目录。所有平台验收成功才发布;普通 push 不构建安装包,手动运行 Release 不上传公开资产。
-`auto` 从同环境、24 小时内的记录计算差异:有效全量基线保留原时间戳;有效局部基线只复用未受差异影响且本次需要的域。相同代码状态补跑缺少的域。新增、删除与修改文件均参与比较;共享设施、未知影响面和环境差异不能复用局部记录。局部记录不会变成全量,继承时间戳不延长有效期。单域失败撤销该域与全量证明,保留其他域的原成功时间;失败域必须补测,不能从旧基线恢复。全量失败撤销所有证明。`-Fresh` 与显式 `full` 始终实际执行。每次签发记录时清退写盘超过 24 小时的记录、持锁说明与残留的半成品文件,这些记录已没有可复用的时间戳;锁文件和非记录文件不动。
+`auto` 扫描同环境的有效记录,按测试文件合并 24 小时内、未受输入差异影响的成功结果;记录数量没有固定搜索上限。每项保留原通过时间,最新的失败或未完成状态阻止旧成功结果恢复。缺少、损坏、过期或未来时间的证明不计入覆盖;单份损坏记录不影响其他候选。`-Fresh` 与显式 `full` 始终实际执行请求范围。
+
+正式父运行在开始时原子保存待验证状态,每个分片完成后立即保存检查点。失败批次仍保留成功文件及其时间;快速门槛失败时,其余文件保持未完成。进程中断后,下一次 `auto` 补齐缺少的文件,串行与并行使用相同结果模型。分片报告必须完整且格式有效;异常退出不能签发该片的整体成功。分片写出完成报告后仍未退出的进程,等待 15 秒后回收该片的进程树,不给尚在执行的测试设置额外时限。
+
+浏览器与 Vitest 容器内按外部测试文件保存完成结果,只有逐条输出不能证明整个文件完成。恢复计划绑定当前输入快照、完整文件集合及每个省略项的成功时间。Python 容器用例自身也必须有成功证明,才能连同其外部文件一起省略;容器的后置检查失败仍需补测。外部选择仅由正式父运行生成,`Focus` 和独立 CI 分片不签发正式记录。
+
+全量证明还要求所有文件与容器检查属于同一个完整批次。独立局部运行可以补齐所需域,不能拼成 `full`;有完整批次来源的中断或失败运行,补齐缺少项后可恢复全量证明。每次写入时清退写盘超过 24 小时的记录、持锁说明与残留临时文件;锁文件和非记录文件不动。
选测比较文件内容:Python 只有注释或格式变化、npm 清单只有 description/keywords 变化、TOML 只有注释或格式变化时选 `checks`。Python docstring、运行时字串和类型注释属于有效内容。Python 构建元数据变化选 `packaging`,实际依赖变化、文件模式变化、解析失败和未知影响面保留完整验证。
@@ -218,7 +224,7 @@ macOS Release 使用 `macos-15`(Apple Silicon)和 `macos-15-intel`(Intel
`src/peach/` 下按名字推不出测试文件的模块,取直接导入它的测试所在的域,并上直接导入它的源码文件按同一套规则推出的域;互相导入的一组模块合起来算。导入者推不出域、谁都不导入它,或共享测试设施 `tests/support` 用到它时仍 `full`。不沿导入链一路扩散:函数里的延迟导入把几乎所有模块连成一团,传递闭包等于全量。随应用分发的 `resources/` 按加载它的模块与打包面选域;`.gitlab-ci.yml` 与 `MANIFEST.in` 在本机选 `packaging` 与 `tooling`(主线流水线改 `.gitlab-ci.yml` 时三平台仍跑全量);只登记在 `core` 或 `packaging` 的测试文件改动时跑登记它的那个域。
-完整批次通过但运行中发生局部改动时,保留未受影响测试文件的结果和原时间;退出 `4`,随后 `auto` 只补缺少的域。只有同一完整批次覆盖所有测试文件才恢复 `full`,局部批次不能拼成全量证明。环境、共享逻辑或未知范围变化清空保留结果;失败和过期结果不能复用。
+运行中输入改变时,无论该批次是否全部通过,都按差异保留未受影响的成功结果和原时间;退出 `4`,随后 `auto` 补齐缺少项。独立 Python 测试文件的逻辑变化使该文件、直接或间接导入它的测试及公共门槛失效;浏览器测试文件变化使该文件及相应容器检查失效。共享设施、未知范围、执行模式或环境变化仍按完整影响范围重新验证。
测试记录格式升级时,主检出的入口可能无法识别新格式。先在工作树通过 `ready`,再由主检出调用该工作树中已验收的 `scripts/agent_worktree.py`,用 `--repo` 指定主检出并执行 `integrate`。该方式仍检查测试记录、README 声明、目标分支和集成锁;不要手工改写记录或跳过门槛。集成后主检出使用同一版本的入口。
@@ -227,8 +233,7 @@ PR 的浏览器 CI 根据界面、Web API、认证与浏览器用例选择;普
## 记录的环境身份
记录只在「代码、环境、范围」三项都匹配时可复用,环境那一项由 `scripts/test_evidence.py`
-的 `environment()` 算成一个摘要:解释器与已安装包、平台、`PEACH_*` 等环境变量、前端
-`node_modules` 锁,以及 node/npm/git/ffmpeg/ffprobe/openssl 六个外部工具。
+的 `environment()` 算成一个摘要:Python 版本、实现与运行时文件内容、规范化的已安装包名称和版本、平台、影响行为的环境变量、前端安装锁的规范化 JSON、实际 Chrome 文件内容,以及 node/npm/git/ffmpeg/ffprobe/openssl 六个外部工具。相同运行时和依赖位于不同工作树、安装锁只有排序或缩进差异、CI 运行编号或工作目录变化,不改变环境身份。CI 工作流和 job 职责、浏览器安装状态与内容变化仍参与判断。
测试入口强制设置的 `PEACH_REPORTING_TEST_MODE` 防外发标记不参与环境选择;入口源码仍参与代码快照。
uv 只探针、不进指纹:它负责建环境,装出来的解释器与包已经逐个记在摘要里,而它自己由
diff --git a/scripts/test_environment_identity.py b/scripts/test_environment_identity.py
new file mode 100644
index 000000000..94982029a
--- /dev/null
+++ b/scripts/test_environment_identity.py
@@ -0,0 +1,93 @@
+"""测试运行时的内容身份与浏览器定位。"""
+from __future__ import annotations
+
+from functools import lru_cache
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import sys
+
+
+RUN_METADATA = frozenset({
+ 'GITHUB_RUN_ID', 'GITHUB_RUN_NUMBER', 'GITHUB_RUN_ATTEMPT', 'GITHUB_WORKSPACE',
+ 'GITHUB_SHA', 'GITHUB_REF', 'GITHUB_REF_NAME', 'GITHUB_HEAD_REF', 'GITHUB_BASE_REF',
+ 'GITHUB_OUTPUT', 'GITHUB_ENV', 'GITHUB_STEP_SUMMARY', 'GITHUB_PATH',
+ 'CI_JOB_ID', 'CI_JOB_URL', 'CI_PIPELINE_ID', 'CI_PIPELINE_IID', 'CI_PIPELINE_URL',
+ 'CI_PROJECT_DIR', 'CI_COMMIT_SHA', 'CI_COMMIT_SHORT_SHA', 'CI_COMMIT_REF_NAME',
+ 'CI_COMMIT_TIMESTAMP', 'CI_PIPELINE_CREATED_AT',
+ 'CI_JOB_STARTED_AT', 'CI_COMMIT_BEFORE_SHA', 'CI_COMMIT_MESSAGE', 'CI_COMMIT_TITLE',
+ 'CI_COMMIT_DESCRIPTION', 'CI_COMMIT_AUTHOR', 'CI_CONCURRENT_ID', 'CI_CONCURRENT_PROJECT_ID',
+})
+CREDENTIAL_FLAGS = frozenset({'GITHUB_TOKEN', 'CI_JOB_TOKEN'})
+ENTRY_FLAGS = frozenset({'PYTHONPATH', 'PEACH_REPORTING_TEST_MODE', 'PEACH_TEST_RUN_TEMP',
+ 'PEACH_E2E_CHROME'})
+
+
+@lru_cache(maxsize=128)
+def _file_digest(path: str, modified: int, size: int) -> str:
+ with open(path, 'rb') as stream:
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
+
+
+def file_identity(path) -> dict:
+ if not path:
+ return {'available': False}
+ try:
+ item = Path(path)
+ stat = item.stat()
+ return {'sha256': _file_digest(str(item), stat.st_mtime_ns, stat.st_size)}
+ except OSError as error:
+ return {'unavailable': type(error).__name__}
+
+
+def runtime_identity(identity: dict, executable: Path) -> dict:
+ return {'version': identity['version'], 'implementation': identity.get('implementation'),
+ 'cache_tag': identity.get('cache_tag'),
+ 'binary': file_identity(identity.get('base_executable') or executable),
+ 'library': file_identity(identity.get('library'))}
+
+
+def package_identity(distributions) -> list:
+ return sorted({(re.sub(r'[-_.]+', '-', item.metadata.get('Name', '')).casefold(), item.version)
+ for item in distributions if item.metadata.get('Name', '').casefold() != 'peach'})
+
+
+def install_identity(path: Path) -> dict:
+ try:
+ data = json.loads(path.read_text(encoding='utf8'))
+ if not isinstance(data, dict):
+ raise ValueError('安装锁必须为对象')
+ return {'lock': data}
+ except FileNotFoundError:
+ return {'available': False}
+ except (OSError, ValueError, UnicodeError):
+ return {'invalid': file_identity(path)}
+
+
+def environment_flags(environ=None) -> dict:
+ values = os.environ if environ is None else environ
+ return {key: bool(value) if key in CREDENTIAL_FLAGS else value for key, value in values.items()
+ if key.startswith(('PEACH_', 'CI', 'GITHUB_', 'PYTHON'))
+ and key not in RUN_METADATA | ENTRY_FLAGS and (key not in CREDENTIAL_FLAGS or value)}
+
+
+def chrome_executable() -> str | None:
+ """读取显式浏览器路径,否则查找各平台安装位置。"""
+ explicit = os.environ.get('PEACH_E2E_CHROME', '').strip()
+ if explicit:
+ return explicit if Path(explicit).is_file() else None
+ candidates = []
+ if os.name == 'nt':
+ for variable in ('PROGRAMFILES', 'PROGRAMFILES(X86)', 'LOCALAPPDATA'):
+ base = os.environ.get(variable)
+ if base:
+ candidates.append(Path(base) / 'Google/Chrome/Application/chrome.exe')
+ elif sys.platform == 'darwin':
+ candidates.append(Path('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'))
+ else:
+ candidates.extend(Path(found) for name in ('google-chrome', 'google-chrome-stable')
+ if (found := shutil.which(name)))
+ return next((str(path) for path in candidates if path.is_file()), None)
diff --git a/scripts/test_evidence.py b/scripts/test_evidence.py
index e7152644b..585112e97 100644
--- a/scripts/test_evidence.py
+++ b/scripts/test_evidence.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import importlib.metadata
import json
+import math
import os
import platform
import re
@@ -19,7 +20,7 @@ from pathlib import Path
from filelock import FileLock, Timeout
-from . import change_impact
+from . import change_impact, test_environment_identity
def git(root: Path, *args: str) -> str:
@@ -90,7 +91,12 @@ def interpreter(root: Path) -> Path:
@lru_cache(maxsize=16)
def python_identity(executable: str, stamp: int) -> dict:
return json.loads(subprocess.run(
- [executable, "-c", "import json,sys,site; print(json.dumps({'version':sys.version,'sites':site.getsitepackages()}))"],
+ [executable, "-c", "import json,sys,site,sysconfig,pathlib; "
+ "library=pathlib.Path(sysconfig.get_config_var('LIBDIR') or pathlib.Path(sys._base_executable).parent)"
+ "/(sysconfig.get_config_var('LDLIBRARY') or 'python'+str(sys.version_info.major)+str(sys.version_info.minor)+'.dll'); "
+ "print(json.dumps({'version':sys.version,'sites':site.getsitepackages(),"
+ "'implementation':sys.implementation.name,'cache_tag':sys.implementation.cache_tag,"
+ "'base_executable':sys._base_executable,'library':str(library) if library.is_file() else None}))"],
check=True, capture_output=True, text=True, encoding="utf-8").stdout)
@@ -161,19 +167,17 @@ def environment(root: Path) -> str:
# 同一个目录可在 sys.path 中出现多次;依赖身份取集合,版本变化仍改变指纹。
python = interpreter(root)
identity = python_identity(str(python), python.stat().st_mtime_ns)
- installed = sorted({(d.metadata.get("Name", ""), d.version)
- for d in importlib.metadata.distributions(path=identity["sites"])
- if d.metadata.get("Name", "").casefold() != "peach"})
+ installed = test_environment_identity.package_identity(
+ importlib.metadata.distributions(path=identity["sites"]))
node_lock = root / "frontend/node_modules/.package-lock.json"
return digest({
- "schema": 7, "python": identity["version"], "executable": str(python),
+ "schema": 8, "python": test_environment_identity.runtime_identity(identity, python),
"platform": platform.platform(), "packages": installed, "tools": tools,
- "node_modules": hashlib.sha256(node_lock.read_bytes()).hexdigest() if node_lock.exists() else None,
+ "node_modules": test_environment_identity.install_identity(node_lock),
+ "browser": test_environment_identity.file_identity(test_environment_identity.chrome_executable()),
# 测试入口强制设置防外发标记与本次运行独占的临时目录;入口源码已进快照,它们不是调用方
# 选择的运行环境。临时目录每次都是新路径,算进来的话签出的记录键在 ready 时永远对不上。
- "flags": {k: v for k, v in os.environ.items()
- if k.startswith(("PEACH_", "CI", "GITHUB_", "PYTHON"))
- and k not in {"PYTHONPATH", "PEACH_REPORTING_TEST_MODE", "PEACH_TEST_RUN_TEMP"}},
+ "flags": test_environment_identity.environment_flags(),
})
@@ -187,7 +191,7 @@ def inputs(root: Path) -> dict:
"state": digest([digest(content), dependencies])}
-def recent_records(folder: Path, limit: int = 32) -> list[Path]:
+def recent_records(folder: Path, limit: int | None = None) -> list[Path]:
"""最近写入的测试记录。同目录还有持锁说明 `*.lock.holder.json`,名字不是 state 摘要,
不算记录;记录和说明都会被别的进程随时删掉,列出后才消失的文件跳过。"""
found = []
@@ -198,7 +202,8 @@ def recent_records(folder: Path, limit: int = 32) -> list[Path]:
found.append((path.stat().st_mtime, path))
except FileNotFoundError:
continue
- return [path for _, path in sorted(found, reverse=True)[:limit]]
+ ordered = sorted(found, reverse=True)
+ return [path for _, path in (ordered[:limit] if limit is not None else ordered)]
def baselines(root: Path, current: dict, *, partial: bool = False):
@@ -245,19 +250,79 @@ def prune_expired(folder: Path, now: float | None = None) -> int:
def read(root: Path, state: str) -> dict:
try:
record = json.loads((evidence_dir(root) / f"{state}.json").read_text(encoding="utf-8"))
- if not isinstance(record, dict) or not isinstance(record.get("validated"), dict):
+ if (not isinstance(record, dict) or not isinstance(record.get("validated"), dict)
+ or not isinstance(record.get("coverage", {}), dict)
+ or not valid_manifest(record.get('manifest'))
+ or not isinstance(record.get("environment"), str)
+ or not isinstance(record.get('units', {}), dict)
+ or not valid_record_fields(record)):
return {}
- if record.get("state") == state:
+ expected = digest([digest(record['manifest']), record['environment']])
+ if record.get("state") == state == expected:
record["passed"] = [scope for scope, stamp in record["validated"].items()
if isinstance(stamp, (float, int)) and 0 <= time.time() - stamp < VALID_SECONDS]
record["coverage"] = {name: stamp for name, stamp in record.get("coverage", {}).items()
if isinstance(stamp, (float, int)) and 0 <= time.time() - stamp < VALID_SECONDS}
+ units = live_units(record.get('units', {}))
+ if units is None:
+ return {}
+ record['units'] = units
return record
- except (OSError, ValueError, KeyError, TypeError):
+ except (OSError, ValueError, KeyError, TypeError, RecursionError):
pass
return {}
+def valid_record_fields(record) -> bool:
+ scopes = record.get('failed_scopes', [])
+ cohort = record.get('cohort')
+ finished = record.get('finished', 0)
+ return (isinstance(scopes, list) and all(isinstance(scope, str) for scope in scopes)
+ and all(isinstance(scope, str) for scope in record['validated'])
+ and (cohort is None or isinstance(cohort, str) and bool(_STATE.fullmatch(cohort)))
+ and type(finished) in (int, float) and math.isfinite(finished))
+
+
+def valid_manifest(manifest) -> bool:
+ if not isinstance(manifest, dict) or not isinstance(manifest.get('files'), dict):
+ return False
+ if not isinstance(manifest.get('signatures', {}), dict):
+ return False
+ for name, value in manifest['files'].items():
+ if not isinstance(name, str):
+ return False
+ if isinstance(value, str) and (value == 'deleted' or value.startswith('link:')):
+ continue
+ if (not isinstance(value, list) or len(value) != 3 or type(value[0]) is not int
+ or not isinstance(value[1], str) or not _STATE.fullmatch(value[1])
+ or value[2] not in {'100644', '100755'}):
+ return False
+ return all(isinstance(name, str) and isinstance(value, dict)
+ and all(isinstance(key, str) and isinstance(stamp, str) and _STATE.fullmatch(stamp)
+ for key, stamp in value.items())
+ for name, value in manifest.get('signatures', {}).items())
+
+
+def live_units(units: dict) -> dict | None:
+ now, kept = time.time(), {}
+ for name, row in units.items():
+ if (not isinstance(name, str) or not isinstance(row, dict)
+ or row.get('outcome') not in {'pass', 'fail', 'unknown'}
+ or type(row.get('at')) not in (int, float) or not math.isfinite(row['at'])):
+ return None
+ if 0 <= now - row['at'] < VALID_SECONDS:
+ kept[name] = row
+ return kept
+
+
+def candidates(root: Path, current: dict):
+ """同环境的有效记录,包括需要继续阻止旧结果复活的失败记录。"""
+ for path in recent_records(evidence_dir(root)):
+ record = read(root, path.stem)
+ if record.get('environment') == current['environment']:
+ yield record
+
+
def covers(record: dict, scopes: tuple[str, ...]) -> bool:
passed = set(record.get("passed", ()))
return "full" in passed or set(scopes).issubset(passed)
@@ -266,7 +331,8 @@ def covers(record: dict, scopes: tuple[str, ...]) -> bool:
def write(root: Path, state: str, scopes: tuple[str, ...], *, success: bool,
elapsed: float, slowest: list, count: int, previous: dict | None = None,
context: dict | None = None, baseline: dict | None = None,
- cohort: str | None = None, coverage: dict | None = None, flaky: list | None = None) -> None:
+ cohort: str | None = None, coverage: dict | None = None, flaky: list | None = None,
+ units: dict | None = None) -> None:
folder = evidence_dir(root)
folder.mkdir(parents=True, exist_ok=True)
prior = previous if previous is not None else read(root, state)
@@ -285,6 +351,7 @@ def write(root: Path, state: str, scopes: tuple[str, ...], *, success: bool,
validated.update({scope: time.time() for scope in scopes})
record = {**(context or inputs(root)), "state": state, "validated": validated, "finished": time.time(),
"cohort": cohort, "coverage": coverage or {},
+ 'units': ({} if scopes else prior.get('units', {})) if units is None else units,
"baseline": baseline.get("state") if baseline else None,
"failed_scopes": sorted(failed),
"elapsed": elapsed, "count": count, "slowest": slowest,
diff --git a/scripts/test_history.py b/scripts/test_history.py
index 2f4b5a2e6..3357571c3 100644
--- a/scripts/test_history.py
+++ b/scripts/test_history.py
@@ -75,6 +75,8 @@ def nested() -> bool:
def record_external(rows: list[dict]) -> None:
"""vitest 与浏览器用例在测试进程里交上来的逐条结果。"""
+ if _running > 1:
+ return
_external.extend(rows)
@@ -161,6 +163,23 @@ def vitest_rows(report: dict, frontend: Path) -> list[dict]:
return rows
+def file_result(kind: str, path: str, success: bool, seconds: float = 0) -> dict:
+ """完整外部文件的终态,区别于尚未收齐的叶子结果。"""
+ return {**result(f'{kind}:{path} > 文件结果', 'pass' if success else 'fail', seconds),
+ 'file_complete': True}
+
+
+def vitest_files(report: dict, frontend: Path) -> list[dict]:
+ rows = []
+ for suite in report.get('testResults', ()):
+ try:
+ path = Path(suite['name']).relative_to(frontend).as_posix()
+ except (ValueError, KeyError):
+ continue
+ rows.append(file_result('vitest', path, suite.get('status') == 'passed'))
+ return rows
+
+
_TAP_RESULT = re.compile(r"^(?P<indent>\s*)(?P<not>not )?ok \d+ - (?P<name>.*?)(?P<skip> # (?:SKIP|TODO)\b.*)?$")
diff --git a/scripts/test_progress.py b/scripts/test_progress.py
deleted file mode 100644
index 9fa8ce3c2..000000000
--- a/scripts/test_progress.py
+++ /dev/null
@@ -1,69 +0,0 @@
-"""保留完整测试批次中未受影响的文件结果,不延长其有效期。"""
-from __future__ import annotations
-
-from itertools import combinations
-
-from . import change_impact
-
-
-def names(select, scopes):
- return {path.name for scope in scopes for path in select(scope)}
-
-
-def affected(record, context, resolve, select):
- if record.get("environment") != context["environment"]:
- return names(select, ("full",))
- paths, kinds = change_impact.delta(record["manifest"], context["manifest"])
- scopes, _ = resolve(paths, kinds=kinds) if paths else ((), "")
- return names(select, scopes)
-
-
-def retained(record, context, resolve, select):
- """只有完整批次的文件结果能组成 full;局部测试不能累加冒充完整批次。"""
- if not record.get("cohort") or not record.get("coverage"):
- return {}
- invalid = affected(record, context, resolve, select)
- required = names(select, ("full",))
- return {name: stamp for name, stamp in record["coverage"].items()
- if name not in invalid and name in required}
-
-
-def completion(coverage, select):
- required = names(select, ("full",))
- return bool(required) and required.issubset(coverage)
-
-
-def pending(coverage, select, scopes):
- """选择覆盖缺少文件、涉及测试文件最少的域组合;未知文件回到 full。"""
- missing = names(select, ("full",)) - coverage.keys()
- if not missing:
- return ()
- candidates = {scope: names(select, (scope,)) for scope in scopes}
- candidates = {scope: files for scope, files in candidates.items() if files & missing}
- if not missing.issubset(set().union(*candidates.values())):
- return ("full",)
- best = None
- for count in range(1, len(candidates) + 1):
- for chosen in combinations(candidates, count):
- files = set().union(*(candidates[scope] for scope in chosen))
- if missing.issubset(files):
- cost = (len(files), len(chosen), chosen)
- if best is None or cost < best:
- best = cost
- return best[2]
-
-
-def after_run(context, scopes, passed, previous, baseline, select, stamp):
- """只接收同一快照上的成功结果;失败会清除本次范围及 full 声明。"""
- source = baseline or previous
- cohort = source.get("cohort")
- coverage = dict(source.get("coverage", {})) if cohort else {}
- tested = names(select, scopes)
- if "full" in scopes:
- cohort = context["state"] if passed else None
- coverage = {}
- if passed and cohort:
- coverage.update(dict.fromkeys(tested, stamp))
- else:
- coverage = {name: when for name, when in coverage.items() if name not in tested}
- return cohort, coverage
diff --git a/scripts/test_resume.py b/scripts/test_resume.py
new file mode 100644
index 000000000..b33afd164
--- /dev/null
+++ b/scripts/test_resume.py
@@ -0,0 +1,307 @@
+"""正式测试的单项覆盖与恢复计划;用例文件是最小复用边界。"""
+from __future__ import annotations
+
+import ast
+from contextlib import contextmanager
+import json
+import os
+from itertools import combinations
+from pathlib import Path
+import re
+import time
+
+from . import change_impact
+
+EXTERNAL = {'frontend/e2e/': 'test_web_e2e.py', 'frontend/test/': 'test_frontend_build.py'}
+CONTAINERS = {
+ 'test_web_e2e.WebE2ESmokeTests.test_every_route_holds_the_layout_and_runtime_invariants': 'frontend/e2e/',
+ 'test_web_e2e.SetupE2ETests.test_the_first_run_page_writes_errors_back_and_finishes': 'frontend/e2e/setup.test.ts',
+ 'test_frontend_build.VitestTests.test_the_island_suite_passes': 'frontend/test/',
+}
+OUTCOMES = frozenset({'pass', 'fail', 'unknown'})
+
+
+def external_files(root: Path, module: str) -> set[str]:
+ prefixes = [prefix for prefix, parent in EXTERNAL.items() if parent == module]
+ return {path.relative_to(root).as_posix() for prefix in prefixes
+ for path in (root / prefix).rglob('*')
+ if path.is_file() and path.name.endswith(('.test.ts', '.test.tsx')
+ if prefix == 'frontend/test/' else '.test.ts')}
+
+
+def owner(unit: str) -> str:
+ if unit.startswith('case:'):
+ return unit.removeprefix('case:').split('.', 1)[0] + '.py'
+ return next((module for prefix, module in EXTERNAL.items() if unit.startswith(prefix)), unit)
+
+
+def container_files(root: Path, case: str) -> set[str]:
+ prefix = CONTAINERS[case]
+ names = {name for name in external_files(root, owner('case:' + case)) if name.startswith(prefix)}
+ if case.endswith('test_every_route_holds_the_layout_and_runtime_invariants'):
+ names.discard('frontend/e2e/setup.test.ts')
+ return names
+
+
+def scope_units(root: Path, scope: str, select, supplements=None) -> set[str]:
+ modules = {path.name for path in select(scope)}
+ units = modules | {name for module in modules for name in external_files(root, module)}
+ units.update('case:' + case for case in CONTAINERS if owner('case:' + case) in modules)
+ for test_id in (supplements or {}).get(scope, ()):
+ module = test_id.split('.', 1)[0] + '.py'
+ if module not in modules:
+ units.add('case:' + test_id)
+ return units
+
+
+def test_importers(root: Path, module: str) -> set[str]:
+ graph = {}
+ for path in (root / 'tests').glob('test_*.py'):
+ try:
+ tree = ast.parse(path.read_text(encoding='utf8'))
+ except (OSError, SyntaxError, UnicodeError):
+ continue
+ imports = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ imports.update(alias.name.removeprefix('tests.').split('.')[0] for alias in node.names)
+ elif isinstance(node, ast.ImportFrom):
+ imports.add((node.module or '').removeprefix('tests.').split('.')[0])
+ if node.module in (None, 'tests'):
+ imports.update(alias.name for alias in node.names)
+ graph[path.name] = {name + '.py' for name in imports if name.startswith('test_')}
+ found = {module}
+ while additions := {name for name, imports in graph.items() if imports & found} - found:
+ found.update(additions)
+ return found
+
+
+def affected(root: Path, record: dict, context: dict, all_units: set[str], resolve, select) -> set[str]:
+ if record.get('environment') != context['environment']:
+ return set(all_units)
+ paths, kinds = change_impact.delta(record['manifest'], context['manifest'])
+ invalid = set()
+ for path in paths:
+ if kinds.get(path) not in {'unsafe', 'prose'} and path.startswith('tests/test_') and path.endswith('.py'):
+ modules = test_importers(root, Path(path).name)
+ invalid.update(unit for unit in all_units if owner(unit) in modules)
+ invalid.update(scope_units(root, 'checks', select))
+ elif kinds.get(path) != 'unsafe' and path.startswith(tuple(EXTERNAL)) and path.endswith(('.test.ts', '.test.tsx')):
+ invalid.update({path, owner(path), 'test_frontend_build.py'})
+ invalid.update('case:' + case for case in CONTAINERS if path in container_files(root, case))
+ invalid.update(scope_units(root, 'checks', select))
+ else:
+ scopes, _ = resolve([path], kinds={path: kinds[path]} if path in kinds else {})
+ invalid.update(unit for scope in scopes for unit in scope_units(root, scope, select))
+ return invalid & all_units
+
+
+def eligible(root: Path, record: dict, context: dict, all_units: set[str], resolve, select) -> dict:
+ invalid = affected(root, record, context, all_units, resolve, select)
+ units = dict(record.get('units', {}))
+ if not units:
+ cohort = record.get('cohort')
+ if cohort:
+ units.update({name: {'outcome': 'pass', 'at': stamp, 'cohort': cohort}
+ for name, stamp in record.get('coverage', {}).items()})
+ for scope in record.get('passed', ()):
+ stamp = record['validated'][scope]
+ cohort = record.get('cohort') or (record.get('state') if scope == 'full' else None)
+ units.update({name: {'outcome': 'pass', 'at': stamp, 'cohort': cohort}
+ for name in recorded_scope(root, scope, select)})
+ for scope in record.get('failed_scopes', ()):
+ units.update({name: {'outcome': 'fail', 'at': record.get('finished', 0)}
+ for name in recorded_scope(root, scope, select)})
+ return {name: row for name, row in units.items() if name in all_units and name not in invalid}
+
+
+def recorded_scope(root, scope, select):
+ try:
+ return scope_units(root, scope, select)
+ except (KeyError, ValueError):
+ return set()
+
+
+def combine(root: Path, records, context: dict, all_units: set[str], resolve, select) -> dict:
+ merged = {}
+ for record in records:
+ for name, row in eligible(root, record, context, all_units, resolve, select).items():
+ previous = merged.get(name)
+ rank = (row['at'], row['outcome'] != 'pass')
+ if previous is None or rank > (previous['at'], previous['outcome'] != 'pass'):
+ merged[name] = row
+ for name in all_units:
+ parent = merged.get(owner(name)) if name.startswith('case:') else None
+ if parent is not None and (name not in merged or parent['at'] >= merged[name]['at']):
+ merged[name] = parent
+ return merged
+
+
+def passed_units(units: dict) -> set[str]:
+ return {name for name, row in units.items() if row.get('outcome') == 'pass'}
+
+
+def validated(units: dict, requirements: dict[str, set[str]], *, allow_full=False) -> dict:
+ successful = passed_units(units)
+ return {scope: min(units[name]['at'] for name in names)
+ for scope, names in requirements.items()
+ if names and names <= successful and (scope != 'full' or allow_full)}
+
+
+def row_unit(test_id: str, assigned: set[str]) -> str | None:
+ for prefix in ('e2e:', 'vitest:'):
+ if test_id.startswith(prefix):
+ return 'frontend/' + test_id.removeprefix(prefix).split(' > ', 1)[0].replace('\\', '/')
+ match = re.search(r'\btest_\w+', test_id)
+ module = match.group(0) + '.py' if match else None
+ return module if module in assigned else None
+
+
+def result_cases(identity: str, cases):
+ if identity in cases:
+ return (identity,)
+ if identity.startswith(('setUpClass ', 'tearDownClass ', 'setUpModule ', 'tearDownModule ')):
+ holder = re.search(r'\((test_\w+(?:\.\w+)?)\)', identity)
+ if holder:
+ return tuple(case for case in cases if case.startswith(holder.group(1) + '.'))
+ return ()
+
+
+def report_units(assigned, report: dict, *, clean_exit: bool, external=None, cases=(), stamp=None) -> dict:
+ """分片完整报告中有明确结果的文件;缺失或异常报告不产生成功证明。"""
+ stamp = time.time() if stamp is None else stamp
+ grouped = {}
+ completed_files = set()
+ assigned = {Path(item).name for item in assigned}
+ for row in report.get('results', ()):
+ identity = str(row.get('id', ''))
+ for case in result_cases(identity, cases):
+ grouped.setdefault('case:' + case, []).append(row.get('outcome'))
+ unit = row_unit(identity, assigned)
+ if unit is not None:
+ grouped.setdefault(unit, []).append(row.get('outcome'))
+ if row.get('file_complete') is True and row.get('outcome') == 'pass':
+ completed_files.add(unit)
+ result = {}
+ for unit, outcomes in grouped.items():
+ failed = any(outcome in {'fail', 'error'} for outcome in outcomes)
+ outcome = 'pass' if set(outcomes) <= {'pass', 'skip'} else 'fail' if failed else 'unknown'
+ if unit.startswith('frontend/') and outcome == 'pass' and unit not in completed_files:
+ outcome = 'unknown'
+ result[unit] = {'outcome': outcome, 'at': stamp}
+ for module in assigned:
+ measured = module.removesuffix('.py') in report.get('files', {}) or module in grouped
+ if (clean_exit and report.get('success') and report.get('count', 0) > 0 and measured
+ and result.get(module, {}).get('outcome') != 'fail'):
+ result[module] = {'outcome': 'pass', 'at': stamp}
+ for unit in (external or {}).get(module, ()):
+ if result.get(unit, {}).get('outcome') != 'fail':
+ result[unit] = {'outcome': 'pass', 'at': stamp}
+ elif module not in grouped:
+ result[module] = {'outcome': 'unknown', 'at': stamp}
+ if report.get('success') and not clean_exit:
+ result = {name: {'outcome': 'unknown', 'at': stamp} for name in result}
+ return result
+
+
+def pending_modules(required: set[str], units: dict) -> set[str]:
+ return {owner(unit) for unit in required - passed_units(units)}
+
+
+def choose_scopes(pending: set[str], requirements: dict[str, set[str]], candidates) -> tuple[str, ...]:
+ if not pending:
+ return ()
+ best = None
+ for size in range(1, len(candidates) + 1):
+ for chosen in combinations(candidates, size):
+ covered = set().union(*(requirements[name] for name in chosen))
+ missing = {name for name in pending if name not in covered
+ and not (name.startswith('case:') and owner(name) in covered)}
+ if not missing:
+ cost = (len(covered), size, chosen)
+ if best is None or cost < best:
+ best = cost
+ return best[2] if best is not None else ('full',)
+
+
+def external_plan(root: Path, modules, units: dict) -> dict:
+ successful = passed_units(units)
+ return {module: sorted(external_files(root, module) - successful)
+ for module in modules if module in EXTERNAL.values()}
+
+
+def validate_cached_results(rows: dict, valid_seconds: float):
+ now = time.time()
+ for row in rows.values():
+ if (not isinstance(row, dict) or row.get('outcome') != 'pass'
+ or type(row.get('at')) not in (int, float) or not 0 <= now - row['at'] < valid_seconds):
+ raise ValueError('恢复计划的成功证明不可用')
+
+
+def validate_child_plan(root: Path, data: dict, *, state: str, valid_seconds: float) -> dict:
+ if not isinstance(data, dict) or data.get('state') != state:
+ raise ValueError('恢复计划不属于当前输入快照')
+ expected, selected, cached = data.get('expected'), data.get('external'), data.get('cached')
+ if not all(isinstance(value, dict) for value in (expected, selected, cached)):
+ raise ValueError('恢复计划格式无效')
+ if expected.keys() != selected.keys() or not set(expected) <= set(EXTERNAL.values()):
+ raise ValueError('恢复计划测试容器无效')
+ universe = set()
+ for module, names in expected.items():
+ actual = external_files(root, module)
+ if not isinstance(names, list) or set(names) != actual or not isinstance(selected[module], list):
+ raise ValueError('恢复计划测试集合与当前文件不符')
+ active = set(selected[module])
+ if not active <= actual or active & cached.keys() or actual - active != actual & cached.keys():
+ raise ValueError('恢复计划缺少被省略文件的成功证明')
+ universe.update(actual)
+ if not set(cached) <= universe:
+ raise ValueError('恢复计划包含容器外的证明')
+ validate_cached_results(cached, valid_seconds)
+ containers = data.get('containers', {})
+ if not isinstance(containers, dict) or not set(containers) <= set(CONTAINERS):
+ raise ValueError('恢复计划的容器证明无效')
+ validate_cached_results(containers, valid_seconds)
+ universe, active_cases = data.get('case_universe', ()), data.get('cases', ())
+ case_cached = data.get('case_cached', {})
+ if (not isinstance(case_cached, dict) or not set(active_cases) <= set(universe)
+ or set(case_cached) != set(universe) - set(active_cases)):
+ raise ValueError('恢复计划缺少被省略用例的成功证明')
+ validate_cached_results(case_cached, valid_seconds)
+ active = set().union(*map(set, selected.values())) if selected else set()
+ allowed = {case for case in containers if container_files(root, case)
+ and container_files(root, case) <= cached.keys() and not container_files(root, case) & active}
+ if set(data.get('skip_cases', ())) != allowed:
+ raise ValueError('恢复计划不能省略未验证的 Python 用例')
+ return data
+
+
+@contextmanager
+def selection_environment(plan):
+ changed = {}
+ for module, variable in (('test_web_e2e.py', 'PEACH_E2E_FILES'),
+ ('test_frontend_build.py', 'PEACH_VITEST_FILES')):
+ if module in plan.get('external', {}):
+ changed[variable] = os.environ.get(variable)
+ os.environ[variable] = json.dumps([name.removeprefix('frontend/') for name in plan['external'][module]])
+ try:
+ yield
+ finally:
+ for key, value in changed.items():
+ if value is None:
+ os.environ.pop(key, None)
+ else:
+ os.environ[key] = value
+
+
+def filter_suite(suite, plan, assigned, suite_type):
+ selected = suite_type()
+ skipped = set(plan.get('skip_cases', ()))
+ for test in suite:
+ if isinstance(test, suite_type):
+ selected.addTests(filter_suite(test, plan, assigned, suite_type))
+ elif test.id() not in skipped and not (
+ test.id() in plan.get('case_universe', ()) and test.id() not in plan.get('cases', ())
+ and test.id().split('.', 1)[0] + '.py' not in assigned):
+ selected.addTest(test)
+ return selected
diff --git a/scripts/test_run_progress.py b/scripts/test_run_progress.py
new file mode 100644
index 000000000..d5eff9019
--- /dev/null
+++ b/scripts/test_run_progress.py
@@ -0,0 +1,131 @@
+"""正式父运行的覆盖检查点,继承原时间并保留已完成单项。"""
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+from . import test_evidence as evidence, test_resume as resume
+
+
+class RunProgress:
+ def __init__(self, root, context, scopes, select, resolve, scope_names, *, supplements=None,
+ force=False, records=(), previous=None, cohort=None):
+ self.root, self.context, self.scopes = root, context, scopes
+ self.select, self.resolve = select, resolve
+ self.scope_names, self.supplements = tuple(scope_names), supplements or {}
+ records = list(records)
+ self.sources = [record.get('state') for record in records if record.get('state')]
+ self.requirements = {scope: resume.scope_units(root, scope, select, supplements)
+ for scope in ('full', *scope_names)}
+ self.all_units = set().union(*self.requirements.values())
+ self.required = set().union(*(self.requirements[scope] for scope in scopes))
+ self.units = resume.combine(root, records, context, self.all_units, resolve, select)
+ self.previous = previous or {}
+ inherited = next((record.get('cohort') or record.get('state') for record in records
+ if record.get('cohort') or 'full' in record.get('passed', ())), None)
+ self.cohort = context['state'] if force and 'full' in scopes else cohort or inherited
+ if self.cohort is None and 'full' in scopes:
+ self.cohort = context['state']
+ if 'full' in scopes:
+ self.units = {name: row for name, row in self.units.items()
+ if row.get('cohort') == self.cohort or row.get('outcome') != 'pass'}
+ self.observed = 0
+ if force:
+ self.units = {name: row for name, row in self.units.items() if name not in self.required}
+ for case in resume.CONTAINERS:
+ if resume.container_files(root, case) - resume.passed_units(self.units):
+ self.units.pop('case:' + case, None)
+ self.pending = self.required - resume.passed_units(self.units)
+ self.modules = resume.pending_modules(self.required, self.units)
+ self.external = resume.external_plan(root, self.modules, self.units)
+ self.cases = {name.removeprefix('case:') for name in self.all_units if name.startswith('case:')}
+
+ def start(self):
+ stamp = time.time()
+ self.units.update({name: {'outcome': 'unknown', 'at': stamp, 'cohort': self.cohort}
+ for name in self.pending})
+ self.persist()
+
+ def checkpoint(self, assigned, report, clean_exit):
+ self.observed += 1
+ assigned = {Path(name).name for name in assigned}
+ if report.get('complete') is not True:
+ return False
+ completed = resume.report_units(assigned, report, clean_exit=clean_exit, external=self.external,
+ cases=self.cases)
+ current = evidence.inputs(self.root)
+ invalid = resume.affected(self.root, self.context, current, self.all_units, self.resolve, self.select)
+ self.units.update({name: {**row, 'cohort': self.cohort}
+ for name, row in completed.items() if name in self.required and name not in invalid})
+ self.persist()
+ return all(self.units.get(name, {}).get('outcome') == 'pass' for name in assigned)
+
+ def accept_success(self, reruns=()):
+ if not self.observed:
+ names = self.pending
+ else:
+ names = set()
+ for selector in reruns:
+ name = selector if selector.startswith('frontend/') else selector.split('.', 1)[0] + '.py'
+ names.update({name, resume.owner(name), 'case:' + selector})
+ names.update('case:' + case for case in resume.CONTAINERS
+ if name in resume.container_files(self.root, case))
+ stamp = time.time()
+ self.units.update({name: {'outcome': 'pass', 'at': stamp, 'cohort': self.cohort}
+ for name in names if name in self.required})
+
+ def complete(self):
+ return self.required <= resume.passed_units(evidence.live_units(self.units) or {})
+
+ def full_coverage(self):
+ if not self.cohort:
+ return {}
+ successful = {name for name, row in self.units.items()
+ if row['outcome'] == 'pass' and row.get('cohort') == self.cohort}
+ return {module: min(self.units[name]['at'] for name in {module, *resume.external_files(self.root, module)})
+ for module in self.requirements['full'] if module.endswith('.py')
+ and {module, *resume.external_files(self.root, module)} <= successful}
+
+ def persist(self, *, final=False, success=False, elapsed=0, slowest=None, count=0, flaky=None):
+ coverage = self.full_coverage()
+ full = bool(self.cohort) and bool(self.requirements['full']) and self.requirements['full'] <= {
+ name for name, row in self.units.items()
+ if row['outcome'] == 'pass' and row.get('cohort') == self.cohort}
+ validated = resume.validated(self.units, self.requirements, allow_full=final and success and full)
+ failed = {scope for scope, names in self.requirements.items()
+ if any(self.units.get(name, {}).get('outcome') == 'fail' for name in names)}
+ prior = {**self.previous, 'validated': validated, 'failed_scopes': sorted(failed)}
+ evidence.write(self.root, self.context['state'], (), success=final and success, previous=prior,
+ context=self.context, cohort=self.cohort, coverage=coverage, units=self.units,
+ elapsed=elapsed, slowest=slowest or [], count=count, flaky=flaky,
+ baseline={'state': self.sources[0], 'validated': {}} if self.sources else None)
+
+ def child_plan(self, scopes=None):
+ scopes = self.scopes if scopes is None else scopes
+ modules = {path.name for scope in scopes for path in self.select(scope)}
+ supplements = {case for scope in scopes for case in self.supplements.get(scope, ())}
+ cases = {case for case in self.cases if case in supplements or resume.owner('case:' + case) in modules}
+ case_cached = {}
+ for case in cases:
+ proof = self.units.get('case:' + case, self.units.get(resume.owner('case:' + case), {}))
+ if proof.get('outcome') == 'pass':
+ case_cached[case] = proof
+ expected = {module: sorted(resume.external_files(self.root, module)) for module in self.external}
+ cached = {name: self.units[name] for names in expected.values() for name in names
+ if name in resume.passed_units(self.units)}
+ containers = {case: proof for case, proof in case_cached.items() if case in resume.CONTAINERS}
+ active = set().union(*map(set, self.external.values())) if self.external else set()
+ skipped = [case for case in containers if resume.container_files(self.root, case)
+ and resume.container_files(self.root, case) <= cached.keys()
+ and not resume.container_files(self.root, case) & active]
+ return {'state': self.context['state'], 'external': self.external, 'expected': expected,
+ 'cached': cached, 'containers': containers, 'skip_cases': skipped, 'case_universe': sorted(cases),
+ 'case_cached': case_cached, 'cases': sorted(cases - case_cached.keys())}
+
+ def retain_current(self):
+ current = evidence.inputs(self.root)
+ source = {**self.context, 'units': self.units, 'cohort': self.cohort}
+ retained = RunProgress(self.root, current, self.scopes, self.select, self.resolve, self.scope_names,
+ supplements=self.supplements, records=[source], cohort=self.cohort)
+ retained.persist()
+ return len(resume.passed_units(retained.units))
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 9016324ee..ffa314303 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -27,7 +27,7 @@ TESTS = ROOT / "tests"
if not __package__:
sys.path.insert(0, str(ROOT))
__package__ = "scripts"
-from . import change_impact, test_evidence, test_history, test_progress
+from . import change_impact, test_evidence, test_history, test_resume, test_run_progress, test_shard_results
COMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py", "test_complexity_ratchet.py",
"test_source_assertion_ratchet.py", "test_python_lint.py")
@@ -372,10 +372,13 @@ AUTO_SCOPE_PREFIXES: tuple[tuple[str, str | tuple[str, ...]], ...] = (
# AGENTS.md 规定必须跑 `full` 的面:迁移、共享测试设施、依赖清单。命中任一个就不再选域。
FULL_ONLY_PREFIXES: tuple[str, ...] = (
+ 'frontend/node_modules/',
"pyproject.toml",
"scripts/test_runner.py", "scripts/test_evidence.py", "scripts/test.ps1", "scripts/test.sh",
- "scripts/ci_plan.py", "scripts/test_environment.py", "scripts/change_impact.py", "scripts/test_progress.py",
+ "scripts/ci_plan.py", "scripts/test_environment.py", "scripts/change_impact.py",
"scripts/test_history.py", "uv.lock",
+ "scripts/test_resume.py", "scripts/test_run_progress.py", "scripts/test_environment_identity.py",
+ "scripts/test_shard_results.py",
"migrations/",
"tests/support/",
"package.json",
@@ -805,13 +808,15 @@ def resolve_jobs(value: str) -> int:
def shard_command(scopes: tuple[str, ...], index: int, count: int, timings: Path,
- plan: Path | None = None) -> list[str]:
+ plan: Path | None = None, resume_plan: Path | None = None) -> list[str]:
command = [sys.executable, str(ROOT / "scripts" / "test_runner.py"),
*(item for scope in scopes for item in ("--scope", scope)),
"--shard-index", str(index), "--shard-count", str(count),
"--timings", str(timings)]
if plan is not None:
command += ["--shard-plan", str(plan)]
+ if resume_plan is not None:
+ command += ['--resume-plan', str(resume_plan)]
return command
@@ -853,7 +858,8 @@ def shard_plan(names: Iterable[str], shard_count: int,
def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
spawn=subprocess.Popen, measured: dict | None = None,
plan: list[list[str]] | None = None,
- outcomes: list | None = None) -> tuple[bool, int, list]:
+ outcomes: list | None = None, checkpoint=None,
+ resume_plan: dict | None = None) -> tuple[bool, int, list]:
"""运行独立分片并汇总证明;并发取调用方的 jobs,取消时清理自己的子进程。
`plan` 是父进程定下的逐片文件名,写成文件交给每个子进程,父子用同一份划分;
@@ -861,6 +867,10 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
"""
folder = Path(tempfile.mkdtemp(prefix="peach-shards-"))
plan_path = None
+ resume_path = None
+ if resume_plan is not None:
+ resume_path = folder / 'resume.json'
+ resume_path.write_text(json.dumps(resume_plan), encoding='utf8')
if plan is not None:
if len(plan) != shard_count:
raise ValueError("分片划分的片数与分片总数不符")
@@ -868,6 +878,7 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
plan_path.write_text(json.dumps(plan), encoding="utf-8")
pending = list(range(shard_count))
running = {}
+ completed_at = {}
passed, count, timings = True, 0, []
try:
while pending or running:
@@ -876,13 +887,13 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
log = open(folder / f"{index}.log", "w+", encoding="utf-8", errors="replace")
try:
process = spawn(shard_command(scopes, index, shard_count, folder / f"{index}.json",
- plan_path),
+ plan_path, resume_path),
stdout=log, stderr=subprocess.STDOUT, cwd=str(ROOT))
except BaseException:
log.close()
raise
running[index] = (process, log)
- finished = [index for index, (process, _) in running.items() if process.poll() is not None]
+ finished = test_shard_results.completed_processes(running, folder, completed_at, now=time.monotonic())
if not finished:
time.sleep(0.2)
continue
@@ -893,9 +904,13 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
sys.stdout.write(log.read())
log.close()
report_path = folder / f"{index}.json"
- report = json.loads(report_path.read_text(encoding="utf-8")) \
- if report_path.is_file() else {"success": False, "count": 0, "timings": []}
+ report = test_shard_results.read_report(report_path)
ok = process.returncode == 0 and bool(report.get("success"))
+ if checkpoint is not None:
+ assigned = plan[index] if plan is not None else sorted({path.name for scope in scopes
+ for path in selected_files(scope)})[index::shard_count]
+ complete = checkpoint(assigned, report, process.returncode == 0)
+ ok = ok and complete
passed = passed and ok
count += int(report.get("count", 0))
timings.extend(tuple(item) for item in report.get("timings", []))
@@ -908,12 +923,7 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
finally:
for process, log in running.values():
if process.poll() is None:
- if os.name == 'nt':
- subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
- else:
- process.terminate()
- process.wait(timeout=15)
+ test_shard_results.stop_process_tree(process)
log.close()
shutil.rmtree(folder, ignore_errors=True)
return passed, count, timings
@@ -999,9 +1009,16 @@ def rerun_selectors(rows: list[dict]) -> list[str] | None:
if item.startswith(("e2e:", "vitest:")):
continue
name = item.split(" ")[0]
- if (name.startswith(E2E_CONTAINER) and e2e) or (name == VITEST_CONTAINER and vitest):
+ if (name in CI_BROWSER_TESTS and any('frontend/' + path in test_resume.container_files(ROOT, name)
+ for path in e2e)) or (name == VITEST_CONTAINER and vitest):
continue
- if not re.fullmatch(r"test_\w+(?:\.\w+)+", name) or name.startswith(E2E_CONTAINER) or name == VITEST_CONTAINER:
+ if not re.fullmatch(r"test_\w+(?:\.\w+)+", name):
+ holder = re.search(r'\((test_\w+)(?:\.\w+)?\)', item)
+ if holder:
+ python.append(holder.group(1))
+ continue
+ return None
+ if name in CI_BROWSER_TESTS or name == VITEST_CONTAINER:
# 类级准备失败、或浏览器容器整个没起来:没有可单独重跑的那一条。
return None
python.append(name)
@@ -1026,9 +1043,15 @@ def rerun_failures(rows: list[dict], spawn=subprocess.run) -> bool:
return True
-def run_local_suite(scopes: tuple[str, ...], jobs: int, label: str | None = None) -> tuple[bool, int, list]:
+def run_local_suite(scopes: tuple[str, ...], jobs: int, label: str | None = None,
+ *, progress=None) -> tuple[bool, int, list]:
"""按调用方选择的并发运行,串行全量通过分片释放测试缓存。"""
chosen = {path for scope in scopes for path in selected_files(scope)}
+ original = set(chosen)
+ progress_args = {}
+ if progress is not None:
+ chosen = {path for path in chosen if path.name in progress.modules}
+ progress_args = {'checkpoint': progress.checkpoint, 'resume_plan': progress.child_plan(scopes)}
FLAKY.clear()
if (jobs > 1 or "full" in scopes) and len(chosen) > 1:
names = sorted(path.name for path in chosen)
@@ -1040,31 +1063,50 @@ def run_local_suite(scopes: tuple[str, ...], jobs: int, label: str | None = None
if rest is not names:
print(f"快速门槛:先跑 {len(gate)} 个秒级检查,有一项不过就不起其余分片", flush=True)
passed, count, timings = run_shards(scopes, jobs=1, shard_count=1, measured=measured,
- plan=[gate], outcomes=rows)
+ plan=[gate], outcomes=rows, **progress_args)
if not passed:
print("快速门槛未通过,其余测试本轮不跑。", flush=True)
save_file_seconds(measured)
test_history.append(ROOT, scope=label or " ".join(scopes), rows=rows,
files=[name.removesuffix(".py") for name in gate])
return False, count, timings
+ if progress is not None:
+ progress_args['resume_plan'] = progress.child_plan(scopes)
shard_count = min(len(rest), 4 * jobs)
print(f"本机分片:{shard_count} 片、同时 {min(jobs, shard_count)} 个子进程,按实测耗时先长后短", flush=True)
plan = shard_plan(rest, shard_count, load_file_seconds())
passed, more, slow = run_shards(scopes, jobs=jobs, shard_count=shard_count, measured=measured, plan=plan,
- outcomes=rows)
+ outcomes=rows, **progress_args)
save_file_seconds(measured)
test_history.append(ROOT, scope=label or " ".join(scopes), rows=rows,
files=[path.stem for path in sorted(chosen)])
if not passed:
passed = rerun_failures(rows)
return passed, count + more, [*timings, *slow]
- suite = build_suite(*scopes)
- with test_history.running():
- result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(suite)
+ return run_serial_suite(scopes, chosen, original, progress, label)
+
+
+def run_serial_suite(scopes, chosen, original, progress, label):
+ """串行执行同一恢复计划,提交与分片相同的文件结果。"""
+ selection = progress.child_plan(scopes) if progress is not None else {}
+ planned = {'assigned_names': [path.name for path in sorted(chosen)]} if chosen != original else {}
+ with test_resume.selection_environment(selection):
+ suite = build_suite(*scopes, **planned)
+ if progress is not None:
+ suite = test_resume.filter_suite(suite, selection, {path.name for path in chosen}, unittest.TestSuite)
+ with test_history.running():
+ result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(suite)
save_file_seconds(result.files)
- test_history.append(ROOT, scope=label or " ".join(scopes), rows=result.results + test_history.take_external(),
+ rows = result.results + test_history.take_external()
+ test_history.append(ROOT, scope=label or " ".join(scopes), rows=rows,
files=[path.stem for path in sorted(chosen)])
- return result.wasSuccessful() and result.testsRun > 0, result.testsRun, result.timings
+ passed = result.wasSuccessful() and result.testsRun > 0
+ if progress is not None:
+ complete = progress.checkpoint([path.name for path in chosen], {
+ 'success': passed, 'count': result.testsRun, 'files': result.files, 'results': rows,
+ 'complete': True}, passed)
+ passed = passed and complete
+ return passed, result.testsRun, result.timings
def run_shard_child(args, requested, scopes, files) -> int:
@@ -1073,16 +1115,33 @@ def run_shard_child(args, requested, scopes, files) -> int:
if args.shard_plan is not None:
planned["assigned_names"] = json.loads(
args.shard_plan.read_text(encoding="utf-8"))[args.shard_index]
- suite = build_suite(*scopes, shard_index=args.shard_index, shard_count=args.shard_count, **planned)
- with test_history.running():
- result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(suite)
+ selection = {}
+ if args.resume_plan is not None:
+ selection = test_resume.validate_child_plan(ROOT,
+ json.loads(args.resume_plan.read_text(encoding='utf8')),
+ state=test_evidence.key(ROOT), valid_seconds=test_evidence.VALID_SECONDS)
+ allowed = {name for scope in scopes for name in SCOPE_TEST_IDS.get(scope, ())}
+ allowed.update(name for names in SCOPE_TEST_IDS.values() for name in names
+ if test_resume.owner('case:' + name) in {path.name for path in files})
+ allowed.update(case for case in test_resume.CONTAINERS
+ if test_resume.owner('case:' + case) in {path.name for path in files})
+ if not set(selection.get('case_universe', ())) <= allowed:
+ raise ValueError('恢复计划包含本次范围外的补充用例')
+ with test_resume.selection_environment(selection):
+ suite = build_suite(*scopes, shard_index=args.shard_index, shard_count=args.shard_count, **planned)
+ if selection:
+ suite = test_resume.filter_suite(suite, selection, set(planned.get('assigned_names', ())), unittest.TestSuite)
+ with test_history.running():
+ result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(suite)
success = result.wasSuccessful() and result.testsRun > 0
rows = result.results + test_history.take_external()
if args.timings is not None:
- args.timings.write_text(json.dumps({"success": success, "count": result.testsRun,
+ temporary = args.timings.with_suffix('.json.tmp')
+ temporary.write_text(json.dumps({"success": success, "count": result.testsRun,
"timings": result.timings, "files": result.files,
- "results": rows}, ensure_ascii=False),
+ "results": rows, 'complete': True}, ensure_ascii=False),
encoding="utf-8")
+ temporary.replace(args.timings)
if args.shard_plan is None:
# CI 的独立分片没有父进程替它汇总,自己写一次历史。
names = [path.name for path in sorted(files)][args.shard_index::args.shard_count]
@@ -1108,6 +1167,7 @@ def main(argv: list[str] | None = None) -> int:
help="分片子进程把成败与逐用例耗时写到这个文件,供父进程汇总")
parser.add_argument("--shard-plan", type=Path, default=None,
help="父进程按耗时划好的逐片文件名;不给时按文件名轮转")
+ parser.add_argument('--resume-plan', type=Path, default=None, help=argparse.SUPPRESS)
parser.add_argument("--jobs", type=resolve_jobs, default=1,
help="本机同时跑几个分片子进程;auto 按核数定。默认串行,正式入口传 auto")
parser.add_argument("--list-scopes", action="store_true")
@@ -1120,6 +1180,8 @@ def main(argv: list[str] | None = None) -> int:
if args.list_scopes:
print("\n".join(("full", "auto", *SCOPES)))
return 0
+ if args.resume_plan is not None and args.shard_plan is None:
+ parser.error('恢复计划仅供正式父运行的分片使用')
if args.focus:
return run_focus(parser, args)
if os.environ.get("PEACH_TEST_FOCUS") or os.environ.get("PEACH_E2E_FILES") or os.environ.get("PEACH_VITEST_FILES"):
@@ -1200,58 +1262,6 @@ def busy(error) -> int:
return 2
-def scoped_baseline(record, scopes, needed):
- """有效域记录只能补齐调用方所需范围,完整基线保留原通过时间。"""
- if "full" in needed:
- return None
- if "full" in record["passed"]:
- return {"full": record["validated"]["full"]}, needed
- if "full" in scopes:
- return None
- retained = {scope: record["validated"][scope] for scope in scopes
- if scope in record["passed"] and scope not in needed}
- if not retained:
- return None
- return retained, tuple(scope for scope in scopes if scope not in retained)
-
-
-def incremental_scopes(context, scopes, files, *, failed=()):
- """选择有效基线,只补测受差异影响或缺少记录的域。"""
- choices = []
- if "full" in failed:
- return None, scopes
- for record, delta, version_only in test_evidence.baselines(ROOT, context, partial=True):
- if record.get("cohort") and record.get("coverage"):
- coverage = test_progress.retained(record, context, scopes_for_changes, selected_files)
- # 已知失败必须实际补测,不能从其他记录恢复同一批文件。
- invalid = test_progress.names(selected_files, failed)
- coverage = {name: stamp for name, stamp in coverage.items() if name not in invalid}
- if coverage:
- needed = test_progress.pending(coverage, selected_files, SCOPES)
- weight = len(test_progress.names(selected_files, needed))
- if weight <= len(files):
- choices.append((weight, {**record, "coverage": coverage, "validated": {}}, needed))
- continue
- _, kinds = change_impact.delta(record["manifest"], context["manifest"])
- needed, _ = scopes_for_changes(delta, kinds=kinds) if delta else ((), "")
- if version_only and "full" not in needed:
- needed = tuple(dict.fromkeys((*needed, "tooling")))
- needed = tuple(dict.fromkeys((*needed, *failed)))
- reusable = scoped_baseline(record, scopes, needed)
- if reusable is None:
- continue
- retained, needed = reusable
- weight = len({p for scope in needed for p in selected_files(scope)})
- if weight <= len(files):
- choices.append((weight, {**record, "validated": retained}, needed))
- if not choices:
- return None, scopes
- _, baseline, scopes = min(choices, key=lambda item: item[0])
- print(f"复用基线 {baseline['state'][:12]}({' '.join(baseline['validated'])});"
- f"差异补测:{' '.join(scopes) or '无'}", flush=True)
- return baseline, scopes
-
-
def verified_run(args, requested, scopes, files) -> int:
"""在调用方持有的全量锁内取得快照、验证并签发记录。"""
context = test_evidence.inputs(ROOT)
@@ -1262,51 +1272,38 @@ def verified_run(args, requested, scopes, files) -> int:
print("复用本机测试记录:代码、依赖环境和范围匹配(24 小时内)。", flush=True)
return 0
previous = test_evidence.read(ROOT, state)
- baseline = None
- if requested == ("auto",) and not args.fresh and (not previous or previous.get("passed") or previous.get("coverage")):
- baseline, scopes = incremental_scopes(context, scopes, files, failed=previous.get("failed_scopes", ()))
- actual = len({path for scope in scopes for path in selected_files(scope)})
+ records = list(test_evidence.candidates(ROOT, context))
+ progress = test_run_progress.RunProgress(ROOT, context, scopes, selected_files, scopes_for_changes, SCOPES,
+ supplements=SCOPE_TEST_IDS, records=records, previous=previous,
+ force=args.fresh or 'full' in requested)
+ if requested == ('auto',) and not args.fresh:
+ choices = ('full', *SCOPES) if 'full' in scopes else scopes
+ scopes = test_resume.choose_scopes(progress.pending, progress.requirements, choices)
+ actual = len(progress.modules)
print(f"实际运行:{' '.join(scopes) or '无需补测'}({actual} 个测试文件)", flush=True)
- folder = test_evidence.evidence_dir(ROOT)
- (folder / f"{state}.json").unlink(missing_ok=True)
+ if records and not args.fresh:
+ print(f'单项覆盖:复用 {len(progress.required) - len(progress.pending)} 项,待验证 {len(progress.pending)} 项。', flush=True)
+ progress.start()
FLAKY.clear()
started = time.monotonic()
- passed, count, timings = run_local_suite(scopes, args.jobs, f"{' '.join(requested)}:{' '.join(scopes)}") \
- if scopes else (True, 0, [])
+ passed, count, timings = run_local_suite(scopes, args.jobs, f"{' '.join(requested)}:{' '.join(scopes)}",
+ progress=progress) if progress.pending else (True, 0, [])
+ if passed:
+ progress.accept_success(FLAKY)
stable = state == test_evidence.key(ROOT)
- success = passed and stable
+ success = passed and stable and progress.complete()
slowest = sorted(timings, reverse=True)[:20]
- cohort, coverage = test_progress.after_run(context, scopes, success, previous, baseline,
- selected_files, time.time())
- if success and test_progress.completion(coverage, selected_files):
- previous = {**previous, "validated": {**previous.get("validated", {}), "full": min(coverage.values())}}
- test_evidence.write(ROOT, state, scopes, success=success, previous=previous,
- context=context, baseline=baseline,
- cohort=cohort, coverage=coverage,
- elapsed=time.monotonic() - started, slowest=slowest, count=count,
- flaky=FLAKY if success else None)
+ progress.persist(final=True, success=success, elapsed=time.monotonic() - started,
+ slowest=slowest, count=count, flaky=FLAKY if success else None)
for seconds, name in slowest[:5]:
print(f"慢测试 {seconds:.3f}s:{name}", flush=True)
if not stable:
- retain_inflight(context, scopes, passed, previous, baseline, count)
+ kept = progress.retain_current()
+ print(f'验证期间输入改变;保留 {kept} 项未受影响的结果,请运行 auto 补齐。', flush=True)
return 4
return 0 if success else 1
-def retain_inflight(context, scopes, passed, previous, baseline, count):
- """运行中改动只保留同环境、完整批次中未受影响的结果。"""
- current = test_evidence.inputs(ROOT)
- cohort, coverage = test_progress.after_run(context, scopes, passed, previous, baseline,
- selected_files, time.time())
- source = {**context, "cohort": cohort, "coverage": coverage}
- kept = test_progress.retained(source, current, scopes_for_changes, selected_files) if passed else {}
- if kept:
- test_evidence.write(ROOT, current["state"], (), success=False, previous={}, context=current,
- cohort=cohort, coverage=kept, elapsed=0, slowest=[], count=count)
- print(f"验证期间代码或依赖环境改变;保留 {len(kept)} 个未受影响的文件结果。"
- "请运行 auto 补齐验证,本次不签发完整通过记录。", flush=True)
-
-
RUN_TEMP = "PEACH_TEST_RUN_TEMP"
RUN_TEMP_PREFIX = "peach-test-run-"
TEMP_VARIABLES = ("TEMP", "TMP", "TMPDIR")
diff --git a/scripts/test_shard_results.py b/scripts/test_shard_results.py
new file mode 100644
index 000000000..74d29a8df
--- /dev/null
+++ b/scripts/test_shard_results.py
@@ -0,0 +1,81 @@
+"""分片完成报告与完成后的进程回收。"""
+from __future__ import annotations
+
+import json
+import math
+from pathlib import Path
+
+
+EXIT_GRACE_SECONDS = 15.0
+
+
+def read_report(path: Path) -> dict:
+ try:
+ report = json.loads(path.read_text(encoding='utf8'))
+ if (not isinstance(report, dict) or report.get('complete') is not True
+ or type(report.get('success')) is not bool
+ or type(report.get('count')) is not int or report['count'] < 0
+ or not isinstance(report.get('timings', []), list)
+ or not isinstance(report.get('files', {}), dict)
+ or not isinstance(report.get('results', []), list)):
+ raise ValueError('分片报告字段无效')
+ if not all(isinstance(row, dict) and isinstance(row.get('id'), str)
+ and row.get('outcome') in {'pass', 'skip', 'fail', 'error'}
+ for row in report.get('results', ())):
+ raise ValueError('分片结果无效')
+ if report['success'] and any(row['outcome'] in {'fail', 'error'} for row in report.get('results', ())):
+ raise ValueError('分片整体结果与用例结果不符')
+ if not all(isinstance(row, list) and len(row) == 2 and duration(row[0])
+ and isinstance(row[1], str) for row in report.get('timings', ())):
+ raise ValueError('分片耗时无效')
+ if not all(isinstance(name, str) and duration(seconds)
+ for name, seconds in report.get('files', {}).items()):
+ raise ValueError('文件耗时无效')
+ return report
+ except (OSError, ValueError, UnicodeError, RecursionError):
+ return {'success': False, 'count': 0, 'timings': [], 'files': {}, 'results': []}
+
+
+def duration(value):
+ return type(value) in (float, int) and math.isfinite(value) and value >= 0
+
+
+def stop_process_tree(process):
+ """只回收调用方创建的进程及其当前子进程。"""
+ import psutil
+ try:
+ children = psutil.Process(process.pid).children(recursive=True)
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ children = []
+ for child in reversed(children):
+ try:
+ child.terminate()
+ except psutil.NoSuchProcess:
+ pass
+ try:
+ process.terminate()
+ except ProcessLookupError:
+ pass
+ _, alive = psutil.wait_procs(children, timeout=2)
+ for child in alive:
+ try:
+ child.kill()
+ except psutil.NoSuchProcess:
+ pass
+ process.wait(timeout=15)
+
+
+def completed_processes(running, folder: Path, completed_at: dict, *, now: float) -> list[int]:
+ finished = []
+ for index, (process, _) in running.items():
+ if process.poll() is not None:
+ finished.append(index)
+ continue
+ report = read_report(folder / f'{index}.json')
+ if report.get('complete') is True:
+ completed_at.setdefault(index, now)
+ if now - completed_at[index] >= EXIT_GRACE_SECONDS:
+ print(f'分片 {index + 1} 已写出完成报告,正在回收其未退出的进程。', flush=True)
+ stop_process_tree(process)
+ finished.append(index)
+ return finished
diff --git a/tests/support/browser.py b/tests/support/browser.py
index 32d80c57f..e7e1de6f4 100644
--- a/tests/support/browser.py
+++ b/tests/support/browser.py
@@ -1,26 +1,4 @@
"""浏览器验收共用的本机 Chrome 定位。"""
-import os
-import shutil
-import sys
-from pathlib import Path
+from scripts.test_environment_identity import chrome_executable
-
-def chrome_executable() -> str | None:
- """读取显式浏览器路径,否则查找各平台安装位置。"""
- explicit = os.environ.get("PEACH_E2E_CHROME", "").strip()
- if explicit:
- return explicit if Path(explicit).is_file() else None
- candidates: list[Path] = []
- if os.name == "nt":
- for variable in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"):
- base = os.environ.get(variable)
- if base:
- candidates.append(Path(base) / "Google" / "Chrome" / "Application" / "chrome.exe")
- elif sys.platform == "darwin":
- candidates.append(Path("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"))
- else:
- for name in ("google-chrome", "google-chrome-stable"):
- found = shutil.which(name)
- if found:
- candidates.append(Path(found))
- return next((str(path) for path in candidates if path.is_file()), None)
+__all__ = ['chrome_executable']
diff --git a/tests/test_frontend_build.py b/tests/test_frontend_build.py
index 9cf2dda1d..465d79b3c 100644
--- a/tests/test_frontend_build.py
+++ b/tests/test_frontend_build.py
@@ -422,8 +422,9 @@ class VitestTests(unittest.TestCase):
capture_output=True, text=True, encoding="utf-8", errors="replace",
cwd=str(FRONTEND), check=False)
if report.is_file():
- test_history.record_external(test_history.vitest_rows(
- json.loads(report.read_text(encoding="utf-8")), FRONTEND))
+ data = json.loads(report.read_text(encoding="utf-8"))
+ test_history.record_external(test_history.vitest_rows(data, FRONTEND)
+ + test_history.vitest_files(data, FRONTEND))
output = f"{completed.stdout}\n{completed.stderr}"
# vitest 的着色随宿主终端能力漂移,计数断言只认去码后的纯文本;
# 退出码与用例数两道判据不受着色影响。
diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.py
index cfc25f50a..a0940fb5d 100644
--- a/tests/test_metadata_library.py
+++ b/tests/test_metadata_library.py
@@ -319,13 +319,16 @@ class LibraryNfoTests(unittest.TestCase):
provider.cover.return_value = False
control = control_for(config)
paused, requested = threading.Event(), threading.Event()
+ pause_lock = threading.Lock()
results, errors = [], []
def report(state):
if state['status'] == 'paused':
paused.set()
- elif state.get('auto_applied', 0) and not requested.is_set():
- requested.set()
- control.request('pause', state['job_id'])
+ elif state.get('auto_applied', 0):
+ with pause_lock:
+ if not requested.is_set():
+ requested.set()
+ control.request('pause', state['job_id'])
def run():
try:
results.append(process_library(config, db, self.root / 'generated', self.root / 'covers',
@@ -345,7 +348,9 @@ class LibraryNfoTests(unittest.TestCase):
self.assertTrue(read_rows(self.root / 'generated/library-metadata-field-candidates.csv'))
self.assertEqual(snapshot(config)['status'], 'paused')
finally:
- control.request('resume', 'one')
+ with pause_lock:
+ requested.set()
+ control.request('resume', 'one')
thread.join(5)
self.assertFalse(thread.is_alive())
self.assertEqual(errors, [])
diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.py
index ca6dcf057..b3c486f30 100644
--- a/tests/test_test_evidence.py
+++ b/tests/test_test_evidence.py
@@ -18,19 +18,25 @@ from unittest import mock
from scripts import agent_worktree as coordinator
from scripts import test_evidence as evidence
from scripts import test_runner as runner
-from scripts import test_progress
+from scripts import test_resume
+from scripts import test_run_progress
+from scripts import test_shard_results
from support.gitrepo import seed_repository
class ParallelShardTests(unittest.TestCase):
+ def test_imported_verification_code_belongs_to_this_workspace(self):
+ self.assertEqual(Path(runner.__file__).resolve().parents[1], Path(__file__).resolve().parents[1])
+ self.assertEqual(Path(evidence.__file__).resolve().parents[1], Path(__file__).resolve().parents[1])
+
def test_requested_parallelism_has_no_machine_slot_ceiling(self):
live, peak = set(), [0]
class Shard:
def __init__(self, command):
report = Path(command[command.index('--timings') + 1])
- report.write_text(json.dumps({'success': True, 'count': 1, 'timings': []}), encoding='utf-8')
+ report.write_text(json.dumps({'complete': True, 'success': True, 'count': 1, 'timings': []}), encoding='utf-8')
self.polls, self.returncode = 0, None
live.add(self)
peak[0] = max(peak[0], len(live))
@@ -49,6 +55,450 @@ class ParallelShardTests(unittest.TestCase):
self.assertEqual(peak[0], 6)
+class EnvironmentIdentityTests(unittest.TestCase):
+ def test_ci_commit_metadata_and_credential_rotation_preserve_environment(self):
+ from scripts.test_environment_identity import environment_flags
+ base = {'GITHUB_ACTIONS': 'true', 'GITHUB_JOB': 'python', 'GITHUB_TOKEN': 'fixture-one'}
+ rotated = {**base, 'GITHUB_TOKEN': 'fixture-two', 'CI_JOB_STARTED_AT': 'another',
+ 'CI_COMMIT_MESSAGE': 'another message'}
+ self.assertEqual(environment_flags(base), environment_flags(rotated))
+ self.assertNotEqual(environment_flags(base), environment_flags({'GITHUB_ACTIONS': 'true', 'GITHUB_JOB': 'python'}))
+ self.assertEqual(environment_flags({'CI_JOB_TOKEN': ''}), environment_flags({}))
+
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.python = self.root / 'python.exe'
+ self.python.write_bytes(b'runtime-fixture')
+ self.enterContext(mock.patch.dict(os.environ, {}, clear=True))
+ self.enterContext(mock.patch.object(evidence, 'interpreter', return_value=self.python))
+ self.enterContext(mock.patch.object(evidence, 'python_identity', return_value={
+ 'version': 'fixture-python', 'sites': []}))
+ self.enterContext(mock.patch.object(evidence, 'tool_identities', return_value={}))
+ self.packages = self.enterContext(mock.patch.object(evidence.importlib.metadata, 'distributions', return_value=[]))
+
+ def test_equivalent_interpreters_in_separate_worktrees_share_identity(self):
+ other = self.root / 'other/python.exe'
+ other.parent.mkdir()
+ other.write_bytes(self.python.read_bytes())
+ first = evidence.environment(self.root)
+ with mock.patch.object(evidence, 'interpreter', return_value=other):
+ self.assertEqual(evidence.environment(self.root), first)
+ other.write_bytes(b'another-runtime')
+ with mock.patch.object(evidence, 'interpreter', return_value=other):
+ self.assertNotEqual(evidence.environment(self.root), first)
+
+ def test_install_lock_identity_uses_json_content(self):
+ lock = self.root / 'frontend/node_modules/.package-lock.json'
+ lock.parent.mkdir(parents=True)
+ lock.write_text('{"name":"app","packages":{"one":{"version":"1"}}}', encoding='utf8')
+ first = evidence.environment(self.root)
+ lock.write_text('{\n "packages": {"one": {"version": "1"}}, "name": "app"\n}', encoding='utf8')
+ self.assertEqual(evidence.environment(self.root), first)
+ lock.write_text('{"name":"app","packages":{"one":{"version":"2"}}}', encoding='utf8')
+ self.assertNotEqual(evidence.environment(self.root), first)
+
+ def test_ci_run_metadata_preserves_identity_and_job_selection_changes_it(self):
+ os.environ.update(GITHUB_RUN_ID='one', GITHUB_RUN_NUMBER='1', GITHUB_JOB='python')
+ first = evidence.environment(self.root)
+ os.environ.update(GITHUB_RUN_ID='two', GITHUB_RUN_NUMBER='2')
+ self.assertEqual(evidence.environment(self.root), first)
+ os.environ['GITHUB_JOB'] = 'web-e2e'
+ self.assertNotEqual(evidence.environment(self.root), first)
+
+ def test_distribution_names_have_canonical_identity(self):
+ from types import SimpleNamespace
+ self.packages.return_value = [SimpleNamespace(metadata={'Name': 'Some_Pkg'}, version='1')]
+ first = evidence.environment(self.root)
+ self.packages.return_value = [SimpleNamespace(metadata={'Name': 'some-pkg'}, version='1')]
+ self.assertEqual(evidence.environment(self.root), first)
+ self.packages.return_value = [SimpleNamespace(metadata={'Name': 'some-pkg'}, version='2')]
+ self.assertNotEqual(evidence.environment(self.root), first)
+
+ def test_browser_paths_share_identity_and_binary_changes_invalidate_it(self):
+ first, second = self.root / 'chrome-one', self.root / 'chrome-two'
+ first.write_bytes(b'browser-fixture')
+ second.write_bytes(first.read_bytes())
+ os.environ['PEACH_E2E_CHROME'] = str(first)
+ identity = evidence.environment(self.root)
+ os.environ['PEACH_E2E_CHROME'] = str(second)
+ self.assertEqual(evidence.environment(self.root), identity)
+ second.write_bytes(b'another-browser')
+ self.assertNotEqual(evidence.environment(self.root), identity)
+
+
+class RecordSelectionTests(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.now = time.time()
+ self.enterContext(mock.patch.object(evidence, 'evidence_dir', return_value=self.root))
+
+ def record(self, index, *, success=True, **changes):
+ manifest = {'files': {'marker': [420, f'{index:064x}', '100644']}, 'signatures': {}}
+ context = {'manifest': manifest, 'environment': 'fixture'}
+ state = evidence.digest([evidence.digest(manifest), context['environment']])
+ value = {**context, 'state': state, 'validated': {'catalog': self.now} if success else {},
+ 'coverage': {}, **changes}
+ path = self.root / f'{state}.json'
+ path.write_text(json.dumps(value), encoding='utf8')
+ os.utime(path, (self.now - 100 + index, self.now - 100 + index))
+ return context, state, path
+
+ def test_live_baseline_survives_newer_failed_records(self):
+ context, _, _ = self.record(0)
+ for index in range(1, 34):
+ self.record(index, success=False)
+ self.assertEqual(len(list(evidence.baselines(self.root, context, partial=True))), 1)
+
+ def test_malformed_record_does_not_hide_other_candidates(self):
+ context, _, _ = self.record(0)
+ self.record(1, coverage=[])
+ self.assertEqual(len(list(evidence.baselines(self.root, context, partial=True))), 1)
+
+ def test_record_content_is_bound_to_its_identity(self):
+ _, state, path = self.record(0)
+ record = json.loads(path.read_text(encoding='utf8'))
+ record['environment'] = 'another'
+ path.write_text(json.dumps(record), encoding='utf8')
+ self.assertEqual(evidence.read(self.root, state), {})
+
+ def test_malformed_optional_fields_do_not_stop_candidate_selection(self):
+ context, _, _ = self.record(0)
+ for index, fields in enumerate(({'failed_scopes': {}}, {'finished': []}, {'cohort': {}},
+ {'units': {'test_a.py': {'outcome': 'pass', 'at': float('nan')}}}), 1):
+ self.record(index, **fields)
+ self.assertEqual(len(list(evidence.candidates(self.root, context))), 1)
+
+
+class ReceiptFixture:
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.now = time.time()
+ self.mapping = {'catalog': (Path('test_catalog.py'),), 'web': (Path('test_web.py'),),
+ 'checks': (), 'full': (Path('test_catalog.py'), Path('test_web.py'))}
+ self.context = {'environment': 'same', 'manifest': {'files': {}, 'signatures': {}}}
+
+ def resolve(self, paths, **kwargs):
+ return (('catalog',), 'fixture')
+
+ def unit(self, outcome='pass', offset=0):
+ return {'outcome': outcome, 'at': self.now + offset}
+
+ def record(self, units, **changes):
+ return {**self.context, 'units': units, **changes}
+
+
+class ReceiptTests(ReceiptFixture, unittest.TestCase):
+ def test_a_failed_file_preserves_successful_sibling_files(self):
+ report = {'success': False, 'count': 2, 'results': [
+ {'id': 'test_catalog.Suite.test_value', 'outcome': 'pass'},
+ {'id': 'test_web.Suite.test_value', 'outcome': 'fail'}]}
+ units = test_resume.report_units(self.mapping['full'], report, clean_exit=True, stamp=self.now)
+ self.assertEqual(units['test_catalog.py']['outcome'], 'pass')
+ self.assertEqual(units['test_web.py']['outcome'], 'fail')
+
+ def test_latest_failure_blocks_an_older_success_from_another_record(self):
+ records = [self.record({'test_web.py': self.unit('fail')}),
+ self.record({'test_web.py': self.unit(offset=-10)})]
+ kept = test_resume.combine(self.root, records, self.context, {'test_web.py'}, self.resolve, self.mapping.__getitem__)
+ self.assertEqual(kept['test_web.py']['outcome'], 'fail')
+
+ def test_compatible_records_cover_scopes_without_claiming_full(self):
+ records = [self.record({'test_web.py': self.unit()}), self.record({'test_catalog.py': self.unit(offset=-10)})]
+ kept = test_resume.combine(self.root, records, self.context,
+ {'test_web.py', 'test_catalog.py'}, self.resolve, self.mapping.__getitem__)
+ requirements = {scope: {path.name for path in files} for scope, files in self.mapping.items()}
+ validated = test_resume.validated(kept, requirements)
+ self.assertEqual(set(validated), {'catalog', 'web'})
+ self.assertEqual(validated['catalog'], self.now - 10)
+
+ def test_a_test_file_change_preserves_an_independent_test_file(self):
+ old = {'files': {'tests/test_catalog.py': [420, 'old', '100644']}, 'signatures': {}}
+ current = {'files': {'tests/test_catalog.py': [420, 'new', '100644']}, 'signatures': {}}
+ record = self.record({'test_web.py': self.unit(), 'test_catalog.py': self.unit()}, manifest=old)
+ kept = test_resume.combine(self.root, [record], {**self.context, 'manifest': current},
+ {'test_web.py', 'test_catalog.py'}, self.resolve, self.mapping.__getitem__)
+ self.assertEqual(set(kept), {'test_web.py'})
+
+ def test_actual_source_changes_invalidate_their_domain(self):
+ old = {'files': {'src/peach/catalog.py': [420, 'old', '100644']}, 'signatures': {}}
+ current = {'files': {'src/peach/catalog.py': [420, 'new', '100644']}, 'signatures': {}}
+ record = self.record({'test_web.py': self.unit(), 'test_catalog.py': self.unit()}, manifest=old)
+ kept = test_resume.combine(self.root, [record], {**self.context, 'manifest': current},
+ {'test_web.py', 'test_catalog.py'}, self.resolve, self.mapping.__getitem__)
+ self.assertEqual(set(kept), {'test_web.py'})
+
+ def test_missing_or_unclean_completion_cannot_produce_success(self):
+ for report, clean in (({'success': True, 'count': 0}, True),
+ ({'success': True, 'count': 1}, False)):
+ with self.subTest(report=report, clean=clean):
+ units = test_resume.report_units(['test_web.py'], report, clean_exit=clean, stamp=self.now)
+ self.assertEqual(units['test_web.py']['outcome'], 'unknown')
+
+ def test_browser_failure_retains_other_browser_file_results(self):
+ folder = self.root / 'frontend/e2e'
+ folder.mkdir(parents=True)
+ for name in ('one.test.ts', 'two.test.ts'):
+ (folder / name).write_text('fixture', encoding='utf8')
+ report = {'success': False, 'count': 1, 'results': [
+ {'id': 'test_web_e2e.Suite.test_browser', 'outcome': 'fail'},
+ {'id': 'e2e:e2e/one.test.ts > value', 'outcome': 'pass'},
+ {'id': 'e2e:e2e/one.test.ts > 文件结果', 'outcome': 'pass', 'file_complete': True},
+ {'id': 'e2e:e2e/two.test.ts > value', 'outcome': 'fail'}]}
+ units = test_resume.report_units(['test_web_e2e.py'], report, clean_exit=True, stamp=self.now)
+ plan = test_resume.external_plan(self.root, ['test_web_e2e.py'], units)
+ self.assertEqual(plan, {'test_web_e2e.py': ['frontend/e2e/two.test.ts']})
+
+ def test_partial_external_output_does_not_prove_file_completion(self):
+ report = {'success': False, 'count': 1, 'results': [
+ {'id': 'e2e:e2e/one.test.ts > first', 'outcome': 'pass'}]}
+ units = test_resume.report_units(['test_web_e2e.py'], report, clean_exit=True, stamp=self.now)
+ self.assertEqual(units['frontend/e2e/one.test.ts']['outcome'], 'unknown')
+
+ def test_imported_test_helpers_invalidate_transitive_consumers(self):
+ folder = self.root / 'tests'
+ folder.mkdir()
+ (folder / 'test_middle.py').write_text('from tests import test_catalog\n', encoding='utf8')
+ (folder / 'test_outer.py').write_text('from . import test_middle\n', encoding='utf8')
+ self.assertEqual(test_resume.test_importers(self.root, 'test_catalog.py'),
+ {'test_catalog.py', 'test_middle.py', 'test_outer.py'})
+
+ def test_comment_only_test_changes_preserve_behavior_coverage(self):
+ behavior = evidence.digest('same')
+ old = {'files': {'tests/test_catalog.py': [420, 'old', '100644']},
+ 'signatures': {'tests/test_catalog.py': {'behavior': behavior}}}
+ current = {'files': {'tests/test_catalog.py': [420, 'new', '100644']},
+ 'signatures': old['signatures']}
+ resolve = lambda paths, **kwargs: (('checks',), 'fixture')
+ record = self.record({'test_catalog.py': self.unit()}, manifest=old)
+ kept = test_resume.combine(self.root, [record], {**self.context, 'manifest': current},
+ {'test_catalog.py'}, resolve, self.mapping.__getitem__)
+ self.assertEqual(set(kept), {'test_catalog.py'})
+
+ def test_container_class_skip_is_an_environment_bound_result(self):
+ case = next(case for case in test_resume.CONTAINERS if '.WebE2E' in case)
+ report = {'success': True, 'count': 1, 'results': [
+ {'id': 'setUpClass (test_web_e2e.WebE2ESmokeTests)', 'outcome': 'skip'},
+ {'id': 'test_web_e2e.Policy.test_value', 'outcome': 'pass'}]}
+ units = test_resume.report_units(['test_web_e2e.py'], report, clean_exit=True, cases={case})
+ self.assertEqual(units['case:' + case]['outcome'], 'pass')
+
+ def test_class_and_module_cleanup_failures_invalidate_container_proof(self):
+ case = next(case for case in test_resume.CONTAINERS if '.WebE2E' in case)
+ for holder in ('tearDownClass (test_web_e2e.WebE2ESmokeTests)', 'tearDownModule (test_web_e2e)'):
+ report = {'success': False, 'count': 1, 'results': [
+ {'id': case, 'outcome': 'pass'}, {'id': holder, 'outcome': 'error'}]}
+ with self.subTest(holder=holder):
+ units = test_resume.report_units(['test_web_e2e.py'], report, clean_exit=True, cases={case})
+ self.assertEqual(units['case:' + case]['outcome'], 'fail')
+ self.assertEqual(units['test_web_e2e.py']['outcome'], 'fail')
+
+
+class CheckpointTests(ReceiptFixture, unittest.TestCase):
+ def setUp(self):
+ super().setUp()
+ manifest = self.context['manifest']
+ self.context['state'] = evidence.digest([evidence.digest(manifest), self.context['environment']])
+ self.enterContext(mock.patch.object(evidence, 'evidence_dir', return_value=self.root / 'records'))
+ self.enterContext(mock.patch.object(evidence, 'inputs', return_value=self.context))
+
+ def progress(self, scopes=('full',), **kwargs):
+ return test_run_progress.RunProgress(self.root, self.context, scopes, self.mapping.__getitem__,
+ self.resolve, ('catalog', 'web', 'checks'), **kwargs)
+
+ def report(self, *names, failure=None):
+ return {'complete': True, 'success': failure is None, 'count': len(names), 'results': [
+ {'id': name.removesuffix('.py') + '.Suite.test_value',
+ 'outcome': 'fail' if name == failure else 'pass'} for name in names]}
+
+ def test_interruption_keeps_completed_shards_and_their_original_age(self):
+ progress = self.progress()
+ progress.start()
+ progress.checkpoint(['test_catalog.py'], self.report('test_catalog.py'), True)
+ saved = evidence.read(self.root, self.context['state'])
+ resumed = self.progress(records=[saved])
+ self.assertEqual(resumed.pending, {'test_web.py'})
+ stamp = saved['units']['test_catalog.py']['at']
+ resumed.start()
+ resumed.checkpoint(['test_web.py'], self.report('test_web.py'), True)
+ resumed.persist(final=True, success=resumed.complete())
+ result = evidence.read(self.root, self.context['state'])
+ self.assertTrue(evidence.covers(result, ('full',)))
+ self.assertEqual(result['validated']['full'], stamp)
+
+ def test_failed_batch_resumes_only_failed_files_without_full_until_complete(self):
+ progress = self.progress()
+ progress.start()
+ progress.checkpoint(self.mapping['full'], self.report('test_catalog.py', 'test_web.py', failure='test_web.py'), True)
+ progress.persist(final=True, success=False)
+ saved = evidence.read(self.root, self.context['state'])
+ self.assertFalse(evidence.covers(saved, ('full',)))
+ self.assertTrue(evidence.covers(saved, ('catalog',)))
+ self.assertEqual(self.progress(records=[saved]).pending, {'test_web.py'})
+
+ def test_fresh_discards_positive_coverage_in_the_requested_scope(self):
+ record = self.record({'test_catalog.py': self.unit(), 'test_web.py': self.unit()})
+ progress = self.progress(('catalog',), records=[record], force=True)
+ self.assertEqual(progress.pending, {'test_catalog.py'})
+ self.assertEqual(progress.units['test_web.py']['outcome'], 'pass')
+
+ def test_partial_runs_do_not_supply_full_batch_provenance(self):
+ records = [self.record({'test_catalog.py': self.unit()}), self.record({'test_web.py': self.unit()})]
+ progress = self.progress(records=records)
+ self.assertEqual(progress.pending, {'test_catalog.py', 'test_web.py'})
+ progress.persist(final=True, success=True)
+ self.assertFalse(evidence.covers(evidence.read(self.root, self.context['state']), ('full',)))
+
+ def test_nonfinal_report_cannot_supply_a_checkpoint(self):
+ progress = self.progress()
+ report = self.report('test_catalog.py')
+ report.pop('complete')
+ self.assertFalse(progress.checkpoint(['test_catalog.py'], report, True))
+ self.assertFalse(progress.units)
+
+ def test_coverage_that_expires_during_execution_requires_revalidation(self):
+ record = self.record({'test_catalog.py': self.unit()})
+ progress = self.progress(('catalog',), records=[record])
+ self.assertTrue(progress.complete())
+ with mock.patch.object(evidence.time, 'time', return_value=self.now + 86401):
+ self.assertFalse(progress.complete())
+
+ def test_cached_external_files_require_current_complete_proof(self):
+ folder = self.root / 'frontend/e2e'
+ folder.mkdir(parents=True)
+ for name in ('one.test.ts', 'two.test.ts'):
+ (folder / name).write_text('export {};', encoding='utf8')
+ self.mapping['web'] = (Path('test_web_e2e.py'),)
+ proof = {'frontend/e2e/one.test.ts': self.unit()}
+ progress = self.progress(('web',), records=[self.record(proof)])
+ plan = progress.child_plan()
+ self.assertEqual(plan['external']['test_web_e2e.py'], ['frontend/e2e/two.test.ts'])
+ test_resume.validate_child_plan(self.root, plan, state=self.context['state'], valid_seconds=86400)
+ for bad in ({**plan, 'cached': {}}, {**plan, 'state': 'another'},
+ {**plan, 'cached': {name: {**row, 'at': self.now - 86401} for name, row in proof.items()}}):
+ with self.subTest(plan=bad), self.assertRaises(ValueError):
+ test_resume.validate_child_plan(self.root, bad, state=self.context['state'], valid_seconds=86400)
+
+ def test_unrelated_python_failure_survives_browser_aggregation(self):
+ smoke = next(case for case in runner.CI_BROWSER_TESTS if '.WebE2E' in case)
+ ids = ['e2e:e2e/smoke.test.ts > failure', smoke,
+ 'test_web_e2e.SourcePolicyTests.test_contract']
+ selectors = runner.rerun_selectors([{'id': name, 'outcome': 'fail'} for name in ids])
+ self.assertEqual(selectors, ['test_web_e2e.SourcePolicyTests.test_contract', 'frontend/e2e/smoke.test.ts'])
+
+ def test_setup_failure_selects_the_whole_module(self):
+ self.assertEqual(runner.rerun_selectors([{'id': 'setUpClass (test_catalog.Suite)', 'outcome': 'error'}]),
+ ['test_catalog'])
+
+ def test_external_success_cannot_hide_python_container_postcondition_failure(self):
+ folder = self.root / 'frontend/e2e'
+ folder.mkdir(parents=True)
+ for name in ('one.test.ts', 'setup.test.ts'):
+ (folder / name).write_text('export {};', encoding='utf8')
+ self.mapping['web'] = (Path('test_web_e2e.py'),)
+ smoke = next(case for case in test_resume.CONTAINERS if '.WebE2E' in case)
+ setup = next(case for case in test_resume.CONTAINERS if '.SetupE2E' in case)
+ proof = {name: self.unit() for name in test_resume.external_files(self.root, 'test_web_e2e.py')}
+ proof.update({'case:' + smoke: self.unit(), 'case:' + setup: self.unit('fail')})
+ plan = self.progress(('web',), records=[self.record(proof)]).child_plan()
+ self.assertEqual(plan['skip_cases'], [smoke])
+ self.assertIn(setup, plan['cases'])
+ test_resume.validate_child_plan(self.root, plan, state=self.context['state'], valid_seconds=86400)
+ self.assertIsNone(runner.rerun_selectors([
+ {'id': setup, 'outcome': 'fail'}, {'id': 'e2e:e2e/smoke.test.ts > error', 'outcome': 'fail'}]))
+
+ def test_input_change_after_a_failure_retains_unaffected_success(self):
+ progress = self.progress()
+ progress.start()
+ progress.checkpoint(self.mapping['full'], self.report('test_catalog.py', 'test_web.py', failure='test_catalog.py'), True)
+ manifest = {'files': {'src/peach/catalog.py': [420, evidence.digest('changed'), '100644']}, 'signatures': {}}
+ current = {**self.context, 'manifest': manifest,
+ 'state': evidence.digest([evidence.digest(manifest), self.context['environment']])}
+ with mock.patch.object(evidence, 'inputs', return_value=current):
+ self.assertEqual(progress.retain_current(), 1)
+ record = evidence.read(self.root, current['state'])
+ self.assertEqual(record['units']['test_web.py']['outcome'], 'pass')
+ self.assertNotIn('test_catalog.py', record['units'])
+
+ def test_narrow_resume_plan_excludes_unselected_containers(self):
+ folder = self.root / 'frontend/e2e'
+ folder.mkdir(parents=True)
+ (folder / 'one.test.ts').write_text('export {};', encoding='utf8')
+ self.mapping['full'] = (Path('test_catalog.py'), Path('test_web_e2e.py'))
+ self.mapping['web'] = (Path('test_web_e2e.py'),)
+ all_units = test_resume.scope_units(self.root, 'full', self.mapping.__getitem__)
+ proof = {name: {**self.unit(), 'cohort': self.context['state']} for name in all_units}
+ proof['test_catalog.py']['outcome'] = 'fail'
+ progress = self.progress(records=[self.record(proof, cohort=self.context['state'])])
+ plan = progress.child_plan(('catalog',))
+ self.assertEqual(plan['case_universe'], [])
+ test_resume.validate_child_plan(self.root, plan, state=self.context['state'], valid_seconds=86400)
+
+ def test_cached_supplement_in_a_resumed_full_run_requires_its_proof(self):
+ case = 'test_extra.Suite.test_value'
+ self.mapping['full'] += (Path('test_extra.py'),)
+ self.mapping['checks'] = (Path('test_catalog.py'),)
+ proof = {name: {**self.unit(), 'cohort': self.context['state']}
+ for name in ('test_catalog.py', 'test_web.py', 'test_extra.py')}
+ proof['test_catalog.py']['outcome'] = 'fail'
+ progress = self.progress(records=[self.record(proof, cohort=self.context['state'])],
+ supplements={'checks': (case,)})
+ plan = progress.child_plan(('checks',))
+ self.assertEqual(plan['case_universe'], [case])
+ self.assertEqual(plan['cases'], [])
+ test_resume.validate_child_plan(self.root, plan, state=self.context['state'], valid_seconds=86400)
+ with self.assertRaises(ValueError):
+ test_resume.validate_child_plan(self.root, {**plan, 'case_cached': {}},
+ state=self.context['state'], valid_seconds=86400)
+ test_type = type('Suite', (unittest.TestCase,), {'__module__': 'test_extra', 'test_value': lambda self: None})
+ selected = test_resume.filter_suite(unittest.TestSuite([test_type('test_value')]), plan,
+ {'test_catalog.py'}, unittest.TestSuite)
+ self.assertEqual(selected.countTestCases(), 0)
+
+
+class ShardReportTests(unittest.TestCase):
+ def test_malformed_reports_are_failures(self):
+ with tempfile.TemporaryDirectory() as folder:
+ path = Path(folder) / 'report.json'
+ base = {'complete': True, 'success': True, 'count': 1, 'timings': [], 'files': {}, 'results': []}
+ invalid = [{'complete': False}, {'count': -1}, {'timings': [[float('nan'), 'id']]},
+ {'timings': ['invalid']}, {'files': {'test_a': 'invalid'}}, {'results': [None]},
+ {'results': [{'id': 'test_a.Suite.test_value', 'outcome': 'fail'}]}]
+ for fields in invalid:
+ with self.subTest(fields=fields):
+ path.write_text(json.dumps({**base, **fields}), encoding='utf8')
+ self.assertFalse(test_shard_results.read_report(path)['success'])
+
+ def test_a_completed_child_with_a_live_thread_is_reaped(self):
+ with tempfile.TemporaryDirectory() as folder:
+ path = Path(folder) / '0.json'
+ script = Path(folder) / 'child.py'
+ script.write_text("import json,pathlib,sys,threading\n"
+ "threading.Thread(target=threading.Event().wait).start()\n"
+ "pathlib.Path(sys.argv[1]).write_text(json.dumps({"
+ "'complete': True,'success': True,'count': 1,'timings': []}))\n", encoding='utf8')
+ process = subprocess.Popen([sys.executable, '-X', 'utf8', str(script), str(path)])
+ try:
+ deadline = time.monotonic() + 10
+ while not path.exists() and time.monotonic() < deadline:
+ time.sleep(.02)
+ self.assertTrue(path.exists())
+ self.assertIsNone(process.poll())
+ with redirect_stdout(io.StringIO()):
+ finished = test_shard_results.completed_processes({0: (process, None)}, Path(folder),
+ {0: 0}, now=test_shard_results.EXIT_GRACE_SECONDS + 1)
+ self.assertEqual(finished, [0])
+ self.assertIsNotNone(process.poll())
+ finally:
+ if process.poll() is None:
+ test_shard_results.stop_process_tree(process)
+
+
class VerificationTests(unittest.TestCase):
def setUp(self):
# 这组用例模拟本机验收,运行它的 CI job 身份不属于临时仓库。
@@ -81,6 +531,19 @@ class VerificationTests(unittest.TestCase):
evidence.write(worker, state, scopes, success=success, elapsed=1, slowest=[], count=1)
return state
+ def scope_suite(self, *scopes, fail=False, **planned):
+ suite = unittest.TestSuite()
+ selected = {path for scope in scopes for path in runner.selected_files(scope)}
+ assigned = planned.get('assigned_names')
+ def exercise(case):
+ if fail:
+ case.fail('fixture')
+ for path in sorted(selected):
+ if assigned is None or path.name in assigned:
+ case = type('Suite', (unittest.TestCase,), {'__module__': path.stem, 'test_value': exercise})
+ suite.addTest(case('test_value'))
+ return suite
+
def test_gate_requires_matching_successful_coverage(self):
worker, branch = self.worker()
before = self.git("rev-parse", "HEAD")
@@ -478,7 +941,7 @@ class VerificationTests(unittest.TestCase):
mock.patch.object(evidence, "write", side_effect=publish_locked) as written, \
mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])):
self.assertEqual(runner.main(["--scope", "full"]), 0)
- written.assert_called_once()
+ self.assertGreaterEqual(written.call_count, 2)
self.assertEqual(self.git("rev-parse", "HEAD"), before)
def test_integration_excludes_full_verification(self):
@@ -528,16 +991,14 @@ class VerificationTests(unittest.TestCase):
self.assertEqual(runner.scopes_for_changes([path])[0], ("full",))
def test_runner_reuses_success_and_fresh_failure_invalidates_it(self):
- def suite(*_):
- return unittest.TestSuite([unittest.FunctionTestCase(lambda: None)])
with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()), \
mock.patch.object(runner, "ROOT", self.repo), \
- mock.patch.object(runner, "build_suite", side_effect=suite) as build:
+ mock.patch.object(runner, "build_suite", side_effect=self.scope_suite) as build:
self.assertEqual(runner.main(["--scope", "checks"]), 0)
self.assertEqual(runner.main(["--scope", "checks"]), 0)
self.assertEqual(build.call_count, 1)
- def failing(*_):
- return unittest.TestSuite([unittest.FunctionTestCase(lambda: self.fail("fixture"))])
+ def failing(*scopes, **planned):
+ return self.scope_suite(*scopes, fail=True, **planned)
build.side_effect = failing
self.assertEqual(runner.main(["--scope", "checks", "--fresh"]), 1)
self.assertFalse(evidence.covers(evidence.read(self.repo, evidence.key(self.repo)), ("checks",)))
@@ -607,8 +1068,7 @@ class VerificationTests(unittest.TestCase):
with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()), \
mock.patch.object(runner, "ROOT", self.repo), \
mock.patch.object(runner, "resolve_auto_scope", return_value=(("full",), "fixture")), \
- mock.patch.object(runner, "build_suite", return_value=unittest.TestSuite([
- unittest.FunctionTestCase(lambda: None)])) as build:
+ mock.patch.object(runner, "build_suite", side_effect=self.scope_suite) as build:
self.assertEqual(runner.main(["--scope", "auto"]), 0)
build.assert_called_once_with("checks", "tooling")
record = evidence.read(self.repo, evidence.key(self.repo))
@@ -633,10 +1093,12 @@ class VerificationTests(unittest.TestCase):
with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()), \
mock.patch.object(runner, "ROOT", self.repo), \
mock.patch.object(runner, "resolve_auto_scope", return_value=(("checks",), "fixture")), \
- mock.patch.object(runner, "build_suite", return_value=unittest.TestSuite([
- unittest.FunctionTestCase(lambda: None)])) as build:
+ mock.patch.object(runner, "build_suite", side_effect=self.scope_suite) as build:
self.assertEqual(runner.main(["--scope", "auto"]), 0)
- build.assert_called_once_with("checks")
+ self.assertEqual(build.call_count, 1)
+ self.assertEqual(build.call_args.args, ('checks',))
+ self.assertLessEqual(set(build.call_args.kwargs.get('assigned_names', ())),
+ {path.name for path in runner.selected_files('checks')})
def test_baseline_distinguishes_version_assignment_and_package_logic(self):
self.certify(self.repo, ("full",))
@@ -688,7 +1150,7 @@ class VerificationTests(unittest.TestCase):
"web": ("test_web.py",)}
select = lambda scope: tuple(Path(name) for name in mapping.get(scope, ()))
- def mutate(*args):
+ def mutate(*args, **kwargs):
(self.repo / "README.md").write_text("检查期间的文档修订\n", encoding="utf-8")
return True, 2, []
@@ -721,11 +1183,13 @@ class VerificationTests(unittest.TestCase):
changed = self.repo / "tests/support/shared.py"
changed.parent.mkdir(parents=True)
changed.write_text("value = 1\n", encoding="utf-8")
- self.assertEqual(test_progress.retained(source, evidence.inputs(self.repo), runner.scopes_for_changes, select), {})
+ self.assertEqual(test_resume.combine(self.repo, [source], evidence.inputs(self.repo), {'test_web.py'},
+ runner.scopes_for_changes, select), {})
changed.unlink()
other = {**context, "environment": "different"}
- self.assertEqual(test_progress.retained(source, other, runner.scopes_for_changes, select), {})
- self.assertEqual(test_progress.retained({**source, "cohort": None}, context, runner.scopes_for_changes, select), {})
+ self.assertEqual(test_resume.combine(self.repo, [source], other, {'test_web.py'}, runner.scopes_for_changes, select), {})
+ self.assertEqual(test_resume.combine(self.repo, [{**source, 'cohort': None}], context, {'test_web.py'},
+ runner.scopes_for_changes, select), {})
def test_content_signatures_preserve_narrow_comment_and_metadata_deltas(self):
path = self.repo / "tests/support/shared.py"
@@ -753,7 +1217,9 @@ class VerificationTests(unittest.TestCase):
mapping = {"full": ("a", "b", "c", "d"), "catalog": ("a", "b", "d"),
"media": ("b", "c", "d"), "web": ("a", "b", "c")}
select = lambda scope: tuple(Path(name) for name in mapping[scope])
- self.assertEqual(test_progress.pending({"d": 100}, select, ("catalog", "media", "web")), ("web",))
+ requirements = {scope: {path.name for path in select(scope)} for scope in mapping}
+ self.assertEqual(test_resume.choose_scopes({'a', 'b', 'c'}, requirements,
+ ('catalog', 'media', 'web')), ('web',))
def test_partial_baseline_preserves_unaffected_scopes_and_their_age(self):
original = self.certify(self.repo, ("catalog", "metadata", "web"))
@@ -898,11 +1364,13 @@ class EvidenceExpiryTests(unittest.TestCase):
def test_signing_a_record_prunes_expired_ones_and_keeps_a_fresh_failure(self):
expired = self.place(f"{self.old}.json", stale=True)
- context = {"manifest": {}, "environment": "fixture"}
+ manifest = {'files': {}, 'signatures': {}}
+ context = {'manifest': manifest, 'environment': 'fixture'}
+ state = evidence.digest([evidence.digest(manifest), context['environment']])
with mock.patch.object(evidence, "evidence_dir", return_value=self.folder):
- evidence.write(self.folder, self.live, ("checks",), success=False, elapsed=0,
+ evidence.write(self.folder, state, ("checks",), success=False, elapsed=0,
slowest=[], count=0, previous={}, context=context)
- record = evidence.read(self.folder, self.live)
+ record = evidence.read(self.folder, state)
self.assertFalse(expired.exists())
self.assertEqual(record["failed_scopes"], ["checks"])
diff --git a/tests/test_test_history.py b/tests/test_test_history.py
index bee11a419..f34f2ee05 100644
--- a/tests/test_test_history.py
+++ b/tests/test_test_history.py
@@ -127,6 +127,7 @@ class HistoryFileTests(unittest.TestCase):
self.assertTrue(history.nested())
self.assertIsNone(history.append(runner.ROOT, scope='full:full', files=[], rows=[]))
self.assertEqual(history.take_external(), [])
+ history.record_external([history.result('vitest:fixture > failure', 'fail', 0.0)])
self.assertEqual(history._external, [outer], '外层运行收集到一半的结果原样留着')
def test_the_parent_collects_every_shards_rows(self):
@@ -139,7 +140,7 @@ class HistoryFileTests(unittest.TestCase):
def spawn(command, *, stdout, stderr, cwd):
index = int(command[command.index('--shard-index') + 1])
Path(command[command.index('--timings') + 1]).write_text(json.dumps({
- 'success': True, 'count': 1, 'timings': [],
+ 'complete': True, 'success': False, 'count': 1, 'timings': [],
'results': [history.result(f'test_{index}.T.test_x', 'fail', 0.1, 'boom')]}), encoding='utf-8')
return Done()
@@ -151,6 +152,15 @@ class HistoryFileTests(unittest.TestCase):
class ExternalRowsTests(unittest.TestCase):
+ def test_file_completion_preserves_process_and_suite_failures(self):
+ frontend = Path(tempfile.gettempdir()).resolve() / 'frontend'
+ report = {'testResults': [{'name': str(frontend / 'test/a.test.ts'), 'status': 'passed'},
+ {'name': str(frontend / 'test/b.test.ts'), 'status': 'failed'}]}
+ rows = history.vitest_files(report, frontend)
+ self.assertEqual([row['outcome'] for row in rows], ['pass', 'fail'])
+ self.assertTrue(all(row['file_complete'] for row in rows))
+ self.assertEqual(history.file_result('e2e', 'e2e/a.test.ts', False)['outcome'], 'fail')
+
def test_tap_leaves_become_rows_with_their_suite_path(self):
rows = history.tap_rows('e2e/anchor-navigation.test.ts', TAP)
self.assertEqual([(row['id'], row['outcome']) for row in rows], [
diff --git a/tests/test_test_planning.py b/tests/test_test_planning.py
index 2b9409486..c89939341 100644
--- a/tests/test_test_planning.py
+++ b/tests/test_test_planning.py
@@ -445,7 +445,7 @@ class TestPlanningTests(unittest.TestCase):
plan = json.loads(Path(command[command.index('--shard-plan') + 1]).read_text(encoding='utf-8'))
seen.append((index, plan[index]))
Path(command[command.index('--timings') + 1]).write_text(
- json.dumps({'success': True, 'count': 1, 'timings': []}), encoding='utf-8')
+ json.dumps({'complete': True, 'success': True, 'count': 1, 'timings': []}), encoding='utf-8')
return Done()
plan = [['test_web_e2e.py'], ['test_a.py', 'test_b.py'], ['test_c.py']]
@@ -493,7 +493,7 @@ class TestPlanningTests(unittest.TestCase):
launched.append(command)
index = int(command[command.index('--shard-index') + 1])
report = Path(command[command.index('--timings') + 1])
- report.write_text(json.dumps({'success': index != failing, 'count': 10 + index,
+ report.write_text(json.dumps({'complete': True, 'success': index != failing, 'count': 10 + index,
'timings': [[0.5, f'test_{index}']],
'files': {f'test_{index}': 1.0 + index}}), encoding='utf-8')
stdout.write(f'分片 {index} 的输出\n')
@@ -611,8 +611,8 @@ class GateAndFlakyRerunTests(unittest.TestCase):
self.assertEqual(runner.rerun_selectors(rows), [
'test_feeds_web.FeedsWebTests.test_second_round', 'frontend/e2e/folder-layout.test.ts',
'frontend/test/react/follow-feed.test.tsx'])
- self.assertIsNone(runner.rerun_selectors([self.fail('setUpClass (test_web_e2e.WebE2ESmokeTests)')]),
- '类级准备失败没有可单独重跑的那一条')
+ self.assertEqual(runner.rerun_selectors([self.fail('setUpClass (test_web_e2e.WebE2ESmokeTests)')]),
+ ['test_web_e2e'], '类级准备失败选择所属模块')
self.assertIsNone(runner.rerun_selectors([self.fail(
'test_web_e2e.WebE2ESmokeTests.test_every_route_holds_the_layout_and_runtime_invariants')]),
'浏览器容器失败却没有逐条结果:说不清是哪个文件')
diff --git a/tests/test_web_e2e.py b/tests/test_web_e2e.py
index 484831ed3..65a64597a 100644
--- a/tests/test_web_e2e.py
+++ b/tests/test_web_e2e.py
@@ -365,8 +365,10 @@ class WebE2ESmokeTests(unittest.TestCase):
output = f"{completed.stdout}\n{completed.stderr}"
log_path.write_text(output, encoding="utf-8")
test_history.record_external(test_history.tap_rows(path, completed.stdout))
- if (completed.returncode != 0 or not re.search(r"# pass [1-9]\d*", output)
- or not re.search(r"# fail 0\b", output)):
+ success = (completed.returncode == 0 and bool(re.search(r"# pass [1-9]\d*", output))
+ and bool(re.search(r"# fail 0\b", output)))
+ test_history.record_external([test_history.file_result('e2e', path, success, time.monotonic() - started)])
+ if not success:
return path, time.monotonic() - started, \
f"{path} 退出码 {completed.returncode},日志:{log_path}\n{output}"
return path, time.monotonic() - started, None
@@ -464,6 +466,9 @@ class SetupE2ETests(unittest.TestCase):
output = f"{completed.stdout}\n{completed.stderr}"
log_path.write_text(output, encoding="utf-8")
test_history.record_external(test_history.tap_rows(SETUP_SUITE, completed.stdout))
+ test_history.record_external([test_history.file_result('e2e', SETUP_SUITE,
+ completed.returncode == 0 and bool(re.search(r'# pass 1\b', output))
+ and bool(re.search(r'# skipped 0\b', output)))])
self.assertEqual(completed.returncode, 0, f"{output}\n--- serve.log ---\n{self._server_log()}")
self.assertRegex(output, r"# pass 1\b", output)
self.assertRegex(output, r"# skipped 0\b", output)
@@ -618,11 +623,14 @@ class MissingPrerequisiteTests(unittest.TestCase):
mock.patch(__name__ + ".BROWSER_LOGS", log_root), \
mock.patch(__name__ + ".e2e_pools", return_value=((files[:3], 2), (files[3:], 1))), \
mock.patch.object(case, "_server_log", return_value="serve fixture"), \
+ mock.patch.object(test_history, 'record_external') as recorded, \
mock.patch("subprocess.run", side_effect=run), \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(AssertionError) as raised:
case.test_every_route_holds_the_layout_and_runtime_invariants()
self.assertCountEqual([command[-1] for command, _ in calls], files)
+ finished = [row for call in recorded.call_args_list for row in call.args[0] if row.get('file_complete')]
+ self.assertCountEqual([row['outcome'] for row in finished], ['pass', 'pass', 'fail', 'fail'])
self.assertEqual(calls[-1][0][-1], "e2e/fourth.test.ts", "串行池在并发池全部结束后才开始")
for command, options in calls:
self.assertEqual(command[:3], ["node", "--test", "--test-concurrency=1"])