Files
STM32F4-Base/test/host/common/unit_test_harness.py
T

226 lines
9.1 KiB
Python
Raw 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
# -*- coding: utf-8 -*-
"""unit_test_harness.py - 主机侧单元测试(L0.5)的通用运行器 harness。
职责(**不认识任何具体模块**):
探测本机 MSVC 工具链 -> 拼 INCLUDE/LIB -> 编译测试单元 -> 运行 -> 判定退出码。
被测模块的差异(源文件、桩目录、额外 include、断言汇总行特征)全部由调用方
(各模块自己的 `run_unit_test.py`)传入。
为什么要 harness(2026-10-01 测试架构评审 T-3):
看门狗单测的运行器(`test/host/watchdog/run_unit_test.py`,170 行)把工具链
探测、`INCLUDE`/`LIB` 拼接、GBK 解码、`/wd4819` 抑制、退出码契约**全部写死在
模块目录内**。第二个 L0.5 单测出现时须整段复制——工具链细节一旦修正(新增 VS
版本、SDK 布局变化、编码处理调整)就会发散。抽到这里后,各模块运行器只剩
"声明式"配置。
实现要点(为何不用 vcvars64.bat):
vcvars64.bat 内部调用 reg.exe 探测环境;本机策略禁止 reg.exe。故这里**直接
拼 INCLUDE/LIB 环境变量**并绝对路径调用 cl.exe——只需 3 个已知目录
(MSVC 版本 / Windows SDK include / SDK lib),无副作用、可重复。
退出码契约(各模块运行器统一遵循):
0 = PASS(编译 + 运行成功,且日志满足 summary_marker 要求)
1 = FAIL(有测试用例未通过)
2 = 环境错误(找不到编译器 / 编译失败 / 未产生汇总行)
用法(模块侧 `run_unit_test.py`):
from unit_test_harness import run_host_unit_test, TestBuild
if __name__ == "__main__":
raise SystemExit(run_host_unit_test(TestBuild(
name="Task Watchdog Tests",
src=<测试单元 .c 的绝对路径>,
include_dirs=[<桩目录>, <生产源码目录>],
summary_marker="=== Task Watchdog Tests:",
)))
设计依据:docs/待处理内容.md T-3;docs/测试说明/测试开发标准流程.md §4.2
创建日期:2026-10-01
"""
import glob
import os
import subprocess
import sys
import tempfile
from dataclasses import dataclass, field
# ----------------------------- 工具链探测位置 -----------------------------
# 顺序 = 优先级;`_first` 取每个根目录下最大的版本子目录(新版本优先)。
VS_ROOTS = [
r"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools",
r"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community",
r"C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional",
r"C:\Program Files\Microsoft Visual Studio\2022\BuildTools",
r"C:\Program Files\Microsoft Visual Studio\2022\Community",
r"C:\Program Files\Microsoft Visual Studio\2022\Professional",
r"C:\Program Files\Microsoft Visual Studio\2022\Enterprise",
r"C:\Program Files\Microsoft Visual Studio\2026\BuildTools",
r"C:\Program Files\Microsoft Visual Studio\2026\Community",
# VS2026 的实际安装目录是 "18"(2026-10 台架实测:vswhere → ...\18\Community,
# MSVC 14.51 + SDK 10.0.26100 布局与 2022 一致,cl.exe 路径模式不变);
# 上面两条 "2026" 目录名在本机并不存在,保留以防将来布局回改
r"C:\Program Files\Microsoft Visual Studio\18\BuildTools",
r"C:\Program Files\Microsoft Visual Studio\18\Community",
r"C:\Program Files\Microsoft Visual Studio\18\Professional",
r"C:\Program Files\Microsoft Visual Studio\18\Enterprise",
]
SDK_ROOTS = [r"C:\Program Files (x86)\Windows Kits\10"]
# 编译开关(各模块共用;模块特有开关见 TestBuild.extra_flags)
_BASE_FLAGS = [
"/nologo", "/W4", "/std:c11", "/utf-8",
# C4819("源代码包含不能在当前代码页中表示的字符")是**纯编码诊断**:
# 测试单元确为 UTF-8(带 BOM,已核验),且已显式传 /utf-8,字节解码无误、
# 编译产物正确。但在"只设 INCLUDE/LIB、不调 vcvars"的调用方式下,
# MSVC 的代码页探测会退化为 `代码页(0)` → 恒定误报。
# 测试单元仅主机侧编译(ARMCC 从不编译 test/),故显式屏蔽,保持门禁输出干净。
"/wd4819",
]
@dataclass
class TestBuild:
"""一个主机侧单测的构建描述(声明式;harness 只读这些字段)。"""
name: str # 人类可读名称(打印用),如 "Task Watchdog Tests"
src: str # 测试单元 .c 的绝对路径(内部 #include 生产源)
include_dirs: list = field(default_factory=list) # /I 目录(桩目录需在前,覆盖真实头)
summary_marker: str = "" # 运行输出中必须出现的汇总行前缀;空 = 不校验
extra_flags: list = field(default_factory=list) # 追加的 cl.exe 开关
exe_name: str = "" # 产物 exe 名;空 = 由 name 派生
obj_tag: str = "" # 中间 obj 目录名;空 = 由 name 派生
def resolved_exe(self):
if self.exe_name:
return self.exe_name
tag = "".join(c if c.isalnum() else "_" for c in self.name).strip("_").lower()
return tag + ".exe"
def resolved_obj_tag(self):
if self.obj_tag:
return self.obj_tag
tag = "".join(c if c.isalnum() else "_" for c in self.name).strip("_").lower()
return tag + "_obj"
def _first(pattern):
"""glob 命中里取最大者(版本号目录的字符串序即数值序,前提是位数一致)。"""
hits = sorted(glob.glob(pattern))
return hits[-1] if hits else None
def decode(b):
"""把 subprocess 字节输出解码为字符串。
本机 MSVC 输出为 GBK(代码页 936),测试程序自身输出为 UTF-8;
按 UTF-8 优先、失败回退 GBK 处理。
"""
if isinstance(b, str):
return b
try:
return b.decode("utf-8")
except UnicodeDecodeError:
return b.decode("gbk", errors="replace")
def locate_toolchain():
"""返回 (cl.exe, include_dirs, lib_dirs);找不到返回 (None, [], [])。"""
cl = None
for vs in VS_ROOTS:
c = _first(os.path.join(vs, r"VC\Tools\MSVC\*\bin\Hostx64\x64\cl.exe"))
if c:
cl = c
break
if not cl:
return None, [], []
# cl.exe = <vs>\VC\Tools\MSVC\<ver>\bin\Hostx64\x64\cl.exe
msvc_ver_dir = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.dirname(cl)))) # -> ...\MSVC\<ver>
inc = [os.path.join(msvc_ver_dir, "include")]
lib = [os.path.join(msvc_ver_dir, "lib", "x64")]
for sdk in SDK_ROOTS:
sdk_inc = _first(os.path.join(sdk, r"Include\*"))
sdk_lib = _first(os.path.join(sdk, r"Lib\*"))
if sdk_inc:
inc += [
os.path.join(sdk_inc, "ucrt"),
os.path.join(sdk_inc, "shared"),
os.path.join(sdk_inc, "um"),
]
if sdk_lib:
lib += [
os.path.join(sdk_lib, "ucrt", "x64"),
os.path.join(sdk_lib, "um", "x64"),
]
return cl, inc, lib
def build_and_run(build, out=None):
"""编译并运行一个测试单元。返回退出码 0/1/2(见模块 docstring 契约)。"""
if out is None:
out = sys.stdout
err = sys.stderr
cl, inc, lib = locate_toolchain()
if not cl:
print("[ENV] 找不到 MSVC cl.exe(需要 VS2019/2022/2026 的 C++ 工具链)", file=err)
return 2
tmp = tempfile.gettempdir()
objdir = os.path.join(tmp, build.resolved_obj_tag())
os.makedirs(objdir, exist_ok=True)
exe = os.path.join(tmp, build.resolved_exe())
env = dict(os.environ)
env["INCLUDE"] = os.pathsep.join(inc)
env["LIB"] = os.pathsep.join(lib)
env["PATH"] = os.path.dirname(cl) + os.pathsep + env.get("PATH", "")
cmd = [cl] + _BASE_FLAGS
for d in build.include_dirs:
cmd += ["/I", d]
cmd += list(build.extra_flags)
cmd += [build.src, "/Fe:" + exe, "/Fo:" + objdir + os.sep]
print("=== 编译并运行 {} ===".format(build.name), file=out)
cp = subprocess.run(cmd, env=env, capture_output=True)
cout, cerr = decode(cp.stdout), decode(cp.stderr)
if cout:
out.write(cout)
if cerr:
err.write(cerr)
if cp.returncode != 0:
print("[ENV] 编译失败", file=err)
return 2
run = subprocess.run([exe], env=env, capture_output=True)
rout = decode(run.stdout)
out.write(rout)
rerr = decode(run.stderr)
if rerr:
err.write(rerr)
if build.summary_marker and build.summary_marker not in rout:
print("[ENV] 未产生测试汇总行(找不到 {!r})".format(build.summary_marker), file=err)
return 2
if run.returncode == 0:
print("[OK] 单元测试全部通过", file=out)
return 0
print("[FAIL] 有测试用例未通过", file=err)
return 1
def run_host_unit_test(build):
"""模块侧入口薄封装:固定控制台 UTF-8 后调用 build_and_run。"""
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
return build_and_run(build)