Files
ViewDesignEngine/tests/infra/test_coverage_profile_config.cpp

490 lines
18 KiB
C++
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.
// W60(KCP-1.0 Wave 10):core-plus-v2 覆盖率 profile / baseline 配置守卫。
//
// 背景:W54 新增 4 个 coverage 补测目标(test_cov_wave9_ssi/_heal/
// _generative/_mesh,共 49 个 gtest 用例)但刻意未写入 profile,避免既有
// baseline 出现 strict-baseline 目标集漂移;W60 把 4 个目标纳入
// `core-plus-v2`、重测并 --update-baseline、line_pct_gate 52.0 → 53.0。
//
// 本测试把该契约固化为 unmerged hermetic 单元测试(只读仓库内
// tools/coverage/*.json,不链接任何几何/生产语义),防止后续 wave 再次
// 出现「profile 加了目标、baseline 没刷新」的漂移回归:
// 1. profile 含 W54 四个新目标;
// 2. line_pct_gate >= 53.0 且不高于 line_pct_goal;
// 3. baseline entry 的目标集与 profile 目标集完全一致(漂移守卫);
// 4. baseline 实测 line_pct 高于 gate(gate 永不高于基线实测);
// 5. baseline entry 自洽(target_count / tests / covered 统计);
// 6. 两份配置 schema_version 均为 1。
//
// 依赖:仅标准库(自带极简 JSON 解析,见下),不引入第三方库。
#include <gtest/gtest.h>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
namespace coverage_cfg {
namespace {
namespace fs = std::filesystem;
// ── 极简 JSON 解析(仅覆盖 tools/coverage/*.json 用到的语法)──────────
struct Json {
enum class Kind { Null, Bool, Number, String, Array, Object };
Kind kind = Kind::Null;
bool b = false;
double num = 0.0;
std::string str;
std::vector<Json> arr;
std::map<std::string, Json> obj;
bool is_object() const { return kind == Kind::Object; }
bool is_array() const { return kind == Kind::Array; }
bool is_number() const { return kind == Kind::Number; }
bool is_string() const { return kind == Kind::String; }
// 取对象成员;不存在返回 nullptr。
const Json* find(const std::string& key) const {
if (!is_object()) return nullptr;
auto it = obj.find(key);
return it == obj.end() ? nullptr : &it->second;
}
};
class JsonParser {
public:
explicit JsonParser(const std::string& text) : s_(text) {}
bool parse(Json& out) {
skip_ws();
if (!parse_value(out)) return false;
skip_ws();
return pos_ == s_.size();
}
const std::string& error() const { return error_; }
private:
static void utf8_append(std::string& out, unsigned cp) {
if (cp <= 0x7F) {
out.push_back(static_cast<char>(cp));
} else if (cp <= 0x7FF) {
out.push_back(static_cast<char>(0xC0 | (cp >> 6)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
} else if (cp <= 0xFFFF) {
out.push_back(static_cast<char>(0xE0 | (cp >> 12)));
out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
} else {
out.push_back(static_cast<char>(0xF0 | (cp >> 18)));
out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
}
}
void skip_ws() {
while (pos_ < s_.size()) {
char c = s_[pos_];
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
++pos_;
} else {
break;
}
}
}
bool fail(const std::string& why) {
if (error_.empty()) {
std::ostringstream oss;
oss << why << " @offset " << pos_;
error_ = oss.str();
}
return false;
}
bool parse_value(Json& out) {
if (pos_ >= s_.size()) return fail("unexpected end of input");
char c = s_[pos_];
switch (c) {
case '{': return parse_object(out);
case '[': return parse_array(out);
case '"': return parse_string(out);
case 't':
case 'f': return parse_bool(out);
case 'n': return parse_null(out);
default: return parse_number(out);
}
}
bool parse_null(Json& out) {
if (s_.compare(pos_, 4, "null") != 0) return fail("invalid literal");
pos_ += 4;
out.kind = Json::Kind::Null;
return true;
}
bool parse_bool(Json& out) {
if (s_.compare(pos_, 4, "true") == 0) {
pos_ += 4;
out.kind = Json::Kind::Bool;
out.b = true;
return true;
}
if (s_.compare(pos_, 5, "false") == 0) {
pos_ += 5;
out.kind = Json::Kind::Bool;
out.b = false;
return true;
}
return fail("invalid bool");
}
bool parse_number(Json& out) {
const char* begin = s_.c_str() + pos_;
char* end = nullptr;
double v = std::strtod(begin, &end);
if (end == begin) return fail("invalid number");
pos_ += static_cast<size_t>(end - begin);
out.kind = Json::Kind::Number;
out.num = v;
return true;
}
bool parse_string(Json& out) {
if (pos_ >= s_.size() || s_[pos_] != '"') return fail("expected string");
++pos_;
out.kind = Json::Kind::String;
out.str.clear();
while (pos_ < s_.size()) {
unsigned char c = static_cast<unsigned char>(s_[pos_]);
if (c == '"') {
++pos_;
return true;
}
if (c == '\\') {
++pos_;
if (pos_ >= s_.size()) return fail("escape at end");
char e = s_[pos_++];
switch (e) {
case '"': out.str.push_back('"'); break;
case '\\': out.str.push_back('\\'); break;
case '/': out.str.push_back('/'); break;
case 'b': out.str.push_back('\b'); break;
case 'f': out.str.push_back('\f'); break;
case 'n': out.str.push_back('\n'); break;
case 'r': out.str.push_back('\r'); break;
case 't': out.str.push_back('\t'); break;
case 'u': {
if (pos_ + 4 > s_.size()) return fail("truncated \\u");
unsigned cp = 0;
for (int i = 0; i < 4; ++i) {
char h = s_[pos_ + static_cast<size_t>(i)];
cp <<= 4;
if (h >= '0' && h <= '9') {
cp |= static_cast<unsigned>(h - '0');
} else if (h >= 'a' && h <= 'f') {
cp |= static_cast<unsigned>(h - 'a' + 10);
} else if (h >= 'A' && h <= 'F') {
cp |= static_cast<unsigned>(h - 'A' + 10);
} else {
return fail("bad hex escape");
}
}
pos_ += 4;
// 简化:不处理代理对(覆盖配置里没有 \u 转义)。
utf8_append(out.str, cp);
break;
}
default: return fail("unknown escape");
}
continue;
}
out.str.push_back(static_cast<char>(c));
++pos_;
}
return fail("unterminated string");
}
bool parse_array(Json& out) {
++pos_; // '['
out.kind = Json::Kind::Array;
out.arr.clear();
skip_ws();
if (pos_ < s_.size() && s_[pos_] == ']') {
++pos_;
return true;
}
while (true) {
Json v;
skip_ws();
if (!parse_value(v)) return false;
out.arr.push_back(std::move(v));
skip_ws();
if (pos_ >= s_.size()) return fail("unterminated array");
if (s_[pos_] == ',') {
++pos_;
continue;
}
if (s_[pos_] == ']') {
++pos_;
return true;
}
return fail("expected ',' or ']'");
}
}
bool parse_object(Json& out) {
++pos_; // '{'
out.kind = Json::Kind::Object;
out.obj.clear();
skip_ws();
if (pos_ < s_.size() && s_[pos_] == '}') {
++pos_;
return true;
}
while (true) {
skip_ws();
Json key;
if (!parse_string(key)) return false;
skip_ws();
if (pos_ >= s_.size() || s_[pos_] != ':') return fail("expected ':'");
++pos_;
Json v;
skip_ws();
if (!parse_value(v)) return false;
out.obj[key.str] = std::move(v);
skip_ws();
if (pos_ >= s_.size()) return fail("unterminated object");
if (s_[pos_] == ',') {
++pos_;
continue;
}
if (s_[pos_] == '}') {
++pos_;
return true;
}
return fail("expected ',' or '}'");
}
}
const std::string& s_;
size_t pos_ = 0;
std::string error_;
};
// 仓库根目录:优先用 CMake 注入的 VDE_SOURCE_DIR,其次从 cwd/__FILE__
// 向上探测 tools/coverage/target_profiles.json(兼容 ctest 在 build 目录
// 运行、以及 exe 被单独拷走的场景)。
fs::path repo_root() {
std::vector<fs::path> starts;
#ifdef VDE_SOURCE_DIR
starts.emplace_back(VDE_SOURCE_DIR);
#endif
{
std::error_code ec;
starts.push_back(fs::current_path(ec));
}
starts.emplace_back(fs::path(__FILE__).parent_path());
for (const auto& start : starts) {
std::error_code ec;
fs::path p = fs::absolute(start, ec);
if (ec) continue;
for (int depth = 0; depth < 8; ++depth) {
if (fs::exists(p / "tools" / "coverage" / "target_profiles.json", ec)) {
return p;
}
if (!p.has_parent_path()) break;
p = p.parent_path();
}
}
return {};
}
const Json* load_json(const fs::path& path, Json& storage, std::string& err) {
std::ifstream in(path, std::ios::binary);
if (!in) {
err = "无法打开 " + path.string();
return nullptr;
}
std::ostringstream oss;
oss << in.rdbuf();
std::string text = oss.str();
// 去掉 UTF-8 BOM(若有)。
if (text.size() >= 3 && static_cast<unsigned char>(text[0]) == 0xEF &&
static_cast<unsigned char>(text[1]) == 0xBB &&
static_cast<unsigned char>(text[2]) == 0xBF) {
text.erase(0, 3);
}
JsonParser parser(text);
if (!parser.parse(storage)) {
err = "JSON 解析失败: " + path.string() + " (" + parser.error() + ")";
return nullptr;
}
return &storage;
}
// core-plus-v2 profile 节点。
const Json* profile_node(const Json& root) {
const Json* profiles = root.find("profiles");
if (!profiles) return nullptr;
return profiles->find("core-plus-v2");
}
// baseline entries["core-plus-v2"] 节点。
const Json* baseline_entry(const Json& root) {
const Json* entries = root.find("entries");
if (!entries) return nullptr;
return entries->find("core-plus-v2");
}
double number_or(const Json* node, double fallback = 0.0) {
return (node && node->is_number()) ? node->num : fallback;
}
std::vector<std::string> string_array(const Json* node) {
std::vector<std::string> out;
if (!node || !node->is_array()) return out;
for (const auto& v : node->arr) {
if (v.is_string()) out.push_back(v.str);
}
return out;
}
bool contains(const std::vector<std::string>& haystack, const std::string& needle) {
for (const auto& s : haystack) {
if (s == needle) return true;
}
return false;
}
const char* const kWave9Targets[] = {
"test_cov_wave9_ssi",
"test_cov_wave9_heal",
"test_cov_wave9_generative",
"test_cov_wave9_mesh",
};
constexpr double kMinLineGate = 53.0;
class CoverageProfileConfigTest : public ::testing::Test {
protected:
void SetUp() override {
root_ = repo_root();
ASSERT_FALSE(root_.empty()) << "找不到仓库根目录(tools/coverage/target_profiles.json)";
profile_path_ = root_ / "tools" / "coverage" / "target_profiles.json";
baseline_path_ = root_ / "tools" / "coverage" / "baseline.json";
ASSERT_NE(load_json(profile_path_, profile_, err_), nullptr) << err_;
ASSERT_NE(load_json(baseline_path_, baseline_, err_), nullptr) << err_;
}
fs::path root_;
fs::path profile_path_;
fs::path baseline_path_;
Json profile_;
Json baseline_;
std::string err_;
};
// 1) W60 契约:core-plus-v2 必须覆盖 W54 的 4 个补测目标。
TEST_F(CoverageProfileConfigTest, ProfileIncludesWave9CoverageTargets) {
const Json* p = profile_node(profile_);
ASSERT_NE(p, nullptr) << "target_profiles.json 缺少 profiles['core-plus-v2']";
const std::vector<std::string> targets = string_array(p->find("targets"));
ASSERT_GE(targets.size(), 100u);
for (const char* name : kWave9Targets) {
EXPECT_TRUE(contains(targets, name)) << "core-plus-v2 缺少目标 " << name;
}
EXPECT_EQ(number_or(p->find("expected_min_cases"), 0.0), 2200.0);
}
// 2) W60 契约:gate 提到 53.0,且 goal 不低于 gate(gate 不得高于目标)。
TEST_F(CoverageProfileConfigTest, ProfileLineGateAtLeast53) {
const Json* p = profile_node(profile_);
ASSERT_NE(p, nullptr);
const double gate = number_or(p->find("line_pct_gate"), -1.0);
const double goal = number_or(p->find("line_pct_goal"), -1.0);
EXPECT_GE(gate, kMinLineGate) << "line_pct_gate 低于 W60 下限 53.0";
EXPECT_GT(goal, 0.0) << "缺少 line_pct_goal";
EXPECT_LE(gate, goal) << "line_pct_gate 高于 line_pct_goal(gate 不可高于目标)";
EXPECT_GE(goal, gate) << "line_pct_goal 应 >= line_pct_gate";
}
// 3) strict-baseline 漂移守卫:baseline entry 目标集与 profile 目标集一致。
TEST_F(CoverageProfileConfigTest, BaselineTargetsMatchProfile) {
const Json* p = profile_node(profile_);
ASSERT_NE(p, nullptr);
const Json* e = baseline_entry(baseline_);
ASSERT_NE(e, nullptr) << "baseline.json 缺少 entries['core-plus-v2']";
const std::vector<std::string> profile_targets = string_array(p->find("targets"));
const std::vector<std::string> baseline_targets = string_array(e->find("targets"));
ASSERT_FALSE(profile_targets.empty());
ASSERT_FALSE(baseline_targets.empty());
EXPECT_EQ(baseline_targets.size(), profile_targets.size())
<< "baseline 目标数与 profile 不一致(请用 --update-baseline 刷新)";
for (const auto& name : profile_targets) {
EXPECT_TRUE(contains(baseline_targets, name))
<< "baseline 缺少 profile 目标 " << name << "(strict-baseline 将漂移)";
}
EXPECT_EQ(number_or(e->find("target_count"), 0.0),
static_cast<double>(profile_targets.size()));
}
// 4) 门限逻辑:baseline 实测 line_pct 必须高于 gate(且 >= 53.0)。
TEST_F(CoverageProfileConfigTest, BaselineLinePctAboveGate) {
const Json* p = profile_node(profile_);
const Json* e = baseline_entry(baseline_);
ASSERT_NE(p, nullptr);
ASSERT_NE(e, nullptr);
const double gate = number_or(p->find("line_pct_gate"), -1.0);
const double line = number_or(e->find("line_pct"), -1.0);
EXPECT_GE(line, kMinLineGate);
EXPECT_GE(line, gate) << "baseline line_pct 低于 gate:gate 不可高于实测基线";
// W60 实测基线 line ≈ 54.0%,与 gate 53.0 之间应留出裕度(>= 0.5pp)。
EXPECT_GE(line - gate, 0.5) << "baseline 与 gate 裕度过小(<0.5pp),门限可能不稳定";
}
// 5) baseline entry 自洽性:count/tests/covered 统计一致。
TEST_F(CoverageProfileConfigTest, BaselineEntrySelfConsistent) {
const Json* e = baseline_entry(baseline_);
ASSERT_NE(e, nullptr);
const std::vector<std::string> targets = string_array(e->find("targets"));
EXPECT_EQ(number_or(e->find("target_count"), -1.0), static_cast<double>(targets.size()));
const Json* tests = e->find("tests");
ASSERT_NE(tests, nullptr) << "baseline entry 缺少 tests 统计";
const double total = number_or(tests->find("total"), -1.0);
const double passed = number_or(tests->find("passed"), -1.0);
const double failed = number_or(tests->find("failed"), -1.0);
EXPECT_GT(total, 0.0);
EXPECT_EQ(passed + failed, total);
EXPECT_EQ(failed, 0.0) << "baseline 记录的测试存在失败用例";
const double lines_covered = number_or(e->find("lines_covered"), -1.0);
const double lines_total = number_or(e->find("lines_total"), -1.0);
EXPECT_GT(lines_total, 0.0);
EXPECT_LE(lines_covered, lines_total);
EXPECT_GT(lines_covered, 0.0);
EXPECT_GE(number_or(e->find("func_pct"), -1.0), 0.0);
EXPECT_GE(number_or(e->find("branch_pct"), -1.0), 0.0);
EXPECT_FALSE(e->find("git") == nullptr || e->find("git")->str.empty())
<< "baseline entry 缺少 git 修订号";
}
// 6) 两份配置文件 schema_version 均为 1(工具链契约)。
TEST_F(CoverageProfileConfigTest, ConfigsUseSchemaVersion1) {
EXPECT_EQ(number_or(profile_.find("schema_version"), -1.0), 1.0);
EXPECT_EQ(number_or(baseline_.find("schema_version"), -1.0), 1.0);
const Json* p = profile_node(profile_);
ASSERT_NE(p, nullptr);
EXPECT_FALSE(p->find("description") == nullptr || p->find("description")->str.empty())
<< "core-plus-v2 缺少 description(W60 文档化契约)";
EXPECT_FALSE(p->find("notes") == nullptr || p->find("notes")->str.empty())
<< "core-plus-v2 缺少 notes(W60 更新说明)";
}
} // namespace
} // namespace coverage_cfg