Files

465 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""VDE 全库覆盖率汇总(Phase5-Coverage / task-108)。
口径:`VDE_ENABLE_COVERAGE=ON` 对 src/ 下**全部产品库**插桩(--coverage),
测试源码不插桩(仅链接 gcov 运行时)。脚本遍历 build dir 内全部 .gcda,用 MinGW
gcov 文本模式(-b -c;行/函数/分支)解析并聚合到**文件/模块/总体**。
用法(仓库根目录):
python tools/coverage/coverage_report_full.py \
--build-dir build-cov \
--out build-cov/coverage_summary_full.md \
--json build-cov/coverage_summary_full.json \
--tests-log build-cov/ctest_cov.log \
--build-time-sec 480 --disk-gb 20
输出:
- Markdown:总体行/函数/分支覆盖率 + 构建/测试事实 + 模块明细 +
未覆盖热点 top20(含行区间)+ 低覆盖文件 + 复现命令;
- JSON:modules/files/hotspot_top20/totals + 构建信息(机读)。
注意:与旧 docs/reference/42 §3 的“仅 core/curves/mesh/brep 四库”基线**不可直接比较**
(旧口径分母只有 4 个库且只跑 363 个手工用例;本口径为全部产品库 + 全量测试)。
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from collections import defaultdict
from datetime import datetime
LINE_RE = re.compile(r"^\s*([0-9#*=\-]+)\s*:\s*(\d+)\s*:(.*)$")
BRANCH_RE = re.compile(r"^\s*branch\s+(\d+)\s+(?:taken\s+(\d+)|never executed)")
FUNC_RE = re.compile(r"^\s*function\s+(.+?)\s+called\s+(\d+)")
SRC_RE = re.compile(r"Source:\s*(.+?)\s*$")
def find_gcov():
candidates = [
"gcov",
r"C:/Users/gxms0/AppData/Local/Microsoft/WinGet/Packages/"
r"BrechtSanders.WinLibs.POSIX.UCRT_Microsoft.Winget.Source_8wekyb3d8bbwe/"
r"mingw64/bin/gcov.exe",
]
for c in candidates:
if os.path.sep in c or c.endswith(".exe"):
if os.path.exists(c):
return c
else:
p = shutil.which(c)
if p:
return p
raise SystemExit("gcov not found (expected MinGW gcov in PATH)")
def find_gcda(build_dir):
out = []
for root, _dirs, files in os.walk(build_dir):
if "CMakeFiles" not in os.path.normpath(root):
continue
for f in files:
if f.endswith(".gcda"):
out.append(os.path.join(root, f))
return sorted(out)
def normalize_src(raw, repo_root):
"""仅接受仓库 <repo>/src/ 下的产品源文件(.c/.cpp),
排除 eigen3/src、系统头文件、json/include 等干扰路径。"""
p = raw.strip().replace("\\", "/")
repo = os.path.abspath(repo_root).replace("\\", "/").rstrip("/")
prefix = repo + "/src/"
if p.startswith(prefix):
rel = "src/" + p[len(prefix):]
else:
idx = p.find(prefix)
if idx < 0:
return None
rel = "src/" + p[idx + len(prefix):]
ext = os.path.splitext(rel)[1].lower()
if ext not in (".cpp", ".c", ".cc", ".cxx", ".c++"):
return None
return rel
def module_of(src):
parts = src.split("/")
if len(parts) < 3:
return "root"
d = parts[1]
return d[4:] if d.startswith("vde_") else d
def run_gcov_text(gcov, gcda, workdir):
"""运行 gcov 文本模式(-b -c),返回生成的 .gcov 文件路径列表。"""
directory = os.path.dirname(os.path.abspath(gcda))
stem = os.path.basename(gcda)[:-5]
attempts = [
[gcov, "-b", "-c", "-o", directory, os.path.join(directory, stem + ".gcda")],
[gcov, "-b", "-c", "-o", directory, stem],
[gcov, "-b", "-c", os.path.join(directory, stem + ".gcda")],
]
for cmd in attempts:
for f in os.listdir(workdir):
if f.endswith(".gcov"):
os.remove(os.path.join(workdir, f))
try:
proc = subprocess.run(cmd, cwd=workdir, capture_output=True, text=True,
timeout=300)
except Exception:
continue
if proc.returncode != 0:
continue
out = [os.path.join(workdir, f) for f in os.listdir(workdir)
if f.endswith(".gcov")]
if out:
return out
return []
def parse_gcov_text(path, repo_root):
"""解析单个 .gcov:行计数/函数调用数/分支 taken,按源文件聚合返回。"""
files = {}
cur_file = None
with open(path, "r", encoding="utf-8", errors="replace") as fh:
lines = fh.readlines()
for ln in lines:
m = LINE_RE.match(ln)
if m and "Source:" in ln:
m2 = SRC_RE.search(ln)
if m2:
src = normalize_src(m2.group(1), repo_root)
cur_file = None
if src:
cur_file = files.setdefault(
src, {"lines": {}, "funcs": {}, "branches": {}})
continue
fm = FUNC_RE.match(ln)
if fm and cur_file is not None:
name = fm.group(1).strip()
called = int(fm.group(2))
if called > cur_file["funcs"].get(name, -1):
cur_file["funcs"][name] = called
continue
bm = BRANCH_RE.match(ln)
if bm and cur_file is not None:
idx = int(bm.group(1))
taken = int(bm.group(2)) if bm.group(2) is not None else 0
key = (cur_file.get("last_line", 0), idx)
if taken > cur_file["branches"].get(key, -1):
cur_file["branches"][key] = taken
continue
if not m:
continue
count_field, line_no = m.group(1).strip(), int(m.group(2))
if cur_file is None or line_no <= 0:
continue
cur_file["last_line"] = line_no
if count_field == "-":
continue
if count_field in ("#####", "====="):
cnt = 0
else:
try:
cnt = int(count_field.rstrip("*"))
except ValueError:
cnt = 0
if cnt > cur_file["lines"].get(line_no, -1):
cur_file["lines"][line_no] = cnt
for rec in files.values():
rec.pop("last_line", None)
return files
def group_ranges(nums):
if not nums:
return []
nums = sorted(nums)
out = []
start = prev = nums[0]
for n in nums[1:]:
if n == prev + 1:
prev = n
continue
out.append((start, prev))
start = prev = n
out.append((start, prev))
return out
def fmt_ranges(ranges, limit=6):
parts = [f"{a}" if a == b else f"{a}-{b}" for a, b in ranges[:limit]]
if len(ranges) > limit:
parts.append("...")
return ", ".join(parts)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--build-dir", default="build-cov")
ap.add_argument("--repo", default=".")
ap.add_argument("--out", default="")
ap.add_argument("--json", default="")
ap.add_argument("--tests-log", default="",
help="可选:ctest 日志,用于把测试规模写入报告")
ap.add_argument("--build-time-sec", type=float, default=0.0)
ap.add_argument("--disk-gb", type=float, default=0.0)
args = ap.parse_args()
repo = os.path.abspath(args.repo)
build_dir = args.build_dir if os.path.isabs(args.build_dir) \
else os.path.join(repo, args.build_dir)
out_md = args.out or os.path.join(build_dir, "coverage_summary_full.md")
out_json = args.json or os.path.join(build_dir, "coverage_summary_full.json")
gcov = find_gcov()
gcda = find_gcda(build_dir)
if not gcda:
raise SystemExit(f"no .gcda under {build_dir}; run the tests first")
print(f"[cov] gcov={gcov}")
print(f"[cov] {len(gcda)} .gcda files under {build_dir}")
per_file = {}
workroot = tempfile.mkdtemp(prefix="vde_gcov_")
try:
for i, g in enumerate(gcda, 1):
wd = os.path.join(workroot, f"o{i}")
os.makedirs(wd, exist_ok=True)
for text in run_gcov_text(gcov, g, wd):
for src, rec in parse_gcov_text(text, repo).items():
dst = per_file.setdefault(
src, {"lines": {}, "funcs": {}, "branches": {}})
for k, v in rec["lines"].items():
if v > dst["lines"].get(k, -1):
dst["lines"][k] = v
for k, v in rec["funcs"].items():
if v > dst["funcs"].get(k, -1):
dst["funcs"][k] = v
for k, v in rec["branches"].items():
if v > dst["branches"].get(k, -1):
dst["branches"][k] = v
shutil.rmtree(wd, ignore_errors=True)
if i % 100 == 0 or i == len(gcda):
print(f"[cov] parsed {i}/{len(gcda)} gcda")
finally:
shutil.rmtree(workroot, ignore_errors=True)
modules = defaultdict(lambda: {"files": 0, "lines_total": 0, "lines_cov": 0,
"func_total": 0, "func_cov": 0,
"branch_total": 0, "branch_cov": 0,
"uncovered": 0})
file_records = []
for src, rec in sorted(per_file.items()):
mod = module_of(src)
total = len(rec["lines"])
if total == 0:
continue
covered = sum(1 for c in rec["lines"].values() if c > 0)
uncovered_lines = [n for n, c in rec["lines"].items() if c == 0]
ftotal = len(rec["funcs"])
fcov = sum(1 for c in rec["funcs"].values() if c > 0)
btotal = len(rec["branches"])
bcov = sum(1 for c in rec["branches"].values() if c > 0)
m = modules[mod]
m["files"] += 1
m["lines_total"] += total
m["lines_cov"] += covered
m["func_total"] += ftotal
m["func_cov"] += fcov
m["branch_total"] += btotal
m["branch_cov"] += bcov
m["uncovered"] += len(uncovered_lines)
file_records.append({
"path": src, "mod": mod, "total": total, "covered": covered,
"pct": 100.0 * covered / total if total else 0.0,
"func_total": ftotal, "func_cov": fcov,
"branch_total": btotal, "branch_cov": bcov,
"uncovered": len(uncovered_lines),
"ranges": group_ranges(uncovered_lines),
})
total_lines = sum(m["lines_total"] for m in modules.values())
total_cov = sum(m["lines_cov"] for m in modules.values())
total_funcs = sum(m["func_total"] for m in modules.values())
total_fcov = sum(m["func_cov"] for m in modules.values())
total_br = sum(m["branch_total"] for m in modules.values())
total_brcov = sum(m["branch_cov"] for m in modules.values())
line_pct = 100.0 * total_cov / total_lines if total_lines else 0.0
func_pct = 100.0 * total_fcov / total_funcs if total_funcs else 0.0
branch_pct = 100.0 * total_brcov / total_br if total_br else 0.0
hotspot = sorted(file_records, key=lambda r: (-r["uncovered"], r["pct"]))[:20]
low_cov = sorted([r for r in file_records if r["total"] >= 50],
key=lambda r: (r["pct"], -r["total"]))[:15]
build_type = "unknown"
cache = os.path.join(build_dir, "CMakeCache.txt")
if os.path.exists(cache):
for line in open(cache, "r", encoding="utf-8", errors="replace"):
if line.startswith("CMAKE_BUILD_TYPE:"):
build_type = line.split("=", 1)[1].strip() or "unknown"
break
all_src = []
src_root = os.path.join(repo, "src")
for root, _dirs, fs in os.walk(src_root):
for f in fs:
if f.endswith((".cpp", ".c", ".cc", ".cxx")):
full = os.path.join(root, f)
rel = os.path.relpath(full, repo).replace(os.sep, "/")
all_src.append(rel)
missing = sorted(set(all_src) - set(per_file.keys()))
tests_info = ""
tests_sec = 0.0
if args.tests_log and os.path.exists(args.tests_log):
try:
txt = open(args.tests_log, "r", encoding="utf-8", errors="replace").read()
m = re.search(r"(\d+)% tests passed, (\d+) tests failed out of (\d+)", txt)
if m:
tests_info = (f"{m.group(3)} 项测试,{m.group(2)} 失败"
f"(通过率 {m.group(1)}%)")
mt = re.search(r"Total Test time \(real\) = ([\d.]+)", txt)
if mt:
tests_sec = float(mt.group(1))
except Exception:
pass
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
md = []
md.append("# 全库覆盖率基线(Phase5-Coverage / task-108)\n")
md.append(f"- 生成时间:{now}")
md.append(f"- 口径:`VDE_ENABLE_COVERAGE=ON`({build_type} + `--coverage`)对 "
"**src/ 下全部产品库**插桩;测试源码不插桩(仅链接 gcov 运行时)")
md.append(f"- 构建目录:`{args.build_dir}`;gcov:`{gcov}`;统计 .gcda:{len(gcda)} 个")
if args.build_time_sec or args.disk_gb:
md.append(f"- 构建耗时:{args.build_time_sec:.0f}s;产物大小:{args.disk_gb:.1f} GB")
if tests_info:
md.append(f"- 测试执行:{tests_info},耗时 {tests_sec:.1f}s")
md.append("")
md.append("> ⚠️ 与旧基线(docs/reference/42 §3:仅 core/curves/mesh/brep 四库、"
"手工执行 363 用例,行 21.76%/函数 26.56%)**不可直接比较**:旧口径分母"
"只有 4 个库且测试集不同;本口径为全部产品库 + 全量 ctest。\n")
md.append("## 1. 总体")
md.append("")
md.append(f"- **行覆盖率:{line_pct:.2f}%({total_cov:,} / {total_lines:,})**")
md.append(f"- **函数覆盖率:{func_pct:.2f}%({total_fcov:,} / {total_funcs:,})**")
if total_br:
md.append(f"- **分支覆盖率:{branch_pct:.2f}%({total_brcov:,} / {total_br:,})**")
else:
md.append("- 分支覆盖率:gcov 文本未输出分支数据(-b 不可用或代码无分支)")
md.append(f"- 文件数:{len(file_records)};模块数:{len(modules)}")
md.append(f"- 源文件全集:{len(all_src)} 个产品源文件(.c/.cpp);产生 `.gcda` 的 "
f"{len(per_file)} 个;未产生 `.gcda`(本次测试未链接/未执行){len(missing)} 个")
if missing:
md.append("")
md.append("未产生 `.gcda` 的源文件(未计入分母;覆盖率按实际执行文件统计,"
"如需完整口径应将其按 0% 计入):")
for mpath in missing:
md.append(f"- `{mpath}`")
md.append("")
md.append("## 2. 模块明细")
md.append("")
md.append("| 模块 | 文件数 | 可执行行 | 已覆盖行 | 行覆盖率 | 函数 (覆盖/总) | 函数覆盖率 | 分支 (覆盖/总) | 未覆盖行 |")
md.append("|---|---:|---:|---:|---:|---:|---:|---:|---:|")
for name in sorted(modules):
m = modules[name]
lp = 100.0 * m["lines_cov"] / m["lines_total"] if m["lines_total"] else 0.0
fp = 100.0 * m["func_cov"] / m["func_total"] if m["func_total"] else 0.0
bp = 100.0 * m["branch_cov"] / m["branch_total"] if m["branch_total"] else 0.0
md.append(f"| {name} | {m['files']} | {m['lines_total']:,} | {m['lines_cov']:,} | "
f"{lp:.2f}% | {m['func_cov']}/{m['func_total']} | {fp:.2f}% | "
f"{m['branch_cov']}/{m['branch_total']} ({bp:.1f}%) | {m['uncovered']:,} |")
md.append("")
md.append("## 3. 未覆盖热点 top20(按未覆盖行数)")
md.append("")
md.append("| # | 文件 | 模块 | 可执行行 | 已覆盖 | 行覆盖率 | 未覆盖行 | 未覆盖行区间 |")
md.append("|---|---|---|---:|---:|---:|---:|---|")
for i, r in enumerate(hotspot, 1):
md.append(f"| {i} | {r['path']} | {r['mod']} | {r['total']:,} | {r['covered']:,} | "
f"{r['pct']:.2f}% | {r['uncovered']:,} | {fmt_ranges(r['ranges'])} |")
md.append("")
md.append("## 4. 行覆盖率最低文件(可执行行 ≥50)")
md.append("")
md.append("| # | 文件 | 模块 | 行覆盖率 | 可执行行 | 未覆盖行 |")
md.append("|---|---|---|---:|---:|---:|")
for i, r in enumerate(low_cov, 1):
md.append(f"| {i} | {r['path']} | {r['mod']} | {r['pct']:.2f}% | "
f"{r['total']:,} | {r['uncovered']:,} |")
md.append("")
md.append("## 5. 复现命令")
md.append("")
md.append("```powershell")
md.append("# configure(全库插桩;测试不插桩;推荐 RelWithDebInfo:-O2 -g -DNDEBUG)")
md.append("cmake -S . -B build-cov -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo \\")
md.append(" -DVDE_ENABLE_COVERAGE=ON -DBUILD_EXAMPLES=OFF -DBUILD_TESTS=ON \\")
md.append(" -DBUILD_BENCHMARKS=OFF -DFETCHCONTENT_FULLY_DISCONNECTED=ON \\")
md.append(" -DFETCHCONTENT_SOURCE_DIR_GOOGLETEST=$PWD/googletest \\")
md.append(" -DFETCHCONTENT_SOURCE_DIR_EIGEN3=$PWD/eigen3 \\")
md.append(" -DFETCHCONTENT_SOURCE_DIR_JSON=$PWD/json \\")
md.append(" -DFETCHCONTENT_SOURCE_DIR_NLOHMANN_JSON=$PWD/json")
md.append("cmake --build build-cov -j 8")
md.append("# run representative tests (full non-benchmark suite)")
md.append("ctest --test-dir build-cov -E \"Benchmark|Bench\" -j 8 --output-on-failure "
"> build-cov/ctest_cov.log 2>&1")
md.append("# aggregate line/function/branch coverage + hotspots")
md.append("python tools/coverage/coverage_report_full.py --build-dir build-cov \\")
md.append(" --out build-cov/coverage_summary_full.md \\")
md.append(" --json build-cov/coverage_summary_full.json \\")
md.append(" --tests-log build-cov/ctest_cov.log")
md.append("```")
md.append("")
md.append("## 6. 口径说明")
md.append("")
md.append("- 分母 = 全部产品库源文件的可执行行/函数/分支;测试源码不插桩,不计入分母。")
md.append("- 行计数按源文件合并(多 object 时取每行最大计数);分支按(行,分支序号)合并。")
md.append("- 头文件内联实现不在统计内(仅 src/*.c/.cpp);模板实例化可能带来轻微重复,")
md.append(" 但按行/名字聚合后影响可忽略。")
md.append("- 旧 4 库口径(21.76%/26.56%)与本次全库口径的差异主要来自分母扩大(新增")
md.append(" foundation/io/上层模块/capi 等)**以及测试集不同**(旧:363 手工用例;"
"新:全量 ctest),**不能据此断言覆盖率回退或提升**。")
md.append("- 未产生 `.gcda` 的源文件不在分母中;这些文件在本次测试执行中未被任何可执行")
md.append(" 目标链接(如需严格口径,可按 0% 计入,覆盖率会略降)。")
with open(out_md, "w", encoding="utf-8") as fh:
fh.write("\n".join(md))
payload = {
"schema": "vde-coverage/2",
"generated_at": now,
"build_dir": args.build_dir,
"build_type": build_type,
"build_time_sec": args.build_time_sec,
"disk_gb": args.disk_gb,
"coverage_scope": "all product libs (src/**, gcov); tests not instrumented",
"gcov": gcov,
"gcda_count": len(gcda),
"source_files_total": len(all_src),
"source_files_measured": len(per_file),
"source_files_missing_gcda": missing,
"totals": {
"lines_total": total_lines, "lines_covered": total_cov,
"line_pct": line_pct,
"funcs_total": total_funcs, "funcs_covered": total_fcov,
"func_pct": func_pct,
"branches_total": total_br, "branches_covered": total_brcov,
"branch_pct": branch_pct,
},
"modules": modules,
"files": file_records,
"hotspot_top20": hotspot,
"low_coverage_top15": low_cov,
}
with open(out_json, "w", encoding="utf-8") as fh:
json.dump(payload, fh, ensure_ascii=False, indent=1)
print(f"[cov] line {line_pct:.2f}% ({total_cov}/{total_lines}), "
f"func {func_pct:.2f}% ({total_fcov}/{total_funcs}), "
f"branch {branch_pct:.2f}% ({total_brcov}/{total_br})")
print(f"[cov] report: {out_md}")
print(f"[cov] json: {out_json}")
if __name__ == "__main__":
sys.exit(main())