Files
hm b2245ca0f7 feat(brep/foundation): Wave21 IGES face orientation, zero-copy import caches, UTF-8 leftovers
A52 (IGES face orientation closure, importer/exporter symmetric):
- importer: apply_shell_orientation derives face.reversed = (514 ORIENTATION==0) XOR (186 SHELLFLAG==0);
  token_is_pure_int guards legacy "0HNAME"; convert_face reads 510 OUTERLOOPFLAG, convert_loop reads
  508 ORIENTATION (diagnostics only); empty/void shells use their own SHELLFLAG
- exporter: 514 writes per-face ORIENTATION (0 when reversed), 510 OUTERLOOPFLAG=1, 508 ORIENTATION
  from edge.reversed; 144 counts reversed trimmed faces only (no orientation field); 186 keeps "1,0"
- test_iges_export 34 -> 43 tests (T1-T8, real corpus round-trips): occ__bug25415 vol_rel
  0.9697 -> 8.30e-12, occ__bug22821_test 2.0 -> 0, PWB/31000/28366 stay ~0

A53 (IGES import zero-copy caches):
- curve_cache_/surface_cache_ become unordered_map<int, shared_ptr<const NurbsCurve/NurbsSurface>>;
  hits share pointers, misses make_shared<const T>(std::move(...)); composite curves return pointers
- split_params/params_of return std::string_view (zero-copy token slicing; tokens are substrings)
- import_iges reads the file in one sized binary read (chunked fallback for >16GB or tellg failure)
- V8 Motor_1.igs 3.40 -> 1.346 s, moteur_v8_asm.igs 9.27 -> 3.284 s; topology/model hashes unchanged

A54/A55 (UTF-8 path leftovers):
- A54: 13 foundation files, 17 open sites -> open_ifstream_utf8/open_ofstream_utf8; 9 UTF-8 cases
- A55: 13 infra/plugin/capi/core files, 24+ sites (11 user-path sites in plugin_manager); 12 UTF-8 cases
- Linux-only fixed paths (/sys,/proc,/etc/machine-id) and platform.cpp fopen wrapper intentionally kept

Verification: 23 suites 918 passed / 0 failed; PR gate 1067/1067 (81.44 s); four KPI windows
bit-identical (fixed 196/36, auto 196/36, band 8/0 and 8/0); 35 extra suites green; redline identical.
2026-11-23 00:28:07 +08:00

1302 lines
56 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.
// P0-2/P0-3:插件清单解析 / 能力注册表 / PluginManager 单元测试
//
// 覆盖:语义化版本、清单合法/缺字段/坏 JSON/非法 ABI/entry 平台缺失/库不存在、
// 能力注册表增删查重(首次为准 + 冲突记录)、目录扫描(合法+非法混合、嵌套、
// 重复 id)、加载失败隔离(未发现/无宿主服务/ABI 不兼容/库加载失败/缺入口
// 符号/query 元信息不一致)、示例插件加载-卸载与 clear() 语义、
// 格式分派错误路径、线程安全冒烟。
#include <gtest/gtest.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include "vde/fs_compat.h"
#include <fstream>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "vde/foundation/utf8_path.h"
#include "vde/plugin/geometry_host_services.h"
#include "vde/plugin/plugin_manager.h"
#ifndef VDE_PLUGIN_SAMPLE_DIR
#define VDE_PLUGIN_SAMPLE_DIR ""
#endif
namespace {
namespace fs = vde::fs;
using vde::plugin::CapabilityRegistry;
using vde::plugin::FormatImportResult;
using vde::plugin::PluginKind;
using vde::plugin::PluginManager;
using vde::plugin::PluginManifest;
using vde::plugin::SemanticVersion;
// ── 临时目录(RAII,测试结束删除)──
class TempDir {
public:
TempDir() {
static std::atomic<unsigned> counter{0};
std::error_code ec;
const fs::path base = fs::temp_directory_path(ec);
const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
path_ = base / ("vde_plugin_test_" + std::to_string(stamp) + "_" +
std::to_string(counter.fetch_add(1)));
fs::create_directories(path_, ec);
}
~TempDir() {
std::error_code ec;
fs::remove_all(path_, ec);
}
TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete;
const fs::path& path() const { return path_; }
fs::path file(const std::string& relative) const { return path_ / relative; }
bool write(const std::string& relative, const std::string& content) const {
const fs::path target = file(relative);
std::error_code ec;
if (!target.parent_path().empty())
fs::create_directories(target.parent_path(), ec);
std::ofstream out(target.string(), std::ios::binary);
if (!out) return false;
out << content;
return static_cast<bool>(out);
}
bool write_dummy_library(const std::string& relative) const {
return write(relative, "not a real dynamic library");
}
private:
fs::path path_;
};
// ── 清单构造工具 ──
std::string entry_object(const std::string& library) {
std::ostringstream os;
os << R"({ "windows": ")" << library << R"(", "linux": ")" << library
<< R"(", "macos": ")" << library << R"(" })";
return os.str();
}
std::string manifest_json(const std::string& id, const std::string& version,
const std::string& kind, int abi_major, int abi_minor,
const std::string& library,
const std::string& capabilities = "format:demo.read",
const std::string& name = "") {
std::ostringstream os;
os << "{\n"
<< " \"id\": \"" << id << "\",\n"
<< " \"name\": \"" << (name.empty() ? id + " display" : name) << "\",\n"
<< " \"version\": \"" << version << "\",\n"
<< " \"kind\": \"" << kind << "\",\n"
<< " \"abi\": { \"major\": " << abi_major << ", \"minor\": " << abi_minor
<< " },\n"
<< " \"entry\": " << entry_object(library) << ",\n"
<< " \"capabilities\": [\"" << capabilities << "\"],\n"
<< " \"dependencies\": [],\n"
<< " \"license\": \"Apache-2.0\"\n"
<< "}\n";
return os.str();
}
/// 在临时目录下造一个「清单 + 占位动态库文件」的插件目录,返回清单路径
std::string make_plugin_dir(const TempDir& dir, const std::string& subdir,
const std::string& id, const std::string& version,
const std::string& kind, int abi_major, int abi_minor,
const std::string& library = "plugin.dll",
const std::string& capabilities = "format:demo.read") {
dir.write_dummy_library(subdir + "/" + library);
const std::string manifest = manifest_json(id, version, kind, abi_major, abi_minor,
library, capabilities);
dir.write(subdir + "/vde-plugin.json", manifest);
return dir.file(subdir + "/vde-plugin.json").string();
}
// ── 管理器状态重置(单例跨测试共享)──
void reset_manager() {
PluginManager& manager = PluginManager::instance();
manager.clear();
manager.clear_search_paths();
manager.clear_host_services();
}
void configure_test_host() {
PluginManager::instance().set_host_services(
vde::plugin::make_geometry_host_services());
}
// Wave21/A55:UTF-8 路径回归辅助——判定字符串是否含非 ASCII 字节。
bool a55_has_non_ascii(const std::string& s) {
for (const char c : s) {
if (static_cast<unsigned char>(c) >= 0x80) return true;
}
return false;
}
// 用 UTF-8 路径写文件(open_ofstream_utf8 在 Windows 下按 UTF-8 → 宽字符打开)。
bool a55_write_utf8_file(const std::string& utf8_path, const std::string& content) {
std::ofstream out =
vde::foundation::open_ofstream_utf8(utf8_path, std::ios::binary);
if (!out) return false;
out << content;
return out.good();
}
fs::path sample_plugin_dir() {
return fs::path(VDE_PLUGIN_SAMPLE_DIR) / "sample_vbox";
}
bool sample_plugin_available() {
std::error_code ec;
return fs::is_regular_file(sample_plugin_dir() / "vde-plugin.json", ec) && !ec;
}
/// 找一个可复制的系统动态库(用于"入口符号缺失"失败路径测试)
std::string find_copyable_system_library() {
#if defined(_WIN32)
const char* root = std::getenv("SystemRoot");
const std::string windows_dir = root ? std::string(root) : std::string("C:/Windows");
const std::vector<std::string> candidates = {
windows_dir + "/System32/version.dll",
windows_dir + "/System32/setupapi.dll",
};
#elif defined(__APPLE__)
const std::vector<std::string> candidates = {
"/usr/lib/libSystem.B.dylib",
};
#else
const std::vector<std::string> candidates = {
"/lib/x86_64-linux-gnu/libm.so.6",
"/usr/lib/libm.so.6",
"/lib64/libm.so.6",
};
#endif
for (const auto& candidate : candidates) {
std::error_code ec;
if (fs::is_regular_file(candidate, ec) && !ec) return candidate;
}
return std::string();
}
/// P4-37:复制已构建 sample 插件目录到临时目录,并覆写 manifest dependencies。
bool copy_sample_plugin(const std::string& sample_name, const std::string& dst,
const std::string& deps_json, const TempDir& dir) {
if (VDE_PLUGIN_SAMPLE_DIR[0] == '\0') return false;
const fs::path src = fs::path(VDE_PLUGIN_SAMPLE_DIR) / sample_name;
std::error_code ec;
if (!fs::is_directory(src, ec) || ec) return false;
const fs::path target = dir.file(dst);
fs::create_directories(target, ec);
if (ec) return false;
for (const auto& entry : fs::directory_iterator(src, ec)) {
if (ec) return false;
if (!entry.is_regular_file(ec) || ec) continue;
fs::copy_file(entry.path(), target / entry.path().filename(),
fs::copy_options::overwrite_existing, ec);
if (ec) return false;
}
std::ifstream in((target / "vde-plugin.json").string(), std::ios::binary);
if (!in) return false;
std::string text((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
const std::string needle = "\"dependencies\": []";
const std::size_t pos = text.find(needle);
if (pos == std::string::npos) return false;
text.replace(pos, needle.size(), "\"dependencies\": " + deps_json);
return dir.write(dst + "/vde-plugin.json", text);
}
} // namespace
// ═══════════════════════════════════════════════════════════
// 语义化版本 / 插件种类
// ═══════════════════════════════════════════════════════════
TEST(PluginSemanticVersionTest, ParsesStrictVersions) {
const std::vector<std::string> valid = {"0.0.0", "1.2.3", "10.20.30",
"1.0.27", "999.0.0"};
for (const auto& text : valid) {
const SemanticVersion version = vde::plugin::parse_semantic_version(text);
EXPECT_TRUE(version.valid) << text;
EXPECT_GE(version.major, 0) << text;
}
const SemanticVersion version = vde::plugin::parse_semantic_version("2.3.4");
EXPECT_EQ(version.major, 2);
EXPECT_EQ(version.minor, 3);
EXPECT_EQ(version.patch, 4);
}
TEST(PluginSemanticVersionTest, RejectsInvalidVersions) {
const std::vector<std::string> invalid = {
"", "1", "1.2", "1.2.3.4", "v1.2.3", "1.2.x",
"-1.2.3", "1.2.3-rc1", " 1.2.3", "1.2.3 ", "1..3", ".1.2",
};
for (const auto& text : invalid) {
const SemanticVersion version = vde::plugin::parse_semantic_version(text);
EXPECT_FALSE(version.valid) << "'" << text << "' 应判为非法版本";
}
}
TEST(PluginSemanticVersionTest, KindNameRoundTrip) {
const std::vector<PluginKind> kinds = {
PluginKind::Format, PluginKind::GeomOp, PluginKind::CaeSolver,
PluginKind::CamStrategy, PluginKind::Ui, PluginKind::Binding};
for (PluginKind kind : kinds) {
const std::string name = vde::plugin::plugin_kind_name(kind);
const auto parsed = vde::plugin::plugin_kind_from_string(name);
ASSERT_TRUE(parsed.has_value()) << name;
EXPECT_EQ(*parsed, kind);
}
EXPECT_STREQ(vde::plugin::plugin_kind_name(PluginKind::Format), "format");
EXPECT_FALSE(vde::plugin::plugin_kind_from_string("banana").has_value());
}
// ═══════════════════════════════════════════════════════════
// 清单解析(P0-2)
// ═══════════════════════════════════════════════════════════
TEST(PluginManifestTest, ParsesValidManifest) {
TempDir dir;
dir.write_dummy_library("demo/plugin.dll");
const std::string manifest_text =
manifest_json("com.test.demo", "1.2.3", "format", 1, 0, "plugin.dll",
"format:demo.read");
const std::string manifest_path = dir.file("demo/vde-plugin.json").string();
ASSERT_TRUE(dir.write("demo/vde-plugin.json", manifest_text));
PluginManifest manifest;
std::string error;
ASSERT_TRUE(vde::plugin::parse_plugin_manifest(manifest_text, manifest_path,
&manifest, &error))
<< error;
EXPECT_EQ(manifest.id, "com.test.demo");
EXPECT_EQ(manifest.name, "com.test.demo display");
EXPECT_TRUE(manifest.version.valid);
EXPECT_EQ(manifest.version.major, 1);
EXPECT_EQ(manifest.version.minor, 2);
EXPECT_EQ(manifest.version.patch, 3);
EXPECT_EQ(manifest.kind, PluginKind::Format);
EXPECT_EQ(manifest.abi_major, 1);
EXPECT_EQ(manifest.abi_minor, 0);
EXPECT_EQ(manifest.entry, "plugin.dll");
EXPECT_EQ(manifest.license, "Apache-2.0");
ASSERT_EQ(manifest.capabilities.size(), 1u);
EXPECT_EQ(manifest.capabilities[0], "format:demo.read");
EXPECT_EQ(manifest.manifest_path, manifest_path);
EXPECT_TRUE(fs::is_regular_file(manifest.library_path)) << manifest.library_path;
// name 缺省 = id
const std::string no_name = R"({
"id": "com.test.noname", "version": "0.1.0", "kind": "geom_op",
"abi": { "major": 1, "minor": 0 },
"entry": )" + entry_object("plugin.dll") + "}";
PluginManifest manifest2;
ASSERT_TRUE(vde::plugin::parse_plugin_manifest(no_name, manifest_path, &manifest2,
&error))
<< error;
EXPECT_EQ(manifest2.name, "com.test.noname");
}
TEST(PluginManifestTest, RejectsMissingRequiredFields) {
const std::vector<std::string> required = {"id", "version", "kind", "abi", "entry"};
for (const auto& field : required) {
std::ostringstream os;
os << "{";
bool first = true;
if (field != "id") { os << "\"id\": \"com.test.x\""; first = false; }
auto add = [&](const std::string& text) {
if (!first) os << ", ";
os << text;
first = false;
};
if (field != "version") add("\"version\": \"1.0.0\"");
if (field != "kind") add("\"kind\": \"format\"");
if (field != "abi") add("\"abi\": { \"major\": 1, \"minor\": 0 }");
if (field != "entry") add("\"entry\": " + entry_object("plugin.dll"));
os << "}";
PluginManifest manifest;
std::string error;
EXPECT_FALSE(vde::plugin::parse_plugin_manifest(os.str(), std::string(),
&manifest, &error))
<< "缺少必填字段 '" << field << "' 应解析失败";
EXPECT_FALSE(error.empty()) << field;
}
}
TEST(PluginManifestTest, RejectsBadJson) {
PluginManifest manifest;
std::string error;
EXPECT_FALSE(vde::plugin::parse_plugin_manifest("{ not json", "", &manifest, &error));
EXPECT_FALSE(error.empty());
EXPECT_FALSE(vde::plugin::parse_plugin_manifest("", "", &manifest, &error));
EXPECT_FALSE(vde::plugin::parse_plugin_manifest("[]", "", &manifest, &error));
EXPECT_FALSE(vde::plugin::parse_plugin_manifest("42", "", &manifest, &error));
}
TEST(PluginManifestTest, RejectsInvalidVersionAndAbi) {
TempDir dir;
dir.write_dummy_library("plugin.dll");
const std::string path = dir.file("vde-plugin.json").string();
struct Case {
std::string version;
int abi_major;
int abi_minor;
};
const std::vector<Case> cases = {
{"1.2", 1, 0}, // 非 x.y.z
{"abc", 1, 0}, // 非数字
{"1.2.3", -1, 0}, // 负 ABI major
{"1.2.3", 1, -2}, // 负 ABI minor
};
for (const auto& c : cases) {
const std::string text = manifest_json("com.test.x", c.version, "format",
c.abi_major, c.abi_minor, "plugin.dll");
PluginManifest manifest;
std::string error;
EXPECT_FALSE(vde::plugin::parse_plugin_manifest(text, path, &manifest, &error))
<< "version=" << c.version << " abi=" << c.abi_major << "." << c.abi_minor;
EXPECT_FALSE(error.empty());
}
// abi 缺 minor
const std::string missing_minor = R"({
"id": "com.test.x", "version": "1.0.0", "kind": "format",
"abi": { "major": 1 }, "entry": )" + entry_object("plugin.dll") + "}";
PluginManifest manifest;
std::string error;
EXPECT_FALSE(vde::plugin::parse_plugin_manifest(missing_minor, path, &manifest,
&error));
}
TEST(PluginManifestTest, RejectsMissingPlatformEntry) {
TempDir dir;
dir.write_dummy_library("plugin.dll");
const std::string path = dir.file("vde-plugin.json").string();
// 只给 linux 键(当前平台 Windows 时应失败;若未来在 Linux 运行则给 windows 键)
#if defined(_WIN32)
const std::string other_platform = "linux";
#elif defined(__APPLE__)
const std::string other_platform = "windows";
#else
const std::string other_platform = "windows";
#endif
const std::string text = R"({
"id": "com.test.x", "version": "1.0.0", "kind": "format",
"abi": { "major": 1, "minor": 0 },
"entry": { ")" + other_platform + R"(": "plugin.dll" }
})";
PluginManifest manifest;
std::string error;
EXPECT_FALSE(vde::plugin::parse_plugin_manifest(text, path, &manifest, &error));
EXPECT_NE(error.find("platform"), std::string::npos) << error;
}
TEST(PluginManifestTest, RejectsMissingLibraryFile) {
TempDir dir;
const std::string text = manifest_json("com.test.x", "1.0.0", "format", 1, 0,
"missing_library.dll");
const std::string path = dir.file("vde-plugin.json").string();
ASSERT_TRUE(dir.write("vde-plugin.json", text));
PluginManifest manifest;
std::string error;
EXPECT_FALSE(vde::plugin::parse_plugin_manifest(text, path, &manifest, &error));
EXPECT_NE(error.find("not found"), std::string::npos) << error;
}
TEST(PluginManifestTest, RejectsUnknownKind) {
TempDir dir;
dir.write_dummy_library("plugin.dll");
const std::string text = manifest_json("com.test.x", "1.0.0", "banana", 1, 0,
"plugin.dll");
PluginManifest manifest;
std::string error;
EXPECT_FALSE(vde::plugin::parse_plugin_manifest(
text, dir.file("vde-plugin.json").string(), &manifest, &error));
EXPECT_NE(error.find("kind"), std::string::npos) << error;
}
// ═══════════════════════════════════════════════════════════
// 能力注册表
// ═══════════════════════════════════════════════════════════
TEST(PluginCapabilityRegistryTest, AddQueryRemoveClear) {
CapabilityRegistry registry;
EXPECT_EQ(registry.size(), 0u);
EXPECT_FALSE(registry.has("format:step.read"));
registry.add("format:step.read", "com.acme.step");
registry.add("format:step.write", "com.acme.step");
registry.add("format:iges.read", "com.acme.iges");
EXPECT_EQ(registry.size(), 3u);
EXPECT_TRUE(registry.has("format:step.read"));
ASSERT_TRUE(registry.provider("format:step.read").has_value());
EXPECT_EQ(*registry.provider("format:step.read"), "com.acme.step");
EXPECT_FALSE(registry.provider("format:unknown.read").has_value());
const auto capabilities = registry.capabilities();
ASSERT_EQ(capabilities.size(), 3u);
EXPECT_TRUE(std::is_sorted(capabilities.begin(), capabilities.end()));
const auto providers = registry.providers();
ASSERT_EQ(providers.size(), 2u);
EXPECT_EQ(providers[0], "com.acme.iges");
EXPECT_EQ(providers[1], "com.acme.step");
registry.remove_provider("com.acme.step");
EXPECT_EQ(registry.size(), 1u);
EXPECT_FALSE(registry.has("format:step.read"));
EXPECT_TRUE(registry.has("format:iges.read"));
registry.clear();
EXPECT_EQ(registry.size(), 0u);
EXPECT_TRUE(registry.capabilities().empty());
EXPECT_TRUE(registry.providers().empty());
EXPECT_TRUE(registry.conflicts().empty());
}
TEST(PluginCapabilityRegistryTest, DuplicateCapabilityFirstProviderWins) {
CapabilityRegistry registry;
registry.add("format:step.read", "com.acme.step");
registry.add("format:step.read", "com.other.step"); // 重复:首次为准
EXPECT_EQ(registry.size(), 1u);
ASSERT_TRUE(registry.provider("format:step.read").has_value());
EXPECT_EQ(*registry.provider("format:step.read"), "com.acme.step");
const auto conflicts = registry.conflicts();
ASSERT_EQ(conflicts.size(), 1u);
EXPECT_NE(conflicts[0].find("com.acme.step"), std::string::npos);
EXPECT_NE(conflicts[0].find("com.other.step"), std::string::npos);
// 同提供者重复注册:幂等、不产生新冲突
registry.add("format:step.read", "com.acme.step");
EXPECT_EQ(registry.size(), 1u);
EXPECT_EQ(registry.conflicts().size(), 1u);
}
// ═══════════════════════════════════════════════════════════
// 插件发现(扫描)
// ═══════════════════════════════════════════════════════════
TEST(PluginDiscoveryTest, ScanDirectoryMixedValidAndInvalid) {
reset_manager();
TempDir dir;
make_plugin_dir(dir, "plugin_good", "com.test.good", "1.0.0", "format", 1, 0);
dir.write("plugin_bad_json/vde-plugin.json", "{ this is not json");
// 清单合法但动态库缺失
dir.write("plugin_missing_lib/vde-plugin.json",
manifest_json("com.test.missinglib", "1.0.0", "format", 1, 0,
"absent.dll"));
PluginManager& manager = PluginManager::instance();
std::string error;
const std::size_t added = manager.scan_directory(dir.path().string(), &error);
EXPECT_EQ(added, 1u);
EXPECT_FALSE(error.empty()) << "坏清单应写诊断但不中断";
const auto plugins = manager.plugins();
ASSERT_EQ(plugins.size(), 1u);
EXPECT_EQ(plugins[0].id, "com.test.good");
EXPECT_FALSE(plugins[0].manifest_path.empty());
EXPECT_TRUE(fs::is_regular_file(plugins[0].library_path));
// 重复扫描同一目录:不重复发现
EXPECT_EQ(manager.scan_directory(dir.path().string(), &error), 0u);
EXPECT_EQ(manager.plugins().size(), 1u);
reset_manager();
}
// Wave21/A55:UTF-8 路径回归(Windows ANSI 代码页)——非 ASCII 插件目录发现。
// 修复前 scan_directory 用 fs::path(std::string) 按 ACP 解释 dir,中文目录扫不到任何插件。
TEST(PluginDiscoveryTest, ScanDirectoryUtf8Path) {
reset_manager();
TempDir dir;
const std::string utf8_dir =
vde::foundation::path_to_utf8(dir.path()) + "/插件目录_①";
ASSERT_TRUE(a55_has_non_ascii(utf8_dir));
std::error_code ec;
fs::create_directories(vde::foundation::path_from_utf8(utf8_dir), ec);
ASSERT_FALSE(ec) << ec.message();
ASSERT_TRUE(a55_write_utf8_file(utf8_dir + "/vde-plugin.json",
manifest_json("com.test.utf8", "1.0.0", "format", 1,
0, "plugin.dll")));
ASSERT_TRUE(a55_write_utf8_file(utf8_dir + "/plugin.dll",
"not a real dynamic library"));
PluginManager& manager = PluginManager::instance();
std::string error;
const std::size_t added = manager.scan_directory(utf8_dir, &error);
EXPECT_EQ(added, 1u) << error;
const auto plugins = manager.plugins();
ASSERT_EQ(plugins.size(), 1u);
EXPECT_EQ(plugins[0].id, "com.test.utf8");
// 清单路径必须保持 UTF-8 编码(load() 会直接把它交给 open_ifstream_utf8)。
EXPECT_TRUE(a55_has_non_ascii(plugins[0].manifest_path));
EXPECT_NE(plugins[0].manifest_path.find("插件目录_①"), std::string::npos)
<< plugins[0].manifest_path;
EXPECT_NE(plugins[0].manifest_path.find("vde-plugin.json"), std::string::npos);
// 重复扫描:不重复发现
EXPECT_EQ(manager.scan_directory(utf8_dir, &error), 0u);
fs::remove_all(vde::foundation::path_from_utf8(utf8_dir), ec);
reset_manager();
}
TEST(PluginDiscoveryTest, ScanDirectoryNestedTwoLevels) {
reset_manager();
TempDir dir;
// 深度 0:目录本身无清单
// 深度 1:plugins/plugin_a/vde-plugin.json
// 深度 2:plugins/group/plugin_b/vde-plugin.json
make_plugin_dir(dir, "level1_plugin", "com.test.level1", "1.0.0", "format", 1, 0);
make_plugin_dir(dir, "group/level2_plugin", "com.test.level2", "2.0.0", "geom_op",
1, 0);
// 深度 3:不应被发现
make_plugin_dir(dir, "a/b/level3_plugin", "com.test.level3", "1.0.0", "format", 1,
0);
PluginManager& manager = PluginManager::instance();
std::string error;
const std::size_t added = manager.scan_directory(dir.path().string(), &error);
EXPECT_EQ(added, 2u);
const auto plugins = manager.plugins();
ASSERT_EQ(plugins.size(), 2u);
EXPECT_EQ(plugins[0].id, "com.test.level1");
EXPECT_EQ(plugins[1].id, "com.test.level2");
reset_manager();
}
TEST(PluginDiscoveryTest, ScanMissingDirectoryReportsError) {
reset_manager();
TempDir dir;
PluginManager& manager = PluginManager::instance();
std::string error;
EXPECT_EQ(manager.scan_directory(dir.file("does_not_exist").string(), &error), 0u);
EXPECT_FALSE(error.empty());
EXPECT_FALSE(manager.last_error().empty());
reset_manager();
}
// ═══════════════════════════════════════════════════════════
// 加载失败路径(失败隔离)
// ═══════════════════════════════════════════════════════════
TEST(PluginLoadTest, LoadNotDiscoveredFails) {
reset_manager();
PluginManager& manager = PluginManager::instance();
std::string error;
EXPECT_FALSE(manager.load("com.test.absent", &error));
EXPECT_NE(error.find("not discovered"), std::string::npos) << error;
EXPECT_FALSE(manager.is_loaded("com.test.absent"));
reset_manager();
}
TEST(PluginLoadTest, LoadWithoutHostServicesFails) {
reset_manager();
TempDir dir;
make_plugin_dir(dir, "plugin", "com.test.host", "1.0.0", "format", 1, 0);
PluginManager& manager = PluginManager::instance();
manager.add_search_path(dir.path().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u);
EXPECT_FALSE(manager.has_host_services());
EXPECT_FALSE(manager.load("com.test.host", &error));
EXPECT_NE(error.find("host services"), std::string::npos) << error;
EXPECT_FALSE(manager.is_loaded("com.test.host"));
reset_manager();
}
TEST(PluginLoadTest, LoadAbiMajorMismatchFails) {
reset_manager();
TempDir dir;
make_plugin_dir(dir, "plugin", "com.test.abimajor", "1.0.0", "format", 99, 0);
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(dir.path().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u);
EXPECT_FALSE(manager.load("com.test.abimajor", &error));
EXPECT_NE(error.find("ABI major"), std::string::npos) << error;
EXPECT_FALSE(manager.is_loaded("com.test.abimajor"));
reset_manager();
}
TEST(PluginLoadTest, LoadAbiMinorTooNewFails) {
reset_manager();
TempDir dir;
make_plugin_dir(dir, "plugin", "com.test.abiminor", "1.0.0", "format", 1, 999);
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(dir.path().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u);
EXPECT_FALSE(manager.load("com.test.abiminor", &error));
EXPECT_NE(error.find("ABI minor"), std::string::npos) << error;
reset_manager();
}
TEST(PluginLoadTest, LoadLibraryLoadFailureFails) {
reset_manager();
TempDir dir;
// 占位文件不是有效动态库:清单校验通过,但 load_library 失败
make_plugin_dir(dir, "plugin", "com.test.badlib", "1.0.0", "format", 1, 0,
"bad_library.dll");
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(dir.path().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u);
EXPECT_FALSE(manager.load("com.test.badlib", &error));
EXPECT_NE(error.find("cannot load"), std::string::npos) << error;
EXPECT_FALSE(manager.is_loaded("com.test.badlib"));
reset_manager();
}
TEST(PluginLoadTest, LoadMissingEntrySymbolsFails) {
reset_manager();
const std::string system_library = find_copyable_system_library();
if (system_library.empty()) {
GTEST_SKIP() << "no copyable system dynamic library found";
}
TempDir dir;
std::error_code ec;
dir.write("plugin/vde-plugin.json",
manifest_json("com.test.nosymbols", "1.0.0", "format", 1, 0,
"not_a_plugin.dll"));
ASSERT_TRUE(fs::copy_file(system_library, dir.file("plugin/not_a_plugin.dll"),
fs::copy_options::overwrite_existing, ec))
<< ec.message();
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(dir.path().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u) << error;
EXPECT_FALSE(manager.load("com.test.nosymbols", &error));
EXPECT_NE(error.find("missing exported symbol"), std::string::npos) << error;
EXPECT_FALSE(manager.is_loaded("com.test.nosymbols"));
reset_manager();
}
TEST(PluginLoadTest, LoadQueryMismatchRejected) {
reset_manager();
if (!sample_plugin_available()) {
GTEST_SKIP() << "sample plugin not built at " << sample_plugin_dir().string();
}
// 复制示例插件 DLL,但清单 id/version 伪造 → 应被 query 交叉校验拒绝
TempDir dir;
std::error_code ec;
fs::create_directories(dir.file("plugin"), ec);
dir.write("plugin/vde-plugin.json",
manifest_json("com.test.fakeid", "9.9.9", "format", 1, 0,
"fake_plugin.dll", "format:fake.read"));
const fs::path sample_library = sample_plugin_dir() / "vde_sample_vbox.dll";
if (!fs::is_regular_file(sample_library, ec) || ec) {
GTEST_SKIP() << "sample plugin library missing";
}
ASSERT_TRUE(fs::copy_file(sample_library, dir.file("plugin/fake_plugin.dll"),
fs::copy_options::overwrite_existing, ec))
<< ec.message();
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(dir.path().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u);
EXPECT_FALSE(manager.load("com.test.fakeid", &error));
EXPECT_NE(error.find("mismatch"), std::string::npos) << error;
reset_manager();
}
// ═══════════════════════════════════════════════════════════
// 示例插件:加载 / 卸载 / 失败隔离
// ═══════════════════════════════════════════════════════════
TEST(PluginLoadTest, LoadUnloadSamplePlugin) {
reset_manager();
if (!sample_plugin_available()) {
GTEST_SKIP() << "sample plugin not built at " << sample_plugin_dir().string();
}
PluginManager& manager = PluginManager::instance();
configure_test_host();
ASSERT_TRUE(manager.has_host_services());
manager.add_search_path(sample_plugin_dir().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u) << error;
const auto plugins = manager.plugins();
ASSERT_EQ(plugins.size(), 1u);
const std::string plugin_id = plugins[0].id;
EXPECT_EQ(plugin_id, "com.vde.sample.vbox");
EXPECT_TRUE(plugins[0].version.valid);
EXPECT_EQ(plugins[0].abi_major, VDE_PLUGIN_ABI_MAJOR);
EXPECT_TRUE(manager.load(plugin_id, &error)) << error;
EXPECT_TRUE(manager.is_loaded(plugin_id));
// 幂等:重复 load 成功且能力不重复
EXPECT_TRUE(manager.load(plugin_id, &error)) << error;
EXPECT_TRUE(manager.capabilities().has("format:vbox.read"));
EXPECT_TRUE(manager.capabilities().has("format:vbox.write"));
const auto provider = manager.capabilities().provider("format:vbox.read");
ASSERT_TRUE(provider.has_value());
EXPECT_EQ(*provider, plugin_id);
const auto formats = manager.formats();
ASSERT_EQ(formats.size(), 1u);
EXPECT_EQ(formats[0].plugin_id, plugin_id);
EXPECT_EQ(formats[0].format_id, "vbox");
EXPECT_NE(formats[0].extensions.find(".vbox"), std::string::npos);
EXPECT_TRUE(manager.unload(plugin_id, &error)) << error;
EXPECT_FALSE(manager.is_loaded(plugin_id));
EXPECT_TRUE(manager.formats().empty());
EXPECT_FALSE(manager.capabilities().has("format:vbox.read"));
// 卸载未加载插件 → 幂等成功(P4-46)
EXPECT_TRUE(manager.unload(plugin_id, &error)) << error;
EXPECT_TRUE(error.empty());
// 卸载后可再次加载(库句柄/状态清理正确)
EXPECT_TRUE(manager.load(plugin_id, &error)) << error;
EXPECT_TRUE(manager.unload(plugin_id, &error)) << error;
reset_manager();
}
TEST(PluginLoadTest, LoadFailureIsolationBetweenPlugins) {
reset_manager();
if (!sample_plugin_available()) {
GTEST_SKIP() << "sample plugin not built at " << sample_plugin_dir().string();
}
TempDir dir;
make_plugin_dir(dir, "bad_abi", "com.test.badabi", "1.0.0", "format", 42, 0);
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(dir.path().string());
manager.add_search_path(sample_plugin_dir().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 2u) << error;
// 坏插件加载失败...
EXPECT_FALSE(manager.load("com.test.badabi", &error));
EXPECT_FALSE(manager.is_loaded("com.test.badabi"));
// ...不影响其它插件加载
EXPECT_TRUE(manager.load("com.vde.sample.vbox", &error)) << error;
EXPECT_TRUE(manager.is_loaded("com.vde.sample.vbox"));
EXPECT_TRUE(manager.unload("com.vde.sample.vbox", &error)) << error;
reset_manager();
}
TEST(PluginLoadTest, ClearUnloadsPluginsAndKeepsHostAndSearchPaths) {
reset_manager();
if (!sample_plugin_available()) {
GTEST_SKIP() << "sample plugin not built at " << sample_plugin_dir().string();
}
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(sample_plugin_dir().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u);
ASSERT_TRUE(manager.load("com.vde.sample.vbox", &error)) << error;
manager.clear();
EXPECT_FALSE(manager.is_loaded("com.vde.sample.vbox"));
EXPECT_TRUE(manager.plugins().empty());
EXPECT_TRUE(manager.formats().empty());
EXPECT_EQ(manager.capabilities().size(), 0u);
EXPECT_TRUE(manager.has_host_services()); // clear() 保留宿主服务
// 搜索路径保留 → 可重新发现
EXPECT_EQ(manager.scan_search_paths(&error), 1u) << error;
reset_manager();
}
// ═══════════════════════════════════════════════════════════
// 格式分派(P0)
// ═══════════════════════════════════════════════════════════
TEST(PluginFormatDispatchTest, ImportExportWithoutHostServicesFail) {
reset_manager();
TempDir dir;
ASSERT_TRUE(dir.write("model.vbox", "vbox 1\n1 2 3"));
PluginManager& manager = PluginManager::instance();
FormatImportResult result;
EXPECT_FALSE(manager.import_file(dir.file("model.vbox").string(), &result));
EXPECT_FALSE(result.ok);
EXPECT_NE(result.error.find("host services"), std::string::npos) << result.error;
EXPECT_FALSE(manager.export_file(dir.file("out.vbox").string(), {}));
EXPECT_NE(manager.last_error().find("host services"), std::string::npos)
<< manager.last_error();
reset_manager();
}
TEST(PluginFormatDispatchTest, ImportNoMatchingPluginFails) {
reset_manager();
if (!sample_plugin_available()) {
GTEST_SKIP() << "sample plugin not built at " << sample_plugin_dir().string();
}
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(sample_plugin_dir().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u);
ASSERT_TRUE(manager.load("com.vde.sample.vbox", &error)) << error;
TempDir dir;
ASSERT_TRUE(dir.write("unknown.bin", "unknown-format-payload"));
FormatImportResult result;
EXPECT_FALSE(manager.import_file(dir.file("unknown.bin").string(), &result));
EXPECT_NE(result.error.find("no loaded format plugin"), std::string::npos)
<< result.error;
// 文件不存在同样失败且不崩溃
FormatImportResult missing;
EXPECT_FALSE(manager.import_file(dir.file("absent.vbox").string(), &missing));
EXPECT_FALSE(missing.error.empty());
reset_manager();
}
TEST(PluginFormatDispatchTest, ImportExportReachSamplePlugin) {
reset_manager();
if (!sample_plugin_available()) {
GTEST_SKIP() << "sample plugin not built at " << sample_plugin_dir().string();
}
PluginManager& manager = PluginManager::instance();
configure_test_host();
manager.add_search_path(sample_plugin_dir().string());
std::string error;
ASSERT_EQ(manager.scan_search_paths(&error), 1u);
ASSERT_TRUE(manager.load("com.vde.sample.vbox", &error)) << error;
TempDir dir;
ASSERT_TRUE(dir.write("cube.vbox", "vbox 1\n1 2 3\n"));
// 分派必须选中示例插件并调用其 read_file:成功时 ok=true;当前脚手架
// read_file 返回 UNSUPPORTED(P0-5 由 plugin-host 补全)时错误必须指明插件。
FormatImportResult result;
const bool imported =
manager.import_file(dir.file("cube.vbox").string(), &result);
if (imported) {
EXPECT_TRUE(result.ok);
EXPECT_EQ(result.format_id, "vbox");
} else {
EXPECT_FALSE(result.ok);
EXPECT_NE(result.error.find("com.vde.sample.vbox"), std::string::npos)
<< result.error;
}
// 导出同理:按扩展名选中 vbox 插件(写能力由 P0-5 补全)
const bool exported = manager.export_file(dir.file("out.vbox").string(), {});
if (!exported) {
EXPECT_NE(manager.last_error().find("com.vde.sample.vbox"), std::string::npos)
<< manager.last_error();
}
reset_manager();
}
// ═══════════════════════════════════════════════════════════
// 线程安全冒烟
// ═══════════════════════════════════════════════════════════
TEST(PluginThreadingTest, ConcurrentQueriesDoNotCrash) {
reset_manager();
PluginManager& manager = PluginManager::instance();
configure_test_host();
if (sample_plugin_available()) {
manager.add_search_path(sample_plugin_dir().string());
std::string error;
manager.scan_search_paths(&error);
manager.load("com.vde.sample.vbox", &error);
}
std::atomic<bool> failed{false};
std::vector<std::thread> threads;
for (int t = 0; t < 4; ++t) {
threads.emplace_back([&manager, &failed]() {
for (int i = 0; i < 200; ++i) {
const auto plugins = manager.plugins();
const bool loaded = manager.is_loaded("com.vde.sample.vbox");
const auto formats = manager.formats();
const auto caps = manager.capabilities().size();
const auto conflicts = manager.capabilities().conflicts();
const std::string& error = manager.last_error();
(void)plugins;
(void)loaded;
(void)formats;
(void)caps;
(void)conflicts;
(void)error;
}
});
}
for (auto& thread : threads) thread.join();
EXPECT_FALSE(failed.load());
reset_manager();
}
// ═══════════════════════════════════════════════════════════════════
// P0 验证修复回归:import_file 必须释放插件分配的 VdeBody* 数组
// (verifier 报告 §8-2:host->alloc 后未 host->free,每次导入泄漏一个数组)
// ═══════════════════════════════════════════════════════════════════
namespace {
VdePluginHost g_counting_base{};
std::atomic<long> g_body_array_balance{0};
void* counting_alloc(size_t size) {
void* p = g_counting_base.alloc ? g_counting_base.alloc(size) : nullptr;
if (p) ++g_body_array_balance;
return p;
}
void* counting_realloc(void* ptr, size_t size) {
return g_counting_base.realloc ? g_counting_base.realloc(ptr, size) : nullptr;
}
void counting_free(void* ptr) {
if (!ptr) return;
--g_body_array_balance;
if (g_counting_base.free) g_counting_base.free(ptr);
}
} // namespace
TEST(PluginManagerLeakTest, ImportReleasesPluginBodyArray) {
reset_manager();
ASSERT_TRUE(sample_plugin_available()) << "sample_vbox 未构建/未部署";
g_body_array_balance = 0;
g_counting_base = vde::plugin::make_geometry_host_services();
ASSERT_NE(g_counting_base.alloc, nullptr);
ASSERT_NE(g_counting_base.free, nullptr);
VdePluginHost host = g_counting_base;
host.alloc = &counting_alloc;
host.realloc = &counting_realloc;
host.free = &counting_free;
PluginManager& manager = PluginManager::instance();
manager.set_host_services(host);
// 注意:<build>/plugins 下除 sample_vbox 外还有官方格式插件(P1:plugins/official/*),
// 因此只要求至少发现一个清单,再按 id 显式加载被测插件。
ASSERT_GE(manager.scan_directory(VDE_PLUGIN_SAMPLE_DIR, nullptr), 1u);
ASSERT_TRUE(manager.load("com.vde.sample.vbox")) << manager.last_error();
ASSERT_FALSE(manager.formats().empty());
TempDir dir;
ASSERT_TRUE(dir.write("leak.vbox", "vbox 1\n1 2 3\n"));
const std::string path = dir.file("leak.vbox").string();
for (int i = 0; i < 20; ++i) {
FormatImportResult result;
ASSERT_TRUE(manager.import_file(path, &result))
<< "iter " << i << ": " << manager.last_error();
ASSERT_EQ(result.bodies.size(), 1u);
for (VdeBody body : result.bodies) {
if (g_counting_base.body_destroy) g_counting_base.body_destroy(body);
}
result.bodies.clear();
// 插件返回的句柄数组已由 manager 用 host->free 释放:宿主分配计数应归零,
// 否则下一次迭代会看到 +1 增长(修复前每轮泄漏一个数组)。
EXPECT_EQ(g_body_array_balance.load(), 0) << "iter " << i;
}
manager.unload("com.vde.sample.vbox");
reset_manager();
}
// ═══════════════════════════════════════════════════════════
// P4-37:manifest dependencies 解析/拓扑加载/错误语义
// ═══════════════════════════════════════════════════════════
TEST(PluginDependencyTest, LoadsDependenciesBeforeDependentPlugin) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox 未构建";
reset_manager();
TempDir dir;
ASSERT_TRUE(copy_sample_plugin("sample_vbox", "dep_vbox",
R"(["com.vde.sample.cae"])", dir));
ASSERT_TRUE(copy_sample_plugin("sample_cae", "dep_cae", "[]", dir));
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(dir.path().string());
std::string error;
manager.scan_search_paths(&error);
ASSERT_TRUE(manager.load("com.vde.sample.vbox", &error)) << error;
EXPECT_TRUE(manager.is_loaded("com.vde.sample.cae"));
EXPECT_TRUE(manager.is_loaded("com.vde.sample.vbox"));
reset_manager();
}
TEST(PluginDependencyTest, MissingDependencyFailsWithExplicitError) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox 未构建";
reset_manager();
TempDir dir;
ASSERT_TRUE(copy_sample_plugin("sample_vbox", "dep_vbox",
R"(["com.vde.sample.absent"])", dir));
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(dir.path().string());
std::string error;
manager.scan_search_paths(&error);
EXPECT_FALSE(manager.load("com.vde.sample.vbox", &error));
EXPECT_NE(error.find("missing dependency"), std::string::npos) << error;
EXPECT_NE(error.find("com.vde.sample.absent"), std::string::npos) << error;
EXPECT_FALSE(manager.is_loaded("com.vde.sample.vbox"));
reset_manager();
}
TEST(PluginDependencyTest, DependencyCycleFailsWithExplicitError) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox 未构建";
reset_manager();
TempDir dir;
ASSERT_TRUE(copy_sample_plugin("sample_vbox", "dep_vbox",
R"(["com.vde.sample.cae"])", dir));
ASSERT_TRUE(copy_sample_plugin("sample_cae", "dep_cae",
R"(["com.vde.sample.vbox"])", dir));
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(dir.path().string());
std::string error;
manager.scan_search_paths(&error);
EXPECT_FALSE(manager.load("com.vde.sample.vbox", &error));
EXPECT_NE(error.find("dependency cycle"), std::string::npos) << error;
EXPECT_FALSE(manager.is_loaded("com.vde.sample.vbox"));
EXPECT_FALSE(manager.is_loaded("com.vde.sample.cae"));
reset_manager();
}
// ═══════════════════════════════════════════════════════════
// P4-46:热重载 / 依赖感知卸载
// ═══════════════════════════════════════════════════════════
TEST(PluginReloadTest, ReloadNotLoadedIsLoad) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox not built";
reset_manager();
TempDir dir;
ASSERT_TRUE(copy_sample_plugin("sample_vbox", "reload_vbox", "[]", dir));
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(dir.path().string());
std::string error;
manager.scan_search_paths(&error);
EXPECT_TRUE(manager.reload("com.vde.sample.vbox", &error)) << error;
EXPECT_TRUE(manager.is_loaded("com.vde.sample.vbox"));
reset_manager();
}
TEST(PluginReloadTest, ReloadDependedPluginKeepsDependentsLoaded) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox not built";
reset_manager();
TempDir dir;
ASSERT_TRUE(copy_sample_plugin("sample_vbox", "reload_vbox", R"(["com.vde.sample.cae"])", dir));
ASSERT_TRUE(copy_sample_plugin("sample_cae", "reload_cae", "[]", dir));
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(dir.path().string());
std::string error;
manager.scan_search_paths(&error);
ASSERT_TRUE(manager.load("com.vde.sample.vbox", &error)) << error;
ASSERT_TRUE(manager.load("com.vde.sample.cae", &error)) << error;
ASSERT_TRUE(manager.is_loaded("com.vde.sample.vbox"));
ASSERT_TRUE(manager.is_loaded("com.vde.sample.cae"));
// 重载被依赖者:先卸载依赖者,再加载被依赖者,最后按依赖顺序恢复依赖者。
EXPECT_TRUE(manager.reload("com.vde.sample.cae", &error)) << error;
EXPECT_TRUE(manager.is_loaded("com.vde.sample.cae"));
EXPECT_TRUE(manager.is_loaded("com.vde.sample.vbox"));
EXPECT_TRUE(manager.reload("com.vde.sample.vbox", &error)) << error;
EXPECT_TRUE(manager.is_loaded("com.vde.sample.vbox"));
reset_manager();
}
TEST(PluginReloadTest, UnloadRejectsActiveDependents) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox not built";
reset_manager();
TempDir dir;
ASSERT_TRUE(copy_sample_plugin("sample_vbox", "reload_vbox", R"(["com.vde.sample.cae"])", dir));
ASSERT_TRUE(copy_sample_plugin("sample_cae", "reload_cae", "[]", dir));
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(dir.path().string());
std::string error;
manager.scan_search_paths(&error);
ASSERT_TRUE(manager.load("com.vde.sample.vbox", &error)) << error;
error.clear();
EXPECT_FALSE(manager.unload("com.vde.sample.cae", &error));
EXPECT_NE(error.find("depended on"), std::string::npos) << error;
EXPECT_NE(error.find("com.vde.sample.vbox"), std::string::npos) << error;
EXPECT_NE(error.find("unload_cascade"), std::string::npos) << error;
EXPECT_TRUE(manager.is_loaded("com.vde.sample.cae"));
EXPECT_TRUE(manager.is_loaded("com.vde.sample.vbox"));
// 显式 cascade 卸载:依赖者先卸载,再卸载被依赖者。
error.clear();
EXPECT_TRUE(manager.unload_cascade("com.vde.sample.cae", &error)) << error;
EXPECT_FALSE(manager.is_loaded("com.vde.sample.cae"));
EXPECT_FALSE(manager.is_loaded("com.vde.sample.vbox"));
// 重复 cascade(未加载)幂等。
EXPECT_TRUE(manager.unload_cascade("com.vde.sample.cae", &error)) << error;
reset_manager();
}
TEST(PluginReloadTest, UnloadCascadeOverload) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox not built";
reset_manager();
TempDir dir;
ASSERT_TRUE(copy_sample_plugin("sample_vbox", "reload_vbox", R"(["com.vde.sample.cae"])", dir));
ASSERT_TRUE(copy_sample_plugin("sample_cae", "reload_cae", "[]", dir));
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(dir.path().string());
std::string error;
manager.scan_search_paths(&error);
ASSERT_TRUE(manager.load("com.vde.sample.vbox", &error)) << error;
EXPECT_FALSE(manager.unload("com.vde.sample.cae", false, &error));
EXPECT_TRUE(manager.unload("com.vde.sample.cae", true, &error)) << error;
EXPECT_FALSE(manager.is_loaded("com.vde.sample.vbox"));
reset_manager();
}
TEST(PluginReloadTest, ReloadUnknownPluginFailsCleanly) {
reset_manager();
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
std::string error;
EXPECT_FALSE(manager.reload("com.vde.sample.absent", &error));
EXPECT_FALSE(error.empty());
reset_manager();
}
TEST(PluginReloadTest, ReloadFailureRollsBack) {
if (VDE_RELOAD_FIXTURE_DIR[0] == '\0') GTEST_SKIP() << "reload fixture not built";
reset_manager();
TempDir dir;
const std::string marker = dir.file("reload_marker.txt").string();
#if defined(_WIN32)
_putenv_s("VDE_TEST_RELOAD_MARKER", marker.c_str());
#else
setenv("VDE_TEST_RELOAD_MARKER", marker.c_str(), 1);
#endif
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(VDE_RELOAD_FIXTURE_DIR);
std::string error;
manager.scan_search_paths(&error);
ASSERT_TRUE(manager.load("com.vde.test.reload", &error)) << error;
ASSERT_TRUE(manager.is_loaded("com.vde.test.reload"));
// 新版本 init 失败一次(夹具消费 marker 后返回错误);reload 应回滚旧版本。
ASSERT_TRUE(dir.write("reload_marker.txt", "fail-next-init"));
error.clear();
EXPECT_FALSE(manager.reload("com.vde.test.reload", &error));
EXPECT_NE(error.find("failed to load"), std::string::npos) << error;
EXPECT_NE(error.find("rolled back"), std::string::npos) << error;
EXPECT_TRUE(manager.is_loaded("com.vde.test.reload"));
#if defined(_WIN32)
_putenv_s("VDE_TEST_RELOAD_MARKER", "");
#else
unsetenv("VDE_TEST_RELOAD_MARKER");
#endif
reset_manager();
}
// ═══════════════════════════════════════════════════════════
// P4-49:插件管理器可观测性(统计 + diagnostics JSON)
// ═══════════════════════════════════════════════════════════
TEST(PluginStatsTest, InitialAndUnknownPlugin) {
reset_manager();
PluginManager& manager = PluginManager::instance();
EXPECT_TRUE(manager.plugin_stats().empty());
EXPECT_EQ(manager.diagnostics_json(), "[]");
EXPECT_FALSE(manager.plugin_stats("com.vde.test.unknown").has_value());
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox not built";
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(VDE_PLUGIN_SAMPLE_DIR);
std::string error;
manager.scan_search_paths(&error);
const auto initial = manager.plugin_stats("com.vde.sample.vbox");
ASSERT_TRUE(initial.has_value());
EXPECT_FALSE(initial->loaded);
EXPECT_EQ(initial->load_count, 0u);
EXPECT_EQ(initial->error_count, 0u);
EXPECT_EQ(initial->kind, "format");
reset_manager();
}
TEST(PluginStatsTest, LoadReloadUnloadCounts) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox not built";
reset_manager();
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(VDE_PLUGIN_SAMPLE_DIR);
std::string error;
manager.scan_search_paths(&error);
const std::string id = "com.vde.sample.vbox";
ASSERT_TRUE(manager.load(id, &error)) << error;
auto stats = manager.plugin_stats(id);
ASSERT_TRUE(stats.has_value());
EXPECT_TRUE(stats->loaded);
EXPECT_EQ(stats->load_count, 1u);
EXPECT_EQ(stats->unload_count, 0u);
EXPECT_EQ(stats->reload_count, 0u);
EXPECT_EQ(stats->error_count, 0u);
EXPECT_GE(stats->last_load_ms, 0.0);
ASSERT_TRUE(manager.reload(id, &error)) << error;
stats = manager.plugin_stats(id);
ASSERT_TRUE(stats.has_value());
EXPECT_EQ(stats->load_count, 2u);
EXPECT_EQ(stats->reload_count, 1u);
// reload 内部先物理卸载一次,因此 unload_count 已为 1。
EXPECT_EQ(stats->unload_count, 1u);
EXPECT_TRUE(stats->loaded);
ASSERT_TRUE(manager.unload(id, &error)) << error;
stats = manager.plugin_stats(id);
ASSERT_TRUE(stats.has_value());
EXPECT_FALSE(stats->loaded);
EXPECT_EQ(stats->unload_count, 2u);
reset_manager();
}
TEST(PluginStatsTest, FailureUpdatesErrorCountAndLastError) {
reset_manager();
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
std::string error;
EXPECT_FALSE(manager.load("com.vde.test.absent", &error));
const auto stats = manager.plugin_stats("com.vde.test.absent");
ASSERT_TRUE(stats.has_value());
EXPECT_GE(stats->error_count, 1u);
EXPECT_FALSE(stats->last_error.empty());
EXPECT_FALSE(stats->loaded);
reset_manager();
}
TEST(PluginStatsTest, DiagnosticsJsonIsDeterministicAndComplete) {
if (!sample_plugin_available()) GTEST_SKIP() << "sample_vbox not built";
reset_manager();
PluginManager& manager = PluginManager::instance();
manager.set_host_services(vde::plugin::make_geometry_host_services());
manager.add_search_path(VDE_PLUGIN_SAMPLE_DIR);
std::string error;
manager.scan_search_paths(&error);
const std::string id = "com.vde.sample.vbox";
ASSERT_TRUE(manager.load(id, &error)) << error;
const std::string first = manager.diagnostics_json();
const std::string second = manager.diagnostics_json();
EXPECT_EQ(first, second);
EXPECT_NE(first.find("\"plugin_id\":\"" + id + "\""), std::string::npos) << first;
EXPECT_NE(first.find("\"loaded\":true"), std::string::npos) << first;
EXPECT_NE(first.find("\"load_count\":1"), std::string::npos) << first;
EXPECT_NE(first.find("\"last_load_ms\":"), std::string::npos) << first;
EXPECT_EQ(first.front(), '[');
EXPECT_EQ(first.back(), ']');
reset_manager();
}