Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(test): 隔离容器用例的选择环境

longmeidao93a2b88c005b
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 4af58648b..6f27dccfb 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -214,7 +214,7 @@ macOS Release 使用 `macos-15`(Apple Silicon)和 `macos-15-intel`(Intel
正式父运行在开始时原子保存待验证状态,每个分片完成后立即保存检查点。失败批次仍保留成功文件、成功补充用例及其时间;整文件状态不覆盖已取得的单项结果。共享输入变化和 `Fresh` 同时作用于文件及其补充用例。快速门槛失败时,其余文件保持未完成。进程中断后,下一次 `auto` 在所需范围内补齐缺少的文件,串行与并行使用相同结果模型。分片报告必须完整且格式有效;异常退出不能签发该片的整体成功。分片写出完成报告后仍未退出的进程,等待 15 秒后回收该片的进程树,不给尚在执行的测试设置额外时限。
-浏览器与 Vitest 容器内按外部测试文件保存完成结果,只有逐条输出不能证明整个文件完成。恢复计划绑定当前输入快照、完整文件集合及每个省略项的成功时间。Python 容器用例自身也必须有成功证明,才能连同其外部文件一起省略;容器的后置检查失败仍需补测。外部选择仅由正式父运行生成,`Focus` 和独立 CI 分片不签发正式记录。
+浏览器与 Vitest 容器内按外部测试文件保存完成结果,只有逐条输出不能证明整个文件完成。恢复计划绑定当前输入快照、完整文件集合及每个省略项的成功时间。Python 容器用例自身也必须有成功证明,才能连同其外部文件一起省略;容器的后置检查失败仍需补测。选择参数只在对应容器用例执行期间启用,普通 Python 用例不继承这些参数;失败或退出时恢复环境。外部选择仅由正式父运行生成,`Focus` 和独立 CI 分片不签发正式记录。
全量证明还要求所有文件与容器检查属于同一个完整批次。独立局部运行可以补齐所需域,不能拼成 `full`;有完整批次来源的中断或失败运行,补齐缺少项后可恢复全量证明。每次写入时清退写盘超过 24 小时的记录、持锁说明与残留临时文件;锁文件和非记录文件不动。
diff --git a/scripts/test_focus.py b/scripts/test_focus.py
index 234e4fa0f..f1f2e9cdf 100644
--- a/scripts/test_focus.py
+++ b/scripts/test_focus.py
@@ -1,13 +1,11 @@
"""统一测试入口的定向调试;不签发正式验收记录。"""
from __future__ import annotations
-import json
-import os
import re
import sys
import unittest
from pathlib import Path
-from unittest import mock
+from functools import partial
VITEST_SUITE = "test_frontend_build.VitestTests.test_the_island_suite_passes"
@@ -58,12 +56,15 @@ def run(runner, args) -> int:
print(error, file=sys.stderr)
return 2
print("定向调试:只运行指定用例,不签发正式记录;提交前仍需 auto。", flush=True)
- flags = {"PEACH_TEST_FOCUS": "1", "PEACH_E2E_FILES": json.dumps(browsers)} if browsers else {}
+ external = {}
+ if browsers:
+ external['test_web_e2e.py'] = ['frontend/' + name for name in browsers]
if islands:
- flags["PEACH_VITEST_FILES"] = json.dumps(islands)
- with mock.patch.dict(os.environ, flags):
- with runner.test_history.running():
- result = unittest.TextTestRunner(verbosity=2, resultclass=runner.TimedResult).run(suite)
+ external['test_frontend_build.py'] = ['frontend/' + name for name in islands]
+ plan = {'external': external, 'focus': True}
+ with runner.test_history.running():
+ result = unittest.TextTestRunner(verbosity=2,
+ resultclass=partial(runner.TimedResult, selection=plan)).run(suite)
runner.test_history.append(runner.ROOT, scope="focus:" + " ".join(args.focus),
rows=result.results + runner.test_history.take_external(),
files=sorted(result.files))
diff --git a/scripts/test_resume.py b/scripts/test_resume.py
index 558880012..afe9ff820 100644
--- a/scripts/test_resume.py
+++ b/scripts/test_resume.py
@@ -295,13 +295,16 @@ def validate_child_plan(root: Path, data: dict, *, state: str, valid_seconds: fl
@contextmanager
-def selection_environment(plan):
+def selection_environment(plan, active_module=None):
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', {}):
+ if module in plan.get('external', {}) and (active_module is None or active_module == module):
changed[variable] = os.environ.get(variable)
os.environ[variable] = json.dumps([name.removeprefix('frontend/') for name in plan['external'][module]])
+ if plan.get('focus'):
+ changed['PEACH_TEST_FOCUS'] = os.environ.get('PEACH_TEST_FOCUS')
+ os.environ['PEACH_TEST_FOCUS'] = '1'
try:
yield
finally:
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index ffa314303..82add997b 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -17,7 +17,7 @@ import time
import unittest
from collections.abc import Iterable
from contextlib import contextmanager, nullcontext
-from functools import lru_cache
+from functools import lru_cache, partial
from pathlib import Path
@@ -375,7 +375,7 @@ 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/ci_plan.py", "scripts/test_environment.py", "scripts/change_impact.py", "scripts/test_focus.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",
@@ -700,31 +700,42 @@ class TimedResult(unittest.TextTestResult):
只量用例本身会漏掉建库、起服务那一段,而分片均衡要的正是整份文件占多久。
"""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args, selection=None, **kwargs):
super().__init__(*args, **kwargs)
self.timings = []
self.files: dict[str, float] = {}
self.results: list[dict] = []
self.outcome: dict[str, tuple[str, str | None]] = {}
self.last = time.monotonic()
+ self.selection = selection or {}
+ self.selection_context = None
def startTestRun(self):
self.last = time.monotonic()
super().startTestRun()
def startTest(self, test):
+ if self.selection and test.id() in test_resume.CONTAINERS:
+ self.selection_context = test_resume.selection_environment(
+ self.selection, test_resume.owner('case:' + test.id()))
+ self.selection_context.__enter__()
self.started = time.monotonic()
super().startTest(test)
def stopTest(self, test):
- now = time.monotonic()
- self.timings.append((round(now - self.started, 3), test.id()))
- outcome, message = self.outcome.pop(test.id(), ("pass", None))
- self.results.append(test_history.result(test.id(), outcome, now - self.started, message))
- module = type(test).__module__
- self.files[module] = round(self.files.get(module, 0.0) + now - self.last, 3)
- self.last = now
- super().stopTest(test)
+ try:
+ now = time.monotonic()
+ self.timings.append((round(now - self.started, 3), test.id()))
+ outcome, message = self.outcome.pop(test.id(), ("pass", None))
+ self.results.append(test_history.result(test.id(), outcome, now - self.started, message))
+ module = type(test).__module__
+ self.files[module] = round(self.files.get(module, 0.0) + now - self.last, 3)
+ self.last = now
+ super().stopTest(test)
+ finally:
+ if self.selection_context is not None:
+ self.selection_context.__exit__(None, None, None)
+ self.selection_context = None
def _mark(self, test, outcome: str, err=None) -> None:
message = f"{err[0].__name__}: {err[1]}" if err else None
@@ -1090,12 +1101,11 @@ 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)
+ 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=partial(TimedResult, selection=selection)).run(suite)
save_file_seconds(result.files)
rows = result.results + test_history.take_external()
test_history.append(ROOT, scope=label or " ".join(scopes), rows=rows,
@@ -1127,12 +1137,11 @@ def run_shard_child(args, requested, scopes, files) -> int:
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)
+ 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=partial(TimedResult, selection=selection)).run(suite)
success = result.wasSuccessful() and result.testsRun > 0
rows = result.results + test_history.take_external()
if args.timings is not None:
diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.py
index aeceacce1..b5b7ad75f 100644
--- a/tests/test_test_evidence.py
+++ b/tests/test_test_evidence.py
@@ -24,6 +24,16 @@ from scripts import test_shard_results
from support.gitrepo import seed_repository
+def fixture_process(command, root, env):
+ process = subprocess.Popen(command, cwd=root, env=env, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, text=True, encoding='utf8')
+ try:
+ output, _ = process.communicate(timeout=180)
+ finally:
+ if process.poll() is None:
+ test_shard_results.stop_process_tree(process)
+ return process.returncode, output
+
class ParallelShardTests(unittest.TestCase):
@@ -583,16 +593,8 @@ class SubprocessResumeTests(unittest.TestCase):
env = {**os.environ, 'GITHUB_ACTIONS': 'false', 'CI': ''}
for key in ('PEACH_TEST_FOCUS', 'PEACH_E2E_FILES', 'PEACH_VITEST_FILES'):
env.pop(key, None)
- process = subprocess.Popen([sys.executable, '-X', 'utf8', str(repo / 'entry.py'),
- '--scope', scope, '--jobs', 'auto'], cwd=repo, env=env,
- stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
- text=True, encoding='utf8')
- try:
- output, _ = process.communicate(timeout=180)
- finally:
- if process.poll() is None:
- test_shard_results.stop_process_tree(process)
- return process.returncode, output
+ return fixture_process([sys.executable, '-X', 'utf8', str(repo / 'entry.py'),
+ '--scope', scope, '--jobs', 'auto'], repo, env)
def test_real_parent_and_children_resume_only_the_failed_file(self):
source = Path(__file__).resolve().parents[1]
@@ -644,6 +646,93 @@ class SubprocessResumeTests(unittest.TestCase):
len(failed_calls) + 1)
+class SelectionEnvironmentTests(unittest.TestCase):
+ VARIABLES = ('PEACH_TEST_FOCUS', 'PEACH_E2E_FILES', 'PEACH_VITEST_FILES')
+
+ def setUp(self):
+ self.enterContext(mock.patch.dict(os.environ))
+ for key in self.VARIABLES:
+ os.environ.pop(key, None)
+
+ def suite(self, captured, fail_container=False):
+ def observe(case):
+ captured.append((case.id(), {key: os.environ.get(key) for key in self.VARIABLES}))
+ if fail_container and case.id() in test_resume.CONTAINERS:
+ case.fail('fixture')
+ backend = type('Backend', (unittest.TestCase,), {'__module__': __name__,
+ 'test_before': observe, 'test_after': observe})
+ container = type('VitestTests', (unittest.TestCase,), {'__module__': 'test_frontend_build',
+ 'test_the_island_suite_passes': observe})
+ return unittest.TestSuite([backend('test_before'), container('test_the_island_suite_passes'), backend('test_after')])
+
+ def assert_isolated(self, captured, *, focus):
+ for _, values in (captured[0], captured[2]):
+ self.assertEqual(values, dict.fromkeys(self.VARIABLES))
+ values = captured[1][1]
+ self.assertEqual(json.loads(values['PEACH_VITEST_FILES']), ['test/example.test.ts'])
+ self.assertIsNone(values['PEACH_E2E_FILES'])
+ self.assertEqual(values['PEACH_TEST_FOCUS'], '1' if focus else None)
+ self.assertTrue(all(os.environ.get(key) is None for key in self.VARIABLES))
+
+ def test_serial_formal_selection_only_applies_to_its_container(self):
+ captured = []
+ selection = {'external': {'test_frontend_build.py': ['frontend/test/example.test.ts'],
+ 'test_web_e2e.py': ['frontend/e2e/example.test.ts']}}
+ progress = mock.Mock()
+ progress.child_plan.return_value = selection
+ progress.checkpoint.return_value = True
+ chosen = {Path('test_frontend_build.py'), Path('test_test_evidence.py')}
+ with mock.patch.object(runner, 'build_suite', return_value=self.suite(captured)), \
+ mock.patch.object(runner, 'save_file_seconds'), mock.patch.object(runner.test_history, 'append'), \
+ redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ self.assertTrue(runner.run_serial_suite(('full',), chosen, chosen, progress, 'fixture')[0])
+ self.assert_isolated(captured, focus=False)
+
+ def test_mixed_focus_selection_does_not_leak_into_backend_cases(self):
+ from scripts import test_focus
+ captured = []
+ args = runner.argparse.Namespace(focus=['fixture'])
+ with mock.patch.object(test_focus, 'selection', return_value=(self.suite(captured), (), ('test/example.test.ts',))), \
+ mock.patch.object(runner.test_history, 'append'), \
+ redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ self.assertEqual(test_focus.run(runner, args), 0)
+ self.assert_isolated(captured, focus=True)
+
+ def test_container_failure_restores_selection_before_the_next_case(self):
+ captured = []
+ selection = {'external': {'test_frontend_build.py': ['frontend/test/example.test.ts']}}
+ progress = mock.Mock()
+ progress.child_plan.return_value = selection
+ progress.checkpoint.return_value = True
+ chosen = {Path('test_frontend_build.py'), Path('test_test_evidence.py')}
+ with mock.patch.object(runner, 'build_suite', return_value=self.suite(captured, fail_container=True)), \
+ mock.patch.object(runner, 'save_file_seconds'), mock.patch.object(runner.test_history, 'append'), \
+ redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ self.assertFalse(runner.run_serial_suite(('full',), chosen, chosen, progress, 'fixture')[0])
+ self.assert_isolated(captured, focus=False)
+
+
+class ShardProtocolTests(unittest.TestCase):
+ def test_backend_shard_runs_with_the_full_parent_browser_plan(self):
+ root = Path(__file__).resolve().parents[1]
+ progress = test_run_progress.RunProgress(root, evidence.inputs(root), ('full',),
+ runner.selected_files, runner.scopes_for_changes, runner.SCOPES, supplements=runner.SCOPE_TEST_IDS)
+ with tempfile.TemporaryDirectory() as folder:
+ temporary = Path(folder).resolve()
+ shard = temporary / 'plan.json'
+ shard.write_text(json.dumps([['test_test_planning.py']]), encoding='utf8')
+ resume = temporary / 'resume.json'
+ resume.write_text(json.dumps(progress.child_plan()), encoding='utf8')
+ report = temporary / 'report.json'
+ code, output = fixture_process([sys.executable, '-X', 'utf8', str(root / 'scripts/test_runner.py'),
+ '--scope', 'full', '--shard-plan', str(shard), '--resume-plan', str(resume),
+ '--timings', str(report)], root, dict(os.environ))
+ self.assertEqual(code, 0, output)
+ result = test_shard_results.read_report(report)
+ self.assertTrue(result['success'], output)
+ self.assertGreater(result['count'], 0)
+
+
class VerificationTests(unittest.TestCase):
def setUp(self):
# 这组用例模拟本机验收,运行它的 CI job 身份不属于临时仓库。
@@ -1131,7 +1220,7 @@ class VerificationTests(unittest.TestCase):
self.assertEqual(runner.scopes_for_changes(["docs/HANDOFF.md"])[0], ("checks",))
self.assertEqual(runner.scopes_for_changes(["web/app.js", "src/peach/follow.py"])[0],
("follow", "web"))
- for path in ("pyproject.toml", "scripts/test_runner.py", "scripts/test_evidence.py",
+ for path in ("pyproject.toml", "scripts/test_runner.py", "scripts/test_evidence.py", 'scripts/test_focus.py',
"uv.lock", "src/peach/unknown.py"):
self.assertEqual(runner.scopes_for_changes([path])[0], ("full",))