selftest_calib.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // portcv 标定记录自检(P0-5)—— 覆盖"记录能不能被 C++ 正确判定"这条链路。
  2. //
  3. // 运行:
  4. // ctest --test-dir build -R portcv_calib_selftest --output-on-failure
  5. // ./build/portcv_calib_selftest
  6. //
  7. // 覆盖(与实现文件对应):
  8. // [1] sha256:FIPS 180-4 标准向量(空串 / "abc" / 56 字节句子)
  9. // [2] canonical JSON:键排序、int/float 区分、浮点渲染、控制符转义、顶层 sha256 剔除
  10. // —— 断言值与 `json.dumps(..., ensure_ascii=False, sort_keys=True,
  11. // separators=(",", ":"))` 逐字相同(黄金向量由 Python 生成)
  12. // [3] 跨语言黄金记录:Python `seal()` 封存的记录 → C++ `verify_hash()` 必须为真;
  13. // 改一个数必须为假(这条断言就是"两侧口径一致"的证据)
  14. // [4] ISO-8601:时区 / Z / 纯日期 / 小数秒 / 非法值
  15. // [5] 判定:过期 / 未复核 / 哈希不符 / 文件缺失 / JSON 损坏 / 字段缺失 /
  16. // 比例尺漂移 / 箱高漂移 / 手工 stale / 未来日期不算过期
  17. // [6] 文件 I/O:真实读盘(写临时记录 → evaluate_calibration → 删除)
  18. // [7] 配置绑定:`calibration.*` 键 → CalibrationConfig;类型错/越界报错并指出键名;
  19. // 默认值与 Python `DEFAULTS` 同值
  20. //
  21. // 说明:断言描述用 ASCII(GBK 控制台下中文会乱码,影响现场排错),源码注释保持中文。
  22. // 记录文本里的中文一律写成 JSON `\uXXXX` 转义:源码保持纯 ASCII,编译器的
  23. // 源码/执行字符集怎么设都不会影响哈希结果(哈希只认 UTF-8 字节)。
  24. #include <cstdio>
  25. #include <cstdlib>
  26. #include <cstring>
  27. #include <string>
  28. #include <vector>
  29. #include "portcv/app_config.hpp"
  30. #include "portcv/calibration.hpp"
  31. #include "portcv/json_lite.hpp"
  32. #include "portcv/sha256.hpp"
  33. namespace {
  34. int g_pass = 0;
  35. int g_fail = 0;
  36. void check(bool ok, const std::string& what) {
  37. if (ok) {
  38. ++g_pass;
  39. std::printf(" [OK] %s\n", what.c_str());
  40. } else {
  41. ++g_fail;
  42. std::printf(" [FAIL] %s\n", what.c_str());
  43. }
  44. }
  45. void check_eq(long long got, long long want, const std::string& what) {
  46. if (got == want) {
  47. ++g_pass;
  48. std::printf(" [OK] %s (=%lld)\n", what.c_str(), got);
  49. } else {
  50. ++g_fail;
  51. std::printf(" [FAIL] %s: got=%lld want=%lld\n", what.c_str(), got, want);
  52. }
  53. }
  54. void check_str(const std::string& got, const std::string& want, const std::string& what) {
  55. if (got == want) {
  56. ++g_pass;
  57. std::printf(" [OK] %s (%s)\n", what.c_str(), got.c_str());
  58. } else {
  59. ++g_fail;
  60. std::printf(" [FAIL] %s: got=%s want=%s\n", what.c_str(), got.c_str(), want.c_str());
  61. }
  62. }
  63. bool has_reason(const portcv::CalibrationStatus& s, const char* reason) {
  64. for (const std::string& r : s.reasons) {
  65. if (r == reason) { return true; }
  66. }
  67. return false;
  68. }
  69. /// 2026-10-26T10:00:00+08:00 的 UTC epoch 秒(= 2026-10-26T02:00:00Z)。
  70. const long long kCalibratedAt = 1792980000LL;
  71. const long long kDay = 86400LL;
  72. // ---------------------------------------------------------------- 黄金向量
  73. // 由 Python 生成(`portcv.calibration.seal()`):记录文本 + 期望 sha256。
  74. // 只要两侧对"整数/浮点渲染、键排序、UTF-8 输出"有任何一处不一致,这里就会失败。
  75. const char* kGoldenRecord1 =
  76. "{"
  77. "\"schema\":\"portcv.calib/1\","
  78. "\"site\":\"CT01\","
  79. "\"camera_id\":\"front\","
  80. "\"calibrated_at\":\"2026-10-26T10:00:00+08:00\","
  81. "\"reviewer\":\"\\u5f20\\u5de5\","
  82. "\"method\":\"box_vertical_scale\","
  83. "\"px_per_m\":115.6,"
  84. "\"box_height_m\":2.591,"
  85. "\"intrinsics\":{\"fx\":1200.0,\"fy\":1200.0,\"cx\":960.0,\"cy\":540.0,\"dist\":[]},"
  86. "\"extrinsics\":{\"height_m\":6.5,\"pitch_deg\":-8.0,\"yaw_deg\":2.0},"
  87. "\"roi\":[[0.03,0.1],[0.97,0.1],[0.97,0.99],[0.03,0.99]],"
  88. "\"sha256\":\"735ab9e8f9e51abe32b17f0abe1976dd35b4a3d3a14aee5ad43674104211df82\""
  89. "}";
  90. const char* kGoldenHash1 = "735ab9e8f9e51abe32b17f0abe1976dd35b4a3d3a14aee5ad43674104211df82";
  91. /// 边界类型:整数 / 浮点 / 指数 / 控制符 / 布尔 / null / 非 ASCII 与非 ASCII 键。
  92. const char* kGoldenRecord2 =
  93. "{"
  94. "\"site\":\"S\","
  95. "\"camera_id\":\"c\","
  96. "\"calibrated_at\":\"2026-01-02\","
  97. "\"reviewer\":\"a\\nb\\tc\\\"d\\\\e\","
  98. "\"n_int\":180,"
  99. "\"n_float\":180.0,"
  100. "\"big\":1e+16,"
  101. "\"mid\":1000000000000000.0,"
  102. "\"small\":1e-05,"
  103. "\"tiny\":0.0001,"
  104. "\"neg_zero\":-0.0,"
  105. "\"prec\":1.2345678901234568e-300,"
  106. "\"flag\":true,"
  107. "\"none\":null,"
  108. "\"text\":\"\\u4e2d\\u6587 \\u00e9\","
  109. "\"\\u4e2d\":1,"
  110. "\"a\":2,"
  111. "\"arr\":[1,2.5,[]]"
  112. "}";
  113. const char* kGoldenHash2 = "b46564ddae4441f475f244a93e0be1bde69fc14bd253d926852a3f4c987117b7";
  114. portcv::json::Value parse_or_null(const std::string& text) {
  115. std::string error;
  116. const portcv::json::Value v = portcv::json::parse(text, &error);
  117. if (!error.empty()) { std::printf(" (parse error: %s)\n", error.c_str()); }
  118. return v;
  119. }
  120. void test_sha256() {
  121. std::printf("[1] sha256 (FIPS 180-4)\n");
  122. check_str(portcv::sha256_hex(""),
  123. "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
  124. "empty string");
  125. check_str(portcv::sha256_hex("abc"),
  126. "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "\"abc\"");
  127. check_str(portcv::sha256_hex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
  128. "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
  129. "56-byte sentence (2 blocks)");
  130. check_eq(static_cast<long long>(portcv::sha256_hex("abc").size()), 64, "hexdigest length");
  131. }
  132. void test_canonical() {
  133. std::printf("[2] canonical JSON == json.dumps(ensure_ascii=False, sort_keys=True, separators=(',',':'))\n");
  134. // 键排序(书写顺序打乱)
  135. check_str(portcv::canonical_json(parse_or_null("{\"b\":1,\"a\":\"x\"}")), "{\"a\":\"x\",\"b\":1}",
  136. "sort_keys");
  137. // 整数/浮点区分(Python: 180 vs 180.0)
  138. check_str(portcv::canonical_json(parse_or_null("{\"v\":180}")), "{\"v\":180}", "int literal stays int");
  139. check_str(portcv::canonical_json(parse_or_null("{\"v\":180.0}")), "{\"v\":180.0}",
  140. "float literal keeps .0");
  141. // 浮点渲染(Python repr 口径:1e15 定点、1e16 科学计数、指数至少两位)
  142. check_str(portcv::canonical_json(parse_or_null("{\"v\":1e15}")), "{\"v\":1000000000000000.0}",
  143. "1e15 -> fixed form");
  144. check_str(portcv::canonical_json(parse_or_null("{\"v\":1e16}")), "{\"v\":1e+16}", "1e16 -> exponent form");
  145. check_str(portcv::canonical_json(parse_or_null("{\"v\":0.0001}")), "{\"v\":0.0001}", "1e-4 stays fixed");
  146. check_str(portcv::canonical_json(parse_or_null("{\"v\":1e-5}")), "{\"v\":1e-05}", "1e-5 -> 2-digit exponent");
  147. check_str(portcv::canonical_json(parse_or_null("{\"v\":-0.0}")), "{\"v\":-0.0}", "negative zero");
  148. check_str(portcv::canonical_json(parse_or_null("{\"v\":5e-324}")), "{\"v\":5e-324}", "denormal min");
  149. check_str(portcv::canonical_json(parse_or_null("{\"v\":1.7976931348623157e308}")),
  150. "{\"v\":1.7976931348623157e+308}", "double max");
  151. // 整数前导 0 / "-0"
  152. check_str(portcv::canonical_json(parse_or_null("{\"v\":-0}")), "{\"v\":0}", "int -0 -> 0");
  153. // 字符串转义(控制符 + 引号 + 反斜杠;非 ASCII 原样)
  154. check_str(portcv::canonical_json(parse_or_null("{\"v\":\"a\\nb\\tc\\\"d\\\\e\"}")),
  155. "{\"v\":\"a\\nb\\tc\\\"d\\\\e\"}", "control/quote/backslash escapes");
  156. check_str(portcv::canonical_json(parse_or_null("{\"v\":\"\\u0001\"}")), "{\"v\":\"\\u0001\"}",
  157. "other control chars -> \\u00XX");
  158. // 顶层 sha256 剔除、嵌套 sha256 保留
  159. check_str(portcv::canonical_json(parse_or_null("{\"sha256\":\"dead\",\"a\":1}")), "{\"a\":1}",
  160. "top-level sha256 dropped");
  161. check_str(portcv::canonical_json(parse_or_null("{\"a\":{\"sha256\":\"x\"}}")),
  162. "{\"a\":{\"sha256\":\"x\"}}", "nested sha256 kept");
  163. // 数组/空容器
  164. check_str(portcv::canonical_json(parse_or_null("{\"a\":[],\"b\":{}}")), "{\"a\":[],\"b\":{}}",
  165. "empty containers");
  166. // 空对象
  167. check_str(portcv::canonical_json(parse_or_null("{}")), "{}", "empty object");
  168. }
  169. void test_golden_records() {
  170. std::printf("[3] cross-language golden records (sealed by Python)\n");
  171. const portcv::json::Value rec1 = parse_or_null(kGoldenRecord1);
  172. check(rec1.is_object(), "golden record 1 parses");
  173. check_str(portcv::compute_hash(rec1), kGoldenHash1, "record 1 sha256 matches Python");
  174. check(portcv::verify_hash(rec1), "record 1 hash verifies");
  175. // 改一个数(其余字段与哈希原样保留)→ 必须校验失败
  176. std::string tampered(kGoldenRecord1);
  177. const std::size_t pos = tampered.find("\"px_per_m\":115.6");
  178. if (pos != std::string::npos) { tampered.replace(pos, 16, "\"px_per_m\":120.0"); }
  179. const portcv::json::Value bad = parse_or_null(tampered);
  180. check(bad.is_object(), "tampered record parses");
  181. check(!portcv::verify_hash(bad), "tampered px_per_m fails verification");
  182. check_str(portcv::compute_hash(bad) != kGoldenHash1 ? "different" : "same", "different",
  183. "tampered hash differs");
  184. const portcv::json::Value rec2 = parse_or_null(kGoldenRecord2);
  185. check(rec2.is_object(), "golden record 2 parses (no sha256 field)");
  186. check_str(portcv::compute_hash(rec2), kGoldenHash2, "record 2 sha256 matches Python (int/float/unicode)");
  187. check(!portcv::verify_hash(rec2), "record without sha256 does not verify");
  188. }
  189. void test_iso8601() {
  190. std::printf("[4] ISO-8601 parsing\n");
  191. long long t1 = 0;
  192. long long t2 = 0;
  193. check(portcv::parse_iso8601("2026-10-26T10:00:00+08:00", &t1), "parse +08:00 form");
  194. check(portcv::parse_iso8601("2026-10-26T02:00:00Z", &t2), "parse Z form");
  195. check_eq(t1, t2, "same instant in different offsets");
  196. check_eq(t1, kCalibratedAt, "epoch value as expected");
  197. check(portcv::parse_iso8601("2026-10-26", &t1), "parse date-only form");
  198. check_eq(t1, kCalibratedAt - 2 * 3600, "date-only == midnight UTC");
  199. check(portcv::parse_iso8601("1970-01-01T00:00:00Z", &t1), "parse epoch origin");
  200. check_eq(t1, 0, "epoch origin is 0");
  201. check(portcv::parse_iso8601("2026-10-26T10:00:00.987+08:00", &t1), "parse fractional seconds");
  202. check_eq(t1, kCalibratedAt, "fraction is truncated to whole seconds");
  203. check(!portcv::parse_iso8601("2026-13-01T00:00:00Z", &t1), "reject month 13");
  204. check(!portcv::parse_iso8601("", &t1), "reject empty");
  205. check(!portcv::parse_iso8601("not-a-date", &t1), "reject garbage");
  206. check(!portcv::parse_iso8601("2026-10-26T25:00:00Z", &t1), "reject hour 25");
  207. check(!portcv::parse_iso8601("2026-10-26T02:00:00Zjunk", &t1), "reject trailing garbage");
  208. }
  209. /// 造一份"自洽封存"的记录(哈希由本实现算,只用于验证**非哈希**规则)。
  210. portcv::json::Value make_record(const std::string& reviewer, const std::string& calibrated_at,
  211. double px_per_m, double box_height_m) {
  212. using portcv::json::Type;
  213. using portcv::json::Value;
  214. Value record;
  215. record.type = Type::Object;
  216. const auto add_text = [&record](const char* key, const std::string& value) {
  217. Value v;
  218. v.type = Type::String;
  219. v.text = value;
  220. record.members.push_back({key, v});
  221. };
  222. const auto add_number = [&record](const char* key, double value) {
  223. Value v;
  224. v.type = Type::Number;
  225. v.number = value;
  226. record.members.push_back({key, v});
  227. };
  228. add_text("site", "CT01");
  229. add_text("camera_id", "front");
  230. add_text("calibrated_at", calibrated_at);
  231. add_text("reviewer", reviewer);
  232. add_number("px_per_m", px_per_m);
  233. add_number("box_height_m", box_height_m);
  234. Value hash;
  235. hash.type = Type::String;
  236. hash.text = portcv::compute_hash(record);
  237. record.members.push_back({"sha256", hash});
  238. return record;
  239. }
  240. portcv::CalibrationInputs inputs_of(const portcv::json::Value& record, double run_px, double run_box) {
  241. portcv::CalibrationInputs in;
  242. in.file_exists = true;
  243. in.json_ok = true;
  244. in.record = record;
  245. in.run_px_per_m = run_px;
  246. in.run_box_height_m = run_box;
  247. return in;
  248. }
  249. void test_evaluate() {
  250. std::printf("[5] evaluate (expiry / review / hash / drift / manual)\n");
  251. portcv::CalibrationConfig cfg; // 默认:180 天 / 10% / 0.02 m / hold_on_stale=true
  252. cfg.record = "configs/calib/ct01-front.json"; // 纯函数不读盘:路径只用于日志/原因
  253. const portcv::json::Value fresh = make_record("zhang", "2026-10-26T02:00:00Z", 115.6, 2.591);
  254. const long long now = kCalibratedAt + 10 * kDay;
  255. portcv::CalibrationStatus s =
  256. portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.591), now);
  257. check(!s.stale, "fresh reviewed record is usable");
  258. check(s.hash_ok, "hash_ok reported");
  259. check(s.has_record, "record parsed");
  260. check_str(s.record.site, "CT01", "site parsed");
  261. check_str(s.record.camera_id, "front", "camera_id parsed");
  262. check(s.hold, "hold_on_stale defaults to true");
  263. check(s.has_age && s.age_days > 9.9 && s.age_days < 10.1, "age_days ~ 10");
  264. check(s.reasons_text().empty(), "no reasons when usable");
  265. // 过期:超过 max_age_days
  266. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.591),
  267. kCalibratedAt + 200 * kDay);
  268. check(s.stale && has_reason(s, "expired"), "expired -> reasons=expired");
  269. cfg.max_age_days = 0.0; // 0 = 关闭过期判定
  270. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.591),
  271. kCalibratedAt + 200 * kDay);
  272. check(!s.stale, "max_age_days=0 disables expiry");
  273. cfg.max_age_days = 180.0;
  274. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.591), kCalibratedAt - kDay);
  275. check(!s.stale, "future calibrated_at is not expired");
  276. // 未复核
  277. const portcv::json::Value unreviewed = make_record("", "2026-10-26T02:00:00Z", 115.6, 2.591);
  278. s = portcv::evaluate_calibration_values(cfg, inputs_of(unreviewed, 115.6, 2.591), now);
  279. check(s.stale && has_reason(s, "unreviewed"), "empty reviewer -> reasons=unreviewed");
  280. // 哈希不符(改了数但没重新封存)
  281. portcv::json::Value tampered = make_record("zhang", "2026-10-26T02:00:00Z", 115.6, 2.591);
  282. for (auto& member : tampered.members) {
  283. if (member.first == "px_per_m") { member.second.number = 120.0; }
  284. }
  285. s = portcv::evaluate_calibration_values(cfg, inputs_of(tampered, 120.0, 2.591), now);
  286. check(s.stale && has_reason(s, "hash_mismatch"), "tampered record -> reasons=hash_mismatch");
  287. }
  288. void test_evaluate_io_edges() {
  289. portcv::CalibrationConfig cfg;
  290. cfg.record = "configs/calib/ct01-front.json"; // 纯函数不读盘
  291. const portcv::json::Value fresh = make_record("zhang", "2026-10-26T02:00:00Z", 115.6, 2.591);
  292. const long long now = kCalibratedAt + 10 * kDay;
  293. // 文件缺失 / JSON 坏 / 记录不是对象 / 缺必填字段
  294. portcv::CalibrationInputs in = inputs_of(fresh, 115.6, 2.591);
  295. in.file_exists = false;
  296. portcv::CalibrationStatus s = portcv::evaluate_calibration_values(cfg, in, now);
  297. check(s.stale && has_reason(s, "missing") && !s.hash_ok, "missing file -> reasons=missing");
  298. in = inputs_of(fresh, 115.6, 2.591);
  299. in.json_ok = false;
  300. s = portcv::evaluate_calibration_values(cfg, in, now);
  301. check(s.stale && has_reason(s, "invalid:json"), "bad json -> reasons=invalid:json");
  302. in = inputs_of(fresh, 115.6, 2.591);
  303. in.record = portcv::json::Value(); // Null
  304. s = portcv::evaluate_calibration_values(cfg, in, now);
  305. check(s.stale && has_reason(s, "invalid:json"), "non-object record -> reasons=invalid:json");
  306. portcv::json::Value partial;
  307. partial.type = portcv::json::Type::Object;
  308. s = portcv::evaluate_calibration_values(cfg, inputs_of(partial, 115.6, 2.591), now);
  309. check(s.stale && has_reason(s, "invalid:fields"), "missing required fields -> invalid:fields");
  310. // 比例尺漂移(相对容差 10%)
  311. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 150.0, 2.591), now);
  312. check(s.stale && has_reason(s, "px_per_m_drift"), "px_per_m 150 vs 115.6 -> drift");
  313. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 120.0, 2.591), now);
  314. check(!s.stale, "px_per_m 120 vs 115.6 (3.8%) -> within tolerance");
  315. // 箱高漂移(绝对容差 0.02 m)
  316. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.70), now);
  317. check(s.stale && has_reason(s, "box_height_drift"), "box_height 2.70 vs 2.591 -> drift");
  318. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.60), now);
  319. check(!s.stale, "box_height 2.60 vs 2.591 -> within tolerance");
  320. // 运行期值为 0(未配置)时不判漂移
  321. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 0.0, 0.0), now);
  322. check(!s.stale, "run px_per_m=0 (unset) skips drift check");
  323. // 手工 stale(有记录时追加一条;无记录时单独成立)
  324. cfg.stale = true;
  325. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.591), now);
  326. check(s.stale && has_reason(s, "manual_stale"), "manual stale flag raises CALIB_STALE");
  327. cfg.stale = false;
  328. cfg.record.clear(); // 未配记录
  329. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.591), now);
  330. check(!s.stale && !s.has_record, "no record configured -> no judgement");
  331. cfg.stale = true;
  332. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 115.6, 2.591), now);
  333. check(s.stale && s.reasons_text() == "manual_stale", "manual stale without record");
  334. cfg.stale = false;
  335. cfg.record = "configs/calib/ct01-front.json"; // 恢复记录,供 hold 用例使用
  336. // hold_on_stale=false:只告警,不清 RESULT_VALID/STABLE
  337. cfg.hold_on_stale = false;
  338. s = portcv::evaluate_calibration_values(cfg, inputs_of(fresh, 150.0, 2.591), now);
  339. check(s.stale && !s.hold, "hold_on_stale=false is carried into status");
  340. }
  341. void test_file_io() {
  342. std::printf("[6] file I/O (real record on disk)\n");
  343. const char* path = "portcv_calib_selftest_tmp.json";
  344. std::FILE* fh = std::fopen(path, "wb");
  345. check(fh != nullptr, "temp record created");
  346. if (fh != nullptr) {
  347. std::fwrite(kGoldenRecord1, 1, std::strlen(kGoldenRecord1), fh);
  348. std::fclose(fh);
  349. }
  350. portcv::CalibrationConfig cfg;
  351. cfg.record = path;
  352. const long long now = kCalibratedAt + 3 * kDay;
  353. const portcv::CalibrationStatus s = portcv::evaluate_calibration(cfg, 115.6, 2.591, now);
  354. check(!s.stale, "record read from disk is usable");
  355. check(s.hash_ok, "disk record hash ok (same bytes as Python-sealed file)");
  356. check(s.has_age && s.age_days > 2.9 && s.age_days < 3.1, "disk record age ~ 3 days");
  357. check_str(s.record.calibrated_at, "2026-10-26T10:00:00+08:00", "calibrated_at kept verbatim");
  358. const std::string line = portcv::calibration_status_line(s);
  359. check(line.find("stale=no") != std::string::npos, "status line reports stale=no");
  360. check(line.find("hash=ok") != std::string::npos, "status line reports hash=ok");
  361. check(line.find("CT01") != std::string::npos, "status line shows site");
  362. std::remove(path);
  363. cfg.record = "definitely_missing_calib_record.json";
  364. const portcv::CalibrationStatus missing = portcv::evaluate_calibration(cfg, 115.6, 2.591, now);
  365. check(missing.stale && has_reason(missing, "missing"), "missing file on disk -> reasons=missing");
  366. check(!missing.hash_ok && !missing.has_record, "missing file: no hash / no record");
  367. cfg.record.clear();
  368. const portcv::CalibrationStatus none = portcv::evaluate_calibration(cfg, 0.0, 0.0, now);
  369. check(!none.stale, "empty record path is not stale");
  370. check(portcv::calibration_status_line(none).find("(未配置)") != std::string::npos,
  371. "status line marks unconfigured record");
  372. }
  373. void test_config() {
  374. std::printf("[7] calibration.* config binding\n");
  375. portcv::AppConfig cfg;
  376. std::string error;
  377. check(portcv::app_config_from_text("{\"calibration\":{}}", &cfg, &error), "empty block ok");
  378. check(cfg.calibration.max_age_days == 180.0, "default max_age_days=180 (same as Python DEFAULTS)");
  379. check(cfg.calibration.px_per_m_tolerance == 0.10, "default px_per_m_tolerance=0.10");
  380. check(cfg.calibration.box_height_tolerance_m == 0.02, "default box_height_tolerance_m=0.02");
  381. check(cfg.calibration.hold_on_stale, "default hold_on_stale=true");
  382. check(cfg.calibration.record.empty() && !cfg.calibration.stale, "default record empty / stale=false");
  383. const char* text =
  384. "{\"calibration\":{\"record\":\"configs/calib/ct01-front.json\",\"stale\":true,"
  385. "\"max_age_days\":90,\"px_per_m_tolerance\":0.05,"
  386. "\"box_height_tolerance_m\":0.01,\"hold_on_stale\":false}}";
  387. check(portcv::app_config_from_text(text, &cfg, &error), "full calibration block parses");
  388. check_str(cfg.calibration.record, "configs/calib/ct01-front.json", "record bound");
  389. check(cfg.calibration.stale, "stale bound");
  390. check(cfg.calibration.max_age_days == 90.0, "max_age_days bound");
  391. check(cfg.calibration.px_per_m_tolerance == 0.05, "px_per_m_tolerance bound");
  392. check(cfg.calibration.box_height_tolerance_m == 0.01, "box_height_tolerance_m bound");
  393. check(!cfg.calibration.hold_on_stale, "hold_on_stale bound");
  394. error.clear();
  395. check(!portcv::app_config_from_text("{\"calibration\":{\"max_age_days\":\"180\"}}", &cfg, &error),
  396. "string max_age_days is rejected");
  397. check(error.find("calibration.max_age_days") != std::string::npos, "error names the offending key");
  398. error.clear();
  399. check(!portcv::app_config_from_text("{\"calibration\":{\"px_per_m_tolerance\":-1}}", &cfg, &error),
  400. "negative tolerance rejected");
  401. error.clear();
  402. check(!portcv::app_config_from_text("{\"calibration\":{\"box_height_tolerance_m\":9}}", &cfg, &error),
  403. "absurd box tolerance rejected");
  404. error.clear();
  405. check(!portcv::app_config_from_text("{\"calibration\":{\"stale\":\"yes\"}}", &cfg, &error),
  406. "string stale is rejected");
  407. const std::string line = portcv::describe_app_config(cfg);
  408. check(line.find("calibration.record=") != std::string::npos, "describe shows calibration.record");
  409. check(line.find("hold_on_stale=") != std::string::npos, "describe shows hold_on_stale");
  410. check(line.find("max_age_days=") != std::string::npos, "describe shows max_age_days");
  411. }
  412. } // namespace
  413. int main() {
  414. std::printf("portcv 标定记录自检(P0-5):记录 / 哈希 / 过期 / 漂移 / 配置\n");
  415. test_sha256();
  416. test_canonical();
  417. test_golden_records();
  418. test_iso8601();
  419. test_evaluate();
  420. test_evaluate_io_edges();
  421. test_file_io();
  422. test_config();
  423. std::printf("\n结果: %d 通过 / %d 失败\n", g_pass, g_fail);
  424. if (g_fail == 0) { std::printf("全部通过(ctest 判据:退出码 0)。\n"); }
  425. return g_fail == 0 ? 0 : 1;
  426. }