// P0-2/P0-3:插件清单解析 / 能力注册表 / PluginManager 单元测试 // // 覆盖:语义化版本、清单合法/缺字段/坏 JSON/非法 ABI/entry 平台缺失/库不存在、 // 能力注册表增删查重(首次为准 + 冲突记录)、目录扫描(合法+非法混合、嵌套、 // 重复 id)、加载失败隔离(未发现/无宿主服务/ABI 不兼容/库加载失败/缺入口 // 符号/query 元信息不一致)、示例插件加载-卸载与 clear() 语义、 // 格式分派错误路径、线程安全冒烟。 #include #include #include #include #include #include "vde/fs_compat.h" #include #include #include #include #include #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 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(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()); } 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 candidates = { windows_dir + "/System32/version.dll", windows_dir + "/System32/setupapi.dll", }; #elif defined(__APPLE__) const std::vector candidates = { "/usr/lib/libSystem.B.dylib", }; #else const std::vector 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(); } } // namespace // ═══════════════════════════════════════════════════════════ // 语义化版本 / 插件种类 // ═══════════════════════════════════════════════════════════ TEST(PluginSemanticVersionTest, ParsesStrictVersions) { const std::vector 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 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 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 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 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(); } 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")); // 卸载未加载插件 → 明确失败 EXPECT_FALSE(manager.unload(plugin_id, &error)); EXPECT_NE(error.find("not loaded"), std::string::npos) << error; // 卸载后可再次加载(库句柄/状态清理正确) 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 failed{false}; std::vector 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 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); // 注意:/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(); }