test(iec104): 补回 104 适配层与服务层的主机单测,覆盖率门禁转绿

90cc9a7d 把旧自研协议层(iec104_asdu/iec104_link/iec104_pts)整体退役
时,连带删掉了 test/host/iec104 与 test/host/iec104_serv 两套单测,却
没给留下来的代码补替代测试,也没同步覆盖率基线。结果 test-coverage
门禁(manual 阶段、远端 CI 强制)一直是红的:

  [REGRESS] 总计: 已覆盖行 8848 -> 8052
  [REGRESS] App/task/iec104_serv.c 基线里在测,本次未出现在任何单测编译
            单元里
  [REGRESS] 模块 iec104 / iec104_serv: 基线里有,本次未跑到

两个模块里约 180 行现役代码一行主机单测都没有:104 的 [comm] 段存取
(iec104_comm.c)与现役服务层(iec104_serv.c)。本笔把它们补回来。

新增:
  test/host/iec104_comm/   50 用例,iec104_comm.c 50/50 行
  test/host/iec104_serv/   50 用例,iec104_serv.c 102/102 行
两个套件都 #include 真实生产源(不是测桩),依赖全部走受控 stub。

同时修两个门禁自身的问题:

一、纯 Python 套件被误判为"缺 BUILD"
  iec104_dtu/run_unit_test.py 是独立 oracle/解码器测试,只有一个 unittest
  模块、不编任何 C 文件,天然没有 TestBuild。覆盖率脚本却把它当 FAIL,
  于是基线里被写进一条 ok:false —— 等于把已知失败烤进台账,下次谁跑都
  还是红。改成显式标记 COVERAGE_SKIP:有标记即记入 no_coverage_suites、
  不计入 modules/modules_total,控制台打 SKIP。没有标记又没有 BUILD 的
  运行器仍然 FAIL,严格性不放宽。
  刻意不用"目录里没有 .c 就跳过"这类启发式:那会把真丢了 BUILD 的 C 套件
  静默洗成绿灯,正是这道门禁要拦的东西。

二、该运行器缺 sys.path 引导
  它 from oracle import ... 但没把自己目录加进 sys.path。直接跑能过
  (sys.path[0] 是脚本目录),被 importlib 加载就 No module named
  'oracle' —— 覆盖率脚本走的正是后者。补上后两种加载方式都过。

基线在全绿状态重建:modules_total = modules_ok = 49,没有任何 ok:false
条目,iec104_dtu 移入 no_coverage_suites;连跑两次全量都 RC=0 且汇总行
逐字一致(8204/9185 行、622/679 函数,suites 49/49)。

测试有牙(源变异实测,每次改完按字节还原并校验 sha 一致):
  iec104_comm.c  CA 下限 < 改 <=  / PORT 上限 > 改 >=  / ca_set 不置脏
                -> 三条全部 KILLED
  iec104_serv.c  carry 饱和值减一 / 回绕判定 < 改 <=  / carry += 改 =
                -> 三条全部 KILLED
最后一条边界判据 `carry > SAT - now` 改 `>=` 经穷举 20 万组输入证明是
等价变异(两个分支返回值相同),没有假装能区分它,只在测试注释里写明。

顺带把 s_monotonic 的用例从 6 条扩到 10 条:补 now == last 不算回绕、
饱和后 carry 恰好等于 SAT、以及 carry + now == SAT-1 不被提前饱和。
只断言返回值不看内部状态时,前一版测试对两个真变异是无感的。

验证:pre-commit 9 Passed / 0 Failed;manual 阶段 test-coverage 与
iec104-tcp(13/13 真实 TCP 回环)均 Passed;新旧文件字节体检 BOM=False
CR=0 U+FFFD=0。
This commit is contained in:
2026-11-18 15:18:15 +08:00
parent 84c5a5d92a
commit d8d8fbe081
13 changed files with 1218 additions and 134 deletions
+36 -9
View File
@@ -7,6 +7,7 @@ r"""
1. 发现 test/host/**/run_unit_test.py(与 scripts/ci_local.py 的主机侧纯逻辑单测同一套发现规则),
直接 import 各模块运行器、复用其中声明的 TestBuild(**单一事实源**:include 目录、
桩顺序、测试单元路径都不在这里重复一遍);
0. 模块运行器顶部显式声明 COVERAGE_SKIP 的纯 Python 套件不参与 C 覆盖率(见 load_test_build);
2. 用**与门禁完全相同的编译开关**(unit_test_harness._BASE_FLAGS)另建一份带 /Zi 调试
信息的产物,交给 Microsoft.CodeCoverage.Console.exe 动态插桩运行;
3. 解析 Cobertura XML,只保留**自研生产源码**(App/**、Drivers/BSP/** 的 .c/.h)的行与
@@ -141,6 +142,10 @@ def load_test_build(runner_path, harness):
各运行器都是声明式的:顶层只 import + 构造 TestBuild,真跑在
if __name__ == "__main__" 里,所以按独立模块名 import 是安全的。
纯 Python 套件没有 C 编译单元,天然没有 BUILD;由运行器顶部显式声明
COVERAGE_SKIP = "<原因>" 退出本 C 覆盖率门禁。必须是显式标记,不能靠
"目录里有没有 .c" 猜——那会把真正丢了 BUILD 的 C 套件静默洗成绿灯。
"""
mod_name = "dtu_cov_" + re.sub(r"\W+", "_", Path(runner_path).parent.name)
spec = importlib.util.spec_from_file_location(mod_name, runner_path)
@@ -153,6 +158,9 @@ def load_test_build(runner_path, harness):
return None, "{} 在 import 阶段就调用了 sys.exit()".format(runner_path)
except Exception as exc:
return None, "import {} 失败: {}".format(runner_path, exc)
skip = getattr(mod, "COVERAGE_SKIP", None)
if skip is not None:
return None, ("__SKIP__" + str(skip))
build = getattr(mod, "BUILD", None)
if build is None:
return None, "{} 未声明模块级 BUILD,覆盖率脚本无法复用其编译配置".format(runner_path)
@@ -435,7 +443,7 @@ BASELINE_FILE_FIELDS = ("lines_valid", "lines_covered", "funcs_valid", "funcs_co
"line_rate", "func_rate")
def write_baseline(path, modules, files, totals, tested_sources, untested):
def write_baseline(path, modules, files, totals, tested_sources, untested, no_coverage_suites):
# 基线只留可比字段:missing_lines 每次跑都会漂,进了台账就是无意义的提交抖动
payload = {
"schema": BASELINE_SCHEMA,
@@ -444,6 +452,7 @@ def write_baseline(path, modules, files, totals, tested_sources, untested):
"门禁判据:files[].lines_covered 与 funcs_covered 只增不减,下降即拦提交。",
"totals": totals,
"modules": modules,
"no_coverage_suites": no_coverage_suites,
"files": {rel: {k: v for k, v in rec.items() if k in BASELINE_FILE_FIELDS}
for rel, rec in files.items()},
"tested_sources": tested_sources,
@@ -454,7 +463,7 @@ def write_baseline(path, modules, files, totals, tested_sources, untested):
f.write("\n")
def diff_baseline(baseline, modules, files, totals, full_run):
def diff_baseline(baseline, modules, files, totals, full_run, no_coverage_suites):
"""返回 (回退项, 提示项);回退项非空即门禁失败。"""
regress, notes = [], []
if baseline is None:
@@ -496,6 +505,8 @@ def diff_baseline(baseline, modules, files, totals, full_run):
for name, b in sorted(base_mods.items()):
cur = modules.get(name)
if cur is None:
if name in no_coverage_suites:
continue
if full_run:
regress.append("模块 {}: 基线里有,本次未跑到(运行器缺失 / import 失败?)".format(name))
elif not cur.get("ok"):
@@ -511,6 +522,8 @@ def diff_baseline(baseline, modules, files, totals, full_run):
notes.append("新纳入统计: {}({}/{} 行,{})——确认无误后 --update-baseline 登记".format(
rel, files[rel]["lines_covered"], files[rel]["lines_valid"],
pct(files[rel]["line_rate"])))
for name, reason in sorted(no_coverage_suites.items()):
notes.append("套件 {} 不参与 C 覆盖率:{}".format(name, reason))
if not full_run:
notes.append("本次是 --module 子集运行:并集必然变小,跳过全部覆盖率回退判定"
"(文件消失 / 行减少 / 函数减少 / 总计下降);只保留"
@@ -522,10 +535,13 @@ def diff_baseline(baseline, modules, files, totals, full_run):
# 输出
# --------------------------------------------------------------------------
def print_report(modules, files, totals, untested, generated, notes, regress, verbose):
def print_report(modules, files, totals, untested, generated, notes, regress, verbose,
no_coverage_suites):
print("=== 主机单测覆盖率(口径:docs/测试说明/单元测试/主机单测覆盖率口径.md)===")
print("")
print("--- 各套单测(插桩运行)---")
for name, reason in sorted(no_coverage_suites.items()):
print(" {:<12} SKIP {}".format(name, reason))
for name in sorted(modules):
m = modules[name]
if not m["ok"]:
@@ -571,7 +587,7 @@ def print_report(modules, files, totals, untested, generated, notes, regress, ve
totals["files_tested"], totals["files_untested"]))
def write_markdown(path, modules, files, totals, untested, notes, regress):
def write_markdown(path, modules, files, totals, untested, notes, regress, no_coverage_suites):
"""一次性 Markdown 报告(建议放临时目录,不入库)。
⚠ 行拼装一律走 code() 显式拼接:`.format` 的优先级高于 `+`,写成
@@ -604,6 +620,8 @@ def write_markdown(path, modules, files, totals, untested, notes, regress):
"| 套件 | 结果 | 触及生产文件 | 插桩行 |",
"|---|---|---|---|",
]
for name, reason in sorted(no_coverage_suites.items()):
out.append("| " + code(name) + " | SKIP(" + reason + ") | 0 | 0 |")
for name in sorted(modules):
m = modules[name]
out.append("| " + code(name) + " | "
@@ -704,12 +722,16 @@ def run(args):
total_files = {}
modules = {}
no_coverage_suites = {}
for name, runner in sorted(runners.items()):
build, err = load_test_build(runner, harness)
if err and err.startswith("__SKIP__"):
no_coverage_suites[name] = err[len("__SKIP__"):]
continue
workdir = os.path.join(work_root, name)
shutil.rmtree(workdir, ignore_errors=True)
os.makedirs(workdir, exist_ok=True)
build, err = load_test_build(runner, harness)
if err:
modules[name] = {"ok": False, "reason": err, "files": {}, "lines_total": 0}
print("[FAIL] {}".format(err), file=sys.stderr)
@@ -796,6 +818,7 @@ def run(args):
if args.json:
payload = {"totals": totals, "modules": modules, "files": files,
"no_coverage_suites": no_coverage_suites,
"untested_sources": untested, "generated_excluded": generated}
Path(args.json).write_text(
json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
@@ -805,15 +828,19 @@ def run(args):
if args.build_only:
regress, notes = [], ["--build-only:只编译覆盖率形态(带 PDB),不采集数据"]
else:
regress, notes = diff_baseline(baseline, modules, files, totals, full_run)
regress, notes = diff_baseline(baseline, modules, files, totals, full_run,
no_coverage_suites)
print_report(modules, files, totals, untested, generated, notes, regress, args.verbose)
print_report(modules, files, totals, untested, generated, notes, regress, args.verbose,
no_coverage_suites)
if args.md:
write_markdown(args.md, modules, files, totals, untested, notes, regress)
write_markdown(args.md, modules, files, totals, untested, notes, regress,
no_coverage_suites)
print("[OK] Markdown 报告: {}".format(args.md))
if args.update_baseline:
write_baseline(args.baseline, modules, files, totals, tested, untested)
write_baseline(args.baseline, modules, files, totals, tested, untested,
no_coverage_suites)
print("[OK] 基线已写入 {}".format(os.path.relpath(args.baseline, REPO_ROOT)))
return 0