fix(qa): 在提交与登记前核对候选逐项报告
build / build (push) Successful in 3m21s

This commit is contained in:
姚章浩
2026-11-25 14:21:04 +08:00
parent c12152529c
commit 6a6fa7129a
4 changed files with 185 additions and 0 deletions
+6
View File
@@ -34,6 +34,12 @@
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
### 原需求单的逐项报告
测试机将 `scripts/qa_report.py` 安装为 `~/.local/bin/kg-qa-report`。在 QA 的 HiFox 任务会话中,从本轮测试设计取得完整编号,保存到 `plan.json` 的 `business`、`regression` 数组。执行 `kg-qa-report init <任务> plan.json sheet.json` 读取原单候选回执并生成待填清单。测试中填写各编号的 `status`(`passed`、`failed`、`blocked`)和 `evidence`。`candidate_check` 记录指定候选部署上的实际验证结果及证据。环境受阻时记录原因。
使用 `kg-qa-report check <任务> plan.json sheet.json` 预检。缺失项按编号提示。使用同一参数将 `check` 换为 `submit` 后,由 QA 本人的 HiFox 执行上下文发表评论。回执变化时,工具会提示重新核对。登记端重新核算汇总和候选实测结论。
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
## 执行器配置
+10
View File
@@ -8,6 +8,7 @@ import re
import sys
from urllib.error import HTTPError
import qa_report
import candidate_release as candidate
import candidate_runtime as runtime
import hifox_release_trigger as hfx
@@ -118,6 +119,8 @@ def publish_candidate(plan, receipt, run):
manual = (record.get('typeId') or (record.get('type') or {}).get('id')) == '1b7f1bb1-72c2-4106-b305-85604cf6d7e2'
if manual:
body += '\n候选已就绪。负责人可在本单切到「测试中」启动同包测试。'
if single:
body += '\nQA 请在测试机用 ~/.local/bin/kg-qa-report 从本轮用例清单生成报告,逐项填写结果和证据,正式候选无法登录时报告 blocked。'
key = 'ready ' + receipt['bundle']
add_comment(plan['task'], key, body)
for item in plan['items']:
@@ -185,6 +188,13 @@ def register(task_id):
row = reports[item_id][0]
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
'invalid QA evidence link')
if [item['task'] for item in plan['items']] == [task_id] and task_id in reports:
accepted = cd.metadata(task(task_id), 'cd_acceptance') or {}
if (accepted.get('sha'), accepted.get('bundle')) != (receipt['sha'], receipt['bundle']):
try:
qa_report.verify_report(reports[task_id][1])
except ValueError as error:
raise cd.CDError(f'QA 请在测试机提交逐项报告:{error}') from error
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
fresh = owner_plan(task_id)
cd.require(fresh == plan, 'release plan changed during registration')
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Prepare candidate QA reports from a case list and per-case evidence."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
POLICY = 'KG-QA-REPORT/v1'
STATES = ('passed', 'failed', 'blocked')
def require(condition, message):
if not condition:
raise ValueError(message)
def summarize(plan, results, host):
require(isinstance(plan, dict), '缺少原用例清单')
ids = []
for group in ('business', 'regression'):
group_ids = plan.get(group)
require(isinstance(group_ids, list) and group_ids, f'缺少 {group} 用例编号')
for case_id in group_ids:
require(isinstance(case_id, str) and case_id.strip() == case_id and case_id, '存在空用例编号')
require(case_id not in ids, f'重复编号 {case_id}')
ids.append(case_id)
require(isinstance(results, dict), '缺少逐项结果')
extras = set(results) - set(ids)
require(not extras, '清单外编号 ' + ', '.join(sorted(extras)))
counts = dict.fromkeys(STATES, 0)
missing = []
for case_id in ids:
entry = results.get(case_id)
if not valid_entry(entry):
missing.append(case_id)
else:
counts[entry['status']] += 1
require(not missing, '请填写结果和证据:' + ', '.join(missing))
require(valid_entry(host), '请填写正式候选环境的实测结果和证据,无法登录请填 blocked')
states = {host['status']} | {k for k, count in counts.items() if count}
verdict = 'failed' if 'failed' in states else 'blocked' if 'blocked' in states else 'passed'
return dict(cases=plan, results=results, candidate_check=host, required=len(ids), verdict=verdict, **counts)
def valid_entry(entry):
return (isinstance(entry, dict) and entry.get('status') in STATES
and isinstance(entry.get('evidence'), str) and bool(entry['evidence'].strip()))
def verify_report(report):
expected = summarize(report.get('cases'), report.get('results'), report.get('candidate_check'))
for key, value in expected.items():
require(type(report.get(key)) is type(value) and report[key] == value, f'报告字段 {key} 与逐项结果不一致')
def cli(*args, body=None):
program = shutil.which('hifox') or str(Path.home() / '.local/bin/hifox')
output = subprocess.check_output([program, *args, '--output', 'json'], input=body, text=True, timeout=45)
return json.loads(output)
def ready(rows):
candidates = sorted((r for r in rows if r['content'].startswith('[KG candidate ready ')
and (r.get('author') or {}).get('id') == '39ae59fb-876c-4587-ab5d-a12a841c6c09'),
key=lambda r: r['createdAt'])
require(candidates, '原单缺少候选就绪回执')
row = candidates[-1]
text = row['content']
def field(pattern):
match = re.search(pattern, text, re.M)
require(match is not None, '候选回执字段不完整')
return match[1]
bundle = field(r'^归档 `([0-9a-f]{64})`$')
require(text.startswith('[KG candidate ready ' + bundle + ']'), '候选归档不一致')
return dict(task=row['taskId'], ready=row['id'], url=field(r'^候选验收地址 (https?://\S+)$'),
sha=field(r'^提交 `([0-9a-f]{40})`$'), bundle=bundle), field(r'用 ([\w.-]+) 代码块回填')
def load(path):
return json.loads(Path(path).read_text())
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['init', 'check', 'submit'])
parser.add_argument('task')
parser.add_argument('plan', help='原用例清单 JSON,含 business、regression 编号数组')
parser.add_argument('sheet', help='逐项填写的结果文件')
args = parser.parse_args()
task = cli('task', 'view', args.task)
def comments():
return cli('task', 'comment', 'list', task['id'], '--limit', '0')
rows = comments()
receipt, fence = ready(rows)
require(receipt['task'] == task['id'], '回执不属于本需求')
plan = load(args.plan)
fingerprint = hashlib.sha256(json.dumps(plan, sort_keys=True).encode()).hexdigest()
if args.action == 'init':
blank = {'status': '', 'evidence': ''}
ids = [k for group in ('business', 'regression') for k in plan[group]]
skeleton = dict(receipt=receipt, plan_digest=fingerprint, candidate_check=blank,
results={k: blank for k in ids})
with Path(args.sheet).open('x') as stream:
json.dump(skeleton, stream, indent=2, ensure_ascii=False)
return
sheet = load(args.sheet)
require(sheet['receipt'] == receipt, '候选版本已变化,请为新候选准备结果清单')
require(sheet['plan_digest'] == fingerprint, '原用例清单已变化,请核对用例范围')
report = dict(**receipt, **summarize(plan, sheet['results'], sheet['candidate_check']))
verify_report(report)
payload = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2)
require('```' not in payload, '证据请填写简短结论或附件名,避免嵌套代码围栏')
text = f'{POLICY} 候选实测结果 {report["verdict"]}\n\n```{fence}\n{payload}\n```'
if args.action == 'check':
print(text)
return
qa_authors = {'62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
def existing(rows):
return next((r for r in rows if r['content'] == text and (r.get('author') or {}).get('id') in qa_authors), None)
found = existing(rows)
if not found:
# The child CLI inherits the QA session's identity. Never replace it with an operator login.
cli('task', 'comment', task['id'], '--body-stdin', body=text)
found = existing(comments())
if found is None:
raise ValueError('请在原单核对评论及 QA 署名后再决定是否重试')
print(found['id'])
if __name__ == '__main__':
try:
main()
except (OSError, KeyError, TypeError, ValueError, subprocess.SubprocessError) as error:
sys.exit(f'QA 报告:{error}')
+31
View File
@@ -0,0 +1,31 @@
import unittest
import qa_report as qa
class QAReportTest(unittest.TestCase):
def setUp(self):
self.plan = {'business': ['A'], 'regression': ['R']}
self.host = {'status': 'passed', 'evidence': 'QA login and operations on the candidate'}
self.rows = {i: {'status': 'passed', 'evidence': i + '.log'} for i in ('A', 'R')}
def test_missing_id_named_before_output(self):
del self.rows['R']
with self.assertRaisesRegex(ValueError, 'R'):
qa.summarize(self.plan, self.rows, self.host)
def test_duplicate_across_groups(self):
with self.assertRaisesRegex(ValueError, 'A'):
qa.summarize(dict(self.plan, regression=['A']), self.rows, self.host)
def test_candidate_login_blocks_local_green(self):
report = qa.summarize(self.plan, self.rows, {'status': 'blocked', 'evidence': 'candidate login 401'})
self.assertEqual(report['verdict'], 'blocked')
def test_generated_report_reconciles(self):
report = qa.summarize(self.plan, self.rows, self.host)
self.assertEqual((report['cases'], report['required'], report['passed']), (self.plan, 2, 2))
qa.verify_report(report)
report['passed'] = 1
with self.assertRaisesRegex(ValueError, 'passed'):
qa.verify_report(report)