Files

65 lines
2.6 KiB
Python

# 只用标准库
"""对 AI 生成的改动跑一组检查,并生成一份“验证记录”(Markdown),作为提交说明 / 作品集证据。
用法:
python verify.py --task "新增优惠价格计算" --check "pytest -q sample" --out verification.md
可以多次传 --check。记录里包含:任务、时间、每条命令的退出码和耗时、输出摘要、结论。
"""
from __future__ import annotations
import argparse
import datetime as dt
import shlex
import subprocess
import sys
import time
from pathlib import Path
def run_check(cmd: str, cwd: Path) -> dict:
t0 = time.perf_counter()
args = shlex.split(cmd)
if args and args[0] in ("pytest", "python"):
args = [sys.executable] + (["-m", "pytest"] + args[1:] if args[0] == "pytest" else args[1:])
p = subprocess.run(args, cwd=cwd, capture_output=True, text=True)
out = (p.stdout + p.stderr).strip().splitlines()
return {"cmd": cmd, "code": p.returncode, "seconds": round(time.perf_counter() - t0, 2),
"tail": "\n".join(out[-8:])}
def render(task: str, results: list[dict], notes: list[str]) -> str:
ok = all(r["code"] == 0 for r in results)
now = dt.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")
lines = [f"# 验证记录:{task}", "", f"- 时间:{now}", f"- 结论:{'通过' if ok else '未通过'}", "",
"| 检查 | 退出码 | 耗时(秒) |", "| --- | --- | --- |"]
lines += [f"| `{r['cmd']}` | {r['code']} | {r['seconds']} |" for r in results]
for r in results:
lines += ["", f"### `{r['cmd']}` 输出摘要", "", "```text", r["tail"], "```"]
if notes:
lines += ["", "## 人工审查要点", ""] + [f"- {n}" for n in notes]
return "\n".join(lines) + "\n"
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--task", default="AI 生成代码的验证")
ap.add_argument("--check", action="append", default=[])
ap.add_argument("--note", action="append", default=[])
ap.add_argument("--out", default="")
ap.add_argument("--cwd", default=str(Path(__file__).parent))
a = ap.parse_args(argv)
checks = a.check or ["pytest -q sample"]
results = [run_check(c, Path(a.cwd)) for c in checks]
md = render(a.task, results, a.note or [
"金额使用 Decimal,舍入方式与产品文档一致(四舍五入到分)",
"补充了“优惠券大于金额”的边界测试:AI 第一版在这里返回负数",
])
if a.out:
Path(a.out).write_text(md, encoding="utf-8")
print(md)
return 0 if all(r["code"] == 0 for r in results) else 1
if __name__ == "__main__":
sys.exit(main())