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
+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}')