# -*- coding: utf-8 -*- """核心设计意图覆盖核验(只读、零污染)。 用途: 主人最怕"改坏"的那几条业务口径(设计意图)有没有被现有 p0/p1 测试真正断言到。 做法: 纯文本静态扫描——只读取 CostReview 的源码与测试,绝不 import、绝不写回。 输出: out/report.md(人读)+ out/report.json(机读),落在工具包自己的 out/ 目录。 安全边界(硬规矩,违反即删): - 不 import 任何 app 模块(避免触发 app 副作用 / 写库)。 - 不向 CostReview/ 写任何文件(输出只落本工具包 out/)。 - 只 open(..., 'r'),对工程目录绝不 open(..., 'w')。 """ import json import os import re import sys from pathlib import Path BASE = Path(__file__).resolve().parent DEFAULT_INTENTS = str(BASE / "intents.json") APP_DEFAULT = r"D:/PricingReview/CostReview/app" TESTS_DEFAULT = r"D:/PricingReview/CostReview/app/tests" OUT_DEFAULT = str(BASE / "out") def _iter_py(root): root = Path(root) if root.is_file() and root.suffix == ".py": yield root return if not root.is_dir(): return for p in root.rglob("*.py"): if "__pycache__" in p.parts: continue yield p def scan_source(app_dir, markers): """返回 {marker: [(rel, lineno, snippet)]} 与 matched_files 集合。""" hits = {m: [] for m in markers} matched_files = set() app_dir = Path(app_dir) for p in _iter_py(app_dir): try: text = p.read_text(encoding="utf-8", errors="replace") except Exception: continue rel = str(p.relative_to(app_dir)) if p.is_relative_to(app_dir) else str(p) for i, line in enumerate(text.splitlines(), 1): for m in markers: if m in line: hits[m].append((rel, i, line.strip()[:120])) matched_files.add(rel) return hits, matched_files def scan_tests(tests_dir, markers): """对每个 marker,返回命中的 (file, func, assert_count) 列表(按 test 函数分块)。""" results = {m: [] for m in markers} tests_dir = Path(tests_dir) for p in _iter_py(tests_dir): try: text = p.read_text(encoding="utf-8", errors="replace") except Exception: continue rel = str(p.relative_to(tests_dir)) if p.is_relative_to(tests_dir) else str(p) lines = text.splitlines() cur_func, cur_start = None, 0 for i, line in enumerate(lines, 1): m = re.match(r"\s*def\s+(test_\w+)\s*\(", line) if m: if cur_func is not None: _classify(results, markers, rel, cur_func, lines[cur_start:i]) cur_func, cur_start = m.group(1), i - 1 if cur_func is not None: _classify(results, markers, rel, cur_func, lines[cur_start:]) return results def _classify(results, markers, rel, func, seg): """按 test_ 函数分块,统计:(a) 函数内总 assert 数; (b) 与意图标记词邻近(±WINDOW 行)的 assert 数 —— 这才是"该意图被真正断言"的口径。""" seg_text = "\n".join(seg) WINDOW = 3 marker_lines = set() for idx, line in enumerate(seg): for m in markers: if m in line: marker_lines.add(idx) total_asserts = 0 intent_asserts = 0 for idx, line in enumerate(seg): if re.search(r"\bassert\b", line): total_asserts += 1 if any(abs(idx - ml) <= WINDOW for ml in marker_lines): intent_asserts += 1 for m in markers: if m in seg_text: results[m].append({"file": rel, "func": func, "asserts": total_asserts, "intent_asserts": intent_asserts}) def run(intents_path, app_dir, tests_dir, out_dir): intents = json.loads(Path(intents_path).read_text(encoding="utf-8")) rows = [] for it in intents: src_markers = it.get("source_markers", []) test_markers = it.get("test_markers") or src_markers shits, sfiles = (scan_source(app_dir, src_markers) if src_markers else ({}, set())) thits = scan_tests(tests_dir, test_markers) test_refs = [] for lst in thits.values(): test_refs.extend(lst) seen, uniq = set(), [] for r in test_refs: k = (r["file"], r["func"]) if k in seen: continue seen.add(k) uniq.append(r) source_present = bool(sfiles) covered = len(uniq) > 0 real_asserts = sum(r["intent_asserts"] for r in uniq) if covered and real_asserts > 0: strength = "强(邻近有断言)" elif covered: strength = "弱(仅引用无邻近断言)" else: strength = "未覆盖" rows.append({ "id": it.get("id"), "name": it.get("name"), "desc": it.get("desc", ""), "source_present": source_present, "source_files": sorted(sfiles), "covered": covered, "strength": strength, "assert_count": real_asserts, "test_refs": uniq, }) out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) md = _render_md(rows) md_path = out_dir / "report.md" jsn_path = out_dir / "report.json" md_path.write_text(md, encoding="utf-8") jsn_path.write_text(json.dumps(rows, ensure_ascii=False, indent=2), encoding="utf-8") return rows, md_path, jsn_path def _render_md(rows): lines = ["# 核心设计意图覆盖核验报告", "", f"> 生成方式:只读静态扫描,未 import / 未修改 CostReview 任何文件。", ""] covered = sum(1 for r in rows if r["covered"]) lines.append(f"总意图数:**{len(rows)}** | 已覆盖:**{covered}** | 未覆盖:**{len(rows) - covered}**") lines.append("") for r in rows: tag = "✅" if r["covered"] else "❌" lines.append(f"## [{tag}] {r['id']} {r['name']}") lines.append(f"- 描述:{r['desc']}") lines.append(f"- 源码存在:{r['source_present']} | 测试覆盖:{r['covered']} | " f"强度:**{r['strength']}** | 邻近断言数:{r['assert_count']}") if r["source_files"]: lines.append(f"- 源码命中文件:{', '.join(r['source_files'])}") if r["test_refs"]: lines.append("- 测试引用(intent=与本意图邻近的断言数 / total=函数内总断言数):") for t in r["test_refs"]: lines.append(f" - `{t['file']}::{t['func']}` (intent={t['intent_asserts']} / total={t['asserts']})") lines.append("") return "\n".join(lines) def main(argv=None): argv = argv or sys.argv[1:] intents_path, app_dir = DEFAULT_INTENTS, APP_DEFAULT tests_dir, out_dir = TESTS_DEFAULT, OUT_DEFAULT i = 0 while i < len(argv): a = argv[i] if a in ("-h", "--help"): print(__doc__) return 0 if a == "--intents": intents_path = argv[i + 1]; i += 2; continue if a == "--app": app_dir = argv[i + 1]; i += 2; continue if a == "--tests": tests_dir = argv[i + 1]; i += 2; continue if a == "--out": out_dir = argv[i + 1]; i += 2; continue i += 1 if not os.path.isabs(intents_path): intents_path = str(BASE / intents_path) rows, md_path, jsn_path = run(intents_path, app_dir, tests_dir, out_dir) print(f"报告已生成:\n {md_path}\n {jsn_path}") print(f"已覆盖 {sum(1 for r in rows if r['covered'])}/{len(rows)} 条设计意图") return 0 if __name__ == "__main__": raise SystemExit(main())