test(qa): 加入目录规则浏览器回归和暂存门禁
build / build (push) Failing after 7m7s

在 QA 虚拟机通过 Chromium 复跑和本地提交检查,并验证必填校验失效会触发失败。Gitea 将浏览器回归纳入必需检查。
This commit is contained in:
姚章浩
2026-11-22 19:57:24 +08:00
parent d7d636792d
commit 5d00715c3a
18 changed files with 407 additions and 8 deletions
+12 -2
View File
@@ -249,6 +249,8 @@ def checks() -> list[Check]:
[g, "test", "-count=1", "-json", "./..."], env=env, judge=judge_go_tests),
Check("tests-web", "前端测试(vitest,必须真跑)",
[py3, "scripts/ci_checks.py", "--internal-web-test"], env=env),
Check("tests-e2e", "Chromium 浏览器回归(CI 必需)", ["make", "tests-e2e-ci"],
env=env, required_in=("ci",), note="本地用 make tests-e2e,复用已安装的浏览器"),
Check("contracts", "版本与变更记录契约(不许 SKIP;开发构建不许自称正式版)",
[py3, "scripts/ci_checks.py", "--internal-contracts", g], env=env),
Check("version", "CHANGELOG 与版本记录(四类小节无空栏目 + 正式 tag 与提交内版本一致)",
@@ -356,8 +358,7 @@ def cmd_internal_web_test() -> int:
def cmd_internal_contracts(go: str) -> int:
"""版本契约:结构 + 注入身份必须**真 PASS**(SKIP 判红),
并且**开发构建不许自称正式版**(负例:标成 release ⇒ 必须红)。"""
qa_rc = subprocess.run(py("-m", "unittest", "discover", "-s", "scripts", "-p", "test_qa_env.py", "-v"),
cwd=ROOT).returncode
qa_rc = subprocess.run(["make", "test-tooling"], cwd=ROOT).returncode
if qa_rc:
return qa_rc
snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode
@@ -442,6 +443,7 @@ CHECK_MANIFEST: dict[str, tuple[str, ...]] = {
"build-web": ("local", "ci"),
"tests-go": ("local", "ci"),
"tests-web": ("local", "ci"),
"tests-e2e": ("ci",),
"contracts": ("local", "ci"),
"version": ("local", "ci"),
"security-secrets": ("local", "ci"),
@@ -635,6 +637,14 @@ def main(argv: list[str]) -> int:
print(f"\n── [{c.id}] {c.title} ──\n {'✅' if status == SUCCESS else ('⏭️' if status == SKIPPED else '❌')} {reason}")
continue
if args.profile not in c.required_in:
reason = f"{args.profile} 档案不要求此项。{c.note}".strip()
results.append({"id": c.id, "title": c.title, "required_in": list(c.required_in),
"status": SKIPPED, "reason": reason, "command": "",
"exit_code": None, "duration_s": 0})
print(f"\n── [{c.id}] {c.title} ──\n ⏭️ {reason}")
continue
print(f"\n── [{c.id}] {c.title} ──")
print(" $ " + " ".join(c.argv))
t0 = time.time()
+1 -1
View File
@@ -316,7 +316,7 @@ def qa_run(commit, env, db_env, versions, state):
wait_service(web, WEB_PORT, '/', 'html', web_log)
wait_service(web, WEB_PORT, '/health', 'ok', web_log)
report('services', 'API /readyz、Web 首页与 Vite /health 代理通过')
run_step(['make', 'tests-go', 'tests-web'], 'tests', env, 300)
run_step(['make', 'tests-go', 'tests-web', 'tests-e2e'], 'tests', env, 300)
check_checkout(commit)
if api.poll() is not None or web.poll() is not None or not probe(WEB_PORT, '/health', 'ok'):
raise QAError(f'服务在测试期间失去健康状态,日志目录 {log_dir}')
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Select verification commands for staged changes."""
import argparse
from pathlib import Path, PurePosixPath
import re
import shlex
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def select_commands(paths, removed=()):
removed = set(removed)
full_go = full_web = browser = tooling = False
go_packages, web_tests = set(), set()
for name in paths:
path = PurePosixPath(name)
if name.startswith('docs/') or path.suffix == '.md':
continue
if name.startswith('web/e2e/') or name == 'web/playwright.config.ts':
browser = True
elif name.startswith('web/'):
if (name not in removed and name.startswith('web/src/') and
re.fullmatch(r'[\w./-]+\.test\.[jt]sx?', name)):
web_tests.add(str(path.relative_to('web')))
else:
full_web = browser = True
elif name.startswith(('scripts/', '.githooks/')) or name == 'Makefile':
tooling = full_go = full_web = browser = True
elif path.name.endswith('_test.go') and name not in removed:
go_packages.add('./' + path.parent.as_posix())
elif path.suffix == '.go' or name in ('go.mod', 'go.sum') or name.startswith(('internal/', 'cmd/')):
full_go = True
else:
full_go = full_web = browser = True
commands = []
if tooling:
commands.append(['make', 'test-tooling'])
if full_go:
commands.append(['make', 'tests-go'])
elif go_packages:
commands.append(['go', 'test', '-count=1', *sorted(go_packages)])
if full_web:
commands.append(['make', 'tests-web'])
elif web_tests:
commands.append(['npm', '--prefix', 'web', 'test', '--', *sorted(web_tests)])
if browser:
commands.append(['make', 'tests-e2e'])
return commands
def staged_names(*args):
result = subprocess.check_output(['git', 'diff', '--cached', '--no-renames', '--name-only', '-z', *args], cwd=ROOT)
return [name for name in result.decode('utf-8', errors='surrogateescape').split('\0') if name]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--list', action='store_true', help='print selected commands only')
args = parser.parse_args()
commands = select_commands(staged_names(), staged_names('--diff-filter=D'))
if not commands:
print('暂无需要执行测试的暂存文件')
return 0
if not args.list:
unstaged = subprocess.check_output(['git', 'diff', '--name-only', '-z'], cwd=ROOT)
paths = [name for name in unstaged.decode('utf-8', errors='surrogateescape').split('\0') if name]
if select_commands(paths):
print('还有未暂存的代码或配置,先整理工作区后再检查暂存改动', file=sys.stderr)
return 1
for cmd in commands:
print(shlex.join(cmd), flush=True)
if not args.list:
code = subprocess.run(cmd, cwd=ROOT, check=False).returncode
if code:
return code
return 0
if __name__ == '__main__':
sys.exit(main())
+31
View File
@@ -0,0 +1,31 @@
import unittest
from test_changed import select_commands
class SelectionTests(unittest.TestCase):
def test_documentation_only(self):
self.assertEqual(select_commands(['docs/DEVELOPMENT_AND_TESTING.md']), [])
def test_go_test_only_selects_its_package(self):
self.assertEqual(select_commands(['internal/governance/a_test.go']),
[['go', 'test', '-count=1', './internal/governance']])
def test_go_source_and_migration_fall_back_to_suite(self):
for name in ('internal/governance/model.go', 'internal/platform/postgres/migrations/0099_qa.up.sql'):
self.assertEqual(select_commands([name]), [['make', 'tests-go']])
def test_frontend_test_only_selects_its_file(self):
self.assertEqual(select_commands(['web/src/scopeRules.test.ts']),
[['npm', '--prefix', 'web', 'test', '--', 'src/scopeRules.test.ts']])
def test_shared_frontend_code_covers_browser_suite(self):
self.assertEqual(select_commands(['web/src/scopeRules.ts']),
[['make', 'tests-web'], ['make', 'tests-e2e']])
def test_e2e_only_runs_browser_suite(self):
self.assertEqual(select_commands(['web/e2e/scope-rules.spec.ts']), [['make', 'tests-e2e']])
def test_unsafe_unknown_paths_fall_back_to_all_relevant_suites(self):
self.assertEqual(select_commands(['new-runtime.conf']),
[['make', 'tests-go'], ['make', 'tests-web'], ['make', 'tests-e2e']])