Skip to content

armgit / peach

Public Imported from GitHub
0

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

perf(test): 仅追加精确测试登记时验证实际影响域

longmeidaod970492e045c
diff --git a/docs/TESTING.md b/docs/TESTING.md
index c458cdcae..d49c9a3a4 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -267,6 +267,8 @@ GitGud 的三平台验证使用正式恢复入口,通过 GitLab 原生缓存
新增、删除文件按所属功能域选测;已有文件的执行权限变化和符号链接保持 `full`。
+只在 `SCOPES` 的现有域末尾追加精确 `test_*.py` 文件名、且登记表外的 AST 完全不变时,选择新增测试所属域、checks 与 tooling;这两项保留选测计划、登记完整性和证明协议回归。删除、改序、通配符、新域、既有路径映射和执行逻辑变化仍按完整验证处理。普通 `scripts/` 脚本已有 tooling 前缀映射,同域时不再添加重复的 `AUTO_SCOPE_FILES` 条目。记录快照和 CI 使用同一内容判据;无法识别的旧记录保持保守判断。
+
`src/peach/` 的已知模块合并直接导入它的测试所在域,名称或显式映射不排除直接消费者。按名字推不出测试文件的模块,还并上直接导入它的源码文件按同一套规则推出的域;互相导入的一组模块合起来算。导入者推不出域、谁都不导入它,或未知模块被共享测试设施 `tests/support` 使用时仍 `full`。不沿导入链一路扩散:函数里的延迟导入把几乎所有模块连成一团,传递闭包等于全量。随应用分发的 `resources/` 按加载它的模块与打包面选域;`.gitlab-ci.yml` 与 `MANIFEST.in` 在本机选 `packaging` 与 `tooling`(主线流水线改 `.gitlab-ci.yml` 时三平台仍跑全量);只登记在 `core` 或 `packaging` 的测试文件改动时跑登记它的那个域。
README 的 Python 下限和双语入口由 checks 的安装契约检查,普通文档不选择整个 tooling。静态文件输入识别以仓库根及其别名为依据,临时夹具的同名写入不属于仓库读取。缺失文件不进入当前快照,删除由前后文件集合识别,暂存或提交相同删除不会改变内容证明。
diff --git a/scripts/change_impact.py b/scripts/change_impact.py
index 9fc0feca4..d4bb0e492 100644
--- a/scripts/change_impact.py
+++ b/scripts/change_impact.py
@@ -6,6 +6,7 @@ from functools import lru_cache
import hashlib
import json
from pathlib import PurePosixPath
+import re
import tomllib
@@ -29,12 +30,27 @@ def dependency_inputs(source: str) -> dict:
@lru_cache(maxsize=2048)
-def signatures(path: str, source: str) -> dict[str, str]:
+def signatures(path: str, source: str) -> dict[str, object]:
"""返回可比较的内容指纹;docstring、类型注释和运行时字串参与比较。"""
try:
if path.endswith(".py"):
tree = ast.parse(source, type_comments=True)
- return {"behavior": digest(ast.dump(tree, include_attributes=False))}
+ result = {"behavior": digest(ast.dump(tree, include_attributes=False))}
+ if path == 'scripts/test_runner.py':
+ declarations = [node for node in tree.body if
+ (isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == 'SCOPES')
+ or (isinstance(node, ast.Assign) and len(node.targets) == 1
+ and isinstance(node.targets[0], ast.Name) and node.targets[0].id == 'SCOPES')]
+ if len(declarations) == 1:
+ declaration = declarations[0]
+ scopes = ast.literal_eval(declaration.value)
+ if isinstance(scopes, dict) and all(isinstance(name, str) and isinstance(patterns, tuple)
+ and all(isinstance(pattern, str) for pattern in patterns)
+ for name, patterns in scopes.items()):
+ declaration.value = ast.Constant(value=None)
+ result['scope_body'] = digest(ast.dump(tree, include_attributes=False))
+ result['scope_entries'] = [[name, list(patterns)] for name, patterns in scopes.items()]
+ return result
if path in PACKAGE_FILES:
data = json.loads(source)
if not isinstance(data, dict):
@@ -47,6 +63,46 @@ def signatures(path: str, source: str) -> dict[str, str]:
return {}
+def valid_scope_entries(value: object) -> bool:
+ """验证快照中的有序登记表,拒绝重复域与非字符串模式。"""
+ if not isinstance(value, list):
+ return False
+ names = set()
+ for row in value:
+ if (not isinstance(row, list) or len(row) != 2 or not isinstance(row[0], str)
+ or not re.fullmatch(r'[a-z]+', row[0]) or row[0] in names
+ or not isinstance(row[1], list) or not all(isinstance(item, str) for item in row[1])):
+ return False
+ names.add(row[0])
+ return True
+
+
+def added_scope_tests(before: dict, after: dict) -> tuple[str, ...]:
+ """只接受现有域末尾追加的精确测试文件,其他覆盖和执行变化保持完整验证。"""
+ if not before.get('scope_body') or before.get('scope_body') != after.get('scope_body'):
+ return ()
+ old, new = before.get('scope_entries'), after.get('scope_entries')
+ if not valid_scope_entries(old) or not valid_scope_entries(new) or len(old) != len(new):
+ return ()
+ changed = []
+ for first, second in zip(old, new):
+ if not isinstance(first, list) or not isinstance(second, list) or len(first) != 2 or len(second) != 2:
+ return ()
+ name, patterns = first
+ updated_name, updated = second
+ if (not isinstance(name, str) or name != updated_name or not re.fullmatch(r'[a-z]+', name)
+ or not isinstance(patterns, list) or not isinstance(updated, list)
+ or updated[:len(patterns)] != patterns):
+ return ()
+ added = updated[len(patterns):]
+ if any(not isinstance(item, str) or not re.fullmatch(r'test_[A-Za-z0-9_]+\.py', item)
+ or item in patterns for item in added):
+ return ()
+ if added:
+ changed.append(name)
+ return tuple(changed)
+
+
def kind(path: str, before: str | None, after: str | None) -> str:
if before is None or after is None:
return "unsafe"
@@ -58,6 +114,8 @@ def signature_kind(before: dict, after: dict) -> str:
return "prose"
if before.get("dependencies") and before.get("dependencies") == after.get("dependencies"):
return "metadata"
+ if scopes := added_scope_tests(before, after):
+ return 'registration:' + ','.join(scopes)
return "logic"
diff --git a/scripts/test_evidence.py b/scripts/test_evidence.py
index f9c6ef39a..3bc53f8a3 100644
--- a/scripts/test_evidence.py
+++ b/scripts/test_evidence.py
@@ -298,7 +298,10 @@ def valid_manifest(manifest) -> bool:
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)
+ and all(isinstance(key, str) and (
+ key == 'scope_entries' and name == 'scripts/test_runner.py'
+ and change_impact.valid_scope_entries(stamp)
+ or isinstance(stamp, str) and _STATE.fullmatch(stamp))
for key, stamp in value.items())
for name, value in manifest.get('signatures', {}).items())
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 8e4a1d620..70e95e711 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -515,6 +515,12 @@ def changed_contents(root: Path, base: str, paths: Iterable[str]) -> dict:
def special_scopes(path: str, kind: str) -> tuple[str, ...] | None:
"""内容类型、共享设施和工作流职责的优先边界。"""
+ if path == 'scripts/test_runner.py' and kind.startswith('registration:'):
+ added = kind.removeprefix('registration:').split(',')
+ if all(scope in SCOPES for scope in added):
+ # tooling 保留登记完整性与证据协议回归,checks 保留选测计划和公共门槛。
+ return tuple(scope for scope in SCOPES if scope in {'checks', 'tooling', *added})
+ return ('full',)
if kind == "unsafe":
return ("full",)
if kind == "prose":
diff --git a/tests/test_test_planning.py b/tests/test_test_planning.py
index f3afc225f..1d7e8ed2e 100644
--- a/tests/test_test_planning.py
+++ b/tests/test_test_planning.py
@@ -97,6 +97,50 @@ class CIFrontendOwnershipTests(unittest.TestCase):
class TestPlanningTests(unittest.TestCase):
+ def test_additive_exact_test_registration_selects_affected_domains_and_collection_guards(self):
+ from scripts import change_impact
+ before = ("SCOPES = {'checks': ('test_context_budget.py',), "
+ "'tooling': ('test_scripts.py',), 'catalog': ('test_search_suggest.py',)}\n"
+ "AUTO_SCOPE_FILES = {}\ndef execute(): return 1\n")
+ after = before.replace("'test_scripts.py',", "'test_scripts.py', 'test_new_script.py',")
+ contents = {'scripts/test_runner.py': (before, after)}
+ self.assertEqual(runner.scopes_for_changes(contents, contents=contents)[0], ('checks', 'tooling'))
+ planned = ci_plan.plan('pull_request', list(contents), contents)
+ self.assertFalse(planned['wide'])
+ self.assertFalse(planned['browser'])
+ first = change_impact.signatures('scripts/test_runner.py', before)
+ second = change_impact.signatures('scripts/test_runner.py', after)
+ from scripts import test_evidence
+ self.assertTrue(test_evidence.valid_manifest({'files': {}, 'signatures': {'scripts/test_runner.py': first}}))
+ for entries in ({}, [['tooling', [None]]], [['tooling', []], ['tooling', []]]):
+ self.assertFalse(test_evidence.valid_manifest({'files': {}, 'signatures': {
+ 'scripts/test_runner.py': {**first, 'scope_entries': entries}}}))
+ self.assertFalse(test_evidence.valid_manifest({'files': {}, 'signatures': {'other.py': first}}))
+ paths, kinds = change_impact.delta(
+ {'files': {'scripts/test_runner.py': [420, 'before', '100644']}, 'signatures': {'scripts/test_runner.py': first}},
+ {'files': {'scripts/test_runner.py': [420, 'after', '100644']}, 'signatures': {'scripts/test_runner.py': second}})
+ self.assertEqual(runner.scopes_for_changes(paths, kinds=kinds)[0], ('checks', 'tooling'))
+ catalog = before.replace("'test_search_suggest.py',", "'test_search_suggest.py', 'test_new_catalog.py',")
+ self.assertEqual(runner.scopes_for_changes(['scripts/test_runner.py'], contents={
+ 'scripts/test_runner.py': (before, catalog)})[0], ('checks', 'catalog', 'tooling'))
+
+ def test_registration_narrowing_does_not_hide_changes_to_existing_coverage_or_execution(self):
+ before = ("SCOPES = {'checks': ('test_context_budget.py',), "
+ "'tooling': ('test_scripts.py',), 'catalog': ('test_search_suggest.py',)}\n"
+ "AUTO_SCOPE_FILES = {}\ndef execute(): return 1\n")
+ changed = [before.replace("'test_scripts.py',", ''),
+ before.replace("'test_scripts.py',", "'test_scripts.py', 'test_*.py',"),
+ before.replace("'test_scripts.py',", "'test_scripts.py', '../outside.py',"),
+ before.replace("'test_scripts.py',", "'test_new_script.py', 'test_scripts.py',"),
+ before.replace('return 1', 'return 2'),
+ before.replace('AUTO_SCOPE_FILES = {}', "AUTO_SCOPE_FILES = {'x.py': ('checks',)}"),
+ before + "SCOPES['tooling'] = ()\n",
+ before.replace("'catalog':", "'new_scope':")]
+ for after in changed:
+ with self.subTest(after=after):
+ self.assertEqual(runner.scopes_for_changes(['scripts/test_runner.py'], contents={
+ 'scripts/test_runner.py': (before, after)})[0], ('full',))
+
def test_checks_ci_omits_runtime_tool_installation_and_keeps_platforms(self):
for path in ("README.md", "CONTRIBUTING.md", ".github/PULL_REQUEST_TEMPLATE.md", "docs/TESTING.md"):
with self.subTest(path=path):