Files
ViewDesignEngine/tests/plugin/test_plugin_extensions.cpp
T

494 lines
21 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// P2-2 插件扩展点(CAE 求解器 / CAM 策略,ABI 1.2)+ 进程外服务协议最小验证。
//
// 覆盖:
// 1) ABI 1.2:VdeCaeSolverPlugin / VdeCamStrategyPlugin 注册、PluginManager
// cae_solvers()/cam_strategies() 查询与 solve_cae()/invoke_cam() 调用;
// 2) 失败隔离:未知 solver/strategy、坏模型数据、插件未加载 → false + error,
// 且不影响后续合法调用;
// 3) ABI 1.1 旧插件(VDE_PLUGIN_ABI_MINOR_OVERRIDE=1 构建)在新宿主可发现/加载/导入;
// 4) 进程外服务协议草案:runner 发现服务 + 请求/响应文件交换 + 示例 STL→OBJ 服务 +
// 超时强制终止 + 协议错误退出码。
#include <gtest/gtest.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "vde/fs_compat.h"
#include <fstream>
#include <string>
#include <vector>
#ifndef _WIN32
#include <sys/wait.h>
#endif
#include "vde/plugin/geometry_host_services.h"
#include "vde/plugin/plugin_manager.h"
#include "vde/plugin/vde_plugin_api.h"
#ifndef VDE_PLUGIN_DIRS
#define VDE_PLUGIN_DIRS ""
#endif
#ifndef VDE_PLUGIN_EXTERNAL_DIR
#define VDE_PLUGIN_EXTERNAL_DIR ""
#endif
namespace {
namespace fs = vde::fs;
using vde::plugin::CaeSolverInfo;
using vde::plugin::CamStrategyInfo;
using vde::plugin::FormatImportResult;
using vde::plugin::PluginManager;
constexpr const char* kCaePluginId = "com.vde.sample.cae";
constexpr const char* kCamPluginId = "com.vde.sample.cam_post";
constexpr const char* kAbi11PluginId = "com.vde.test.abi11";
std::string temp_path(const char* name) { return std::string(VDE_TEST_TEMP_DIR) + name; }
bool write_text_file(const std::string& path, const std::string& text) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out.good()) return false;
out.write(text.data(), static_cast<std::streamsize>(text.size()));
out.close();
return out.good();
}
std::string read_text_file(const std::string& path) {
std::ifstream in(path, std::ios::binary);
if (!in.good()) return {};
return std::string((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
}
bool near_rel(double a, double b, double rel) {
const double scale = std::max(std::abs(a), std::abs(b));
if (scale <= 0.0) return std::abs(a - b) <= rel;
return std::abs(a - b) / scale <= rel;
}
int normalize_exit_code(int raw) {
#ifdef _WIN32
return raw;
#else
if (raw < 0) return raw;
if (WIFEXITED(raw)) return WEXITSTATUS(raw);
return -1;
#endif
}
/// 运行命令并把 stdout/stderr 重定向到文件(避免 popen 兼容性问题)
int run_command(const std::string& command, const std::string& log_path) {
#ifdef _WIN32
// cmd.exe 的 /c 引号规则:命令以引号开头时必须整体再包一层引号,
// 否则会报 "The filename, directory name, or volume label syntax is incorrect."
const std::string full =
"cmd /c \"" + command + " > \"" + log_path + "\" 2>&1\"";
#else
const std::string full = command + " > \"" + log_path + "\" 2>&1";
#endif
return normalize_exit_code(std::system(full.c_str()));
}
std::string quoted(const std::string& text) { return "\"" + text + "\""; }
// ── 立方体 ASCII STL 夹具 ──
struct CubeMesh {
std::vector<double> positions; // 3×8
std::vector<uint32_t> indices; // 3×12
};
CubeMesh make_cube(double w, double h, double d) {
const double x = w * 0.5, y = h * 0.5, z = d * 0.5;
CubeMesh mesh;
mesh.positions = {-x, -y, -z, x, -y, -z, x, y, -z, -x, y, -z,
-x, -y, z, x, -y, z, x, y, z, -x, y, z};
mesh.indices = {0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4,
1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7};
return mesh;
}
std::string cube_to_stl_ascii(const CubeMesh& mesh) {
std::string out = "solid vde_p2_cube\n";
char line[256];
for (std::size_t t = 0; t + 2 < mesh.indices.size(); t += 3) {
out += " facet normal 0 0 1\n outer loop\n";
for (int k = 0; k < 3; ++k) {
const uint32_t index = mesh.indices[t + static_cast<std::size_t>(k)];
std::snprintf(line, sizeof(line), " vertex %.17g %.17g %.17g\n",
mesh.positions[3 * index], mesh.positions[3 * index + 1],
mesh.positions[3 * index + 2]);
out += line;
}
out += " endloop\n endfacet\n";
}
out += "endsolid vde_p2_cube\n";
return out;
}
// ── 夹具:宿主服务 + 管理器重置 ──
class PluginExtensionsFixture : public ::testing::Test {
protected:
void SetUp() override { host_ = vde::plugin::make_geometry_host_services(); }
void TearDown() override {
PluginManager::instance().clear();
vde::plugin::release_geometry_host_services(&host_);
}
void reset_manager() {
PluginManager& manager = PluginManager::instance();
manager.clear();
manager.set_host_services(host_);
manager.clear_search_paths();
if (VDE_PLUGIN_DIRS[0] != '\0') manager.add_search_path(VDE_PLUGIN_DIRS);
manager.scan_search_paths();
}
bool load(const std::string& id, std::string* error) {
return PluginManager::instance().load(id, error);
}
/// 宿主侧序列化一个盒体,返回 VDE 序列化字节
std::string serialize_box(double w, double h, double d) {
VdeBody body = host_.body_create_box(w, h, d);
if (!body) return {};
VdeBuffer buffer{nullptr, 0};
if (host_.body_serialize(body, &buffer) != VDE_PLUGIN_OK) {
host_.body_destroy(body);
return {};
}
std::string bytes(static_cast<const char*>(buffer.data), buffer.size);
host_.free_buffer(buffer.data);
host_.body_destroy(body);
return bytes;
}
VdePluginHost host_{};
};
} // namespace
// ═══════════════════════════════════════════════════════════
// 1. ABI 1.2:CAE 求解器扩展点
// ═══════════════════════════════════════════════════════════
TEST_F(PluginExtensionsFixture, CaeSolverRegistrationAndSolve) {
ASSERT_EQ(VDE_PLUGIN_ABI_MAJOR, 1);
ASSERT_EQ(VDE_PLUGIN_ABI_MINOR, 9); // ABI 1.6(P4 optimizer/io_batch run_v2 扩展点)
reset_manager();
std::string error;
ASSERT_TRUE(load(kCaePluginId, &error)) << error;
const auto solvers = PluginManager::instance().cae_solvers();
ASSERT_EQ(solvers.size(), 1u);
EXPECT_EQ(solvers[0].plugin_id, kCaePluginId);
EXPECT_EQ(solvers[0].solver_id, "fea.linear_static");
EXPECT_NE(solvers[0].capabilities_json.find("element_types"), std::string::npos);
EXPECT_TRUE(PluginManager::instance().capabilities().has(
"cae_solver:fea.linear_static"));
const auto manifest = PluginManager::instance().manifest(kCaePluginId);
ASSERT_TRUE(manifest.has_value());
EXPECT_STREQ(vde::plugin::plugin_kind_name(manifest->kind), "cae_solver");
const std::string model = serialize_box(20.0, 30.0, 40.0);
ASSERT_FALSE(model.empty());
std::string result;
ASSERT_TRUE(PluginManager::instance().solve_cae(
"fea.linear_static", model.data(), model.size(),
"{\"youngs_modulus\":200000000000,\"load\":5000}", &result, &error))
<< error;
EXPECT_NE(result.find("\"solver_id\":\"fea.linear_static\""), std::string::npos) << result;
EXPECT_NE(result.find("\"ok\":true"), std::string::npos) << result;
EXPECT_NE(result.find("24000"), std::string::npos) << result; // 体积 20*30*40
EXPECT_NE(result.find("axial_stress"), std::string::npos) << result;
// 截面积 20*30=600,载荷 5000 → 应力 ≈ 8.333
const double stress = 5000.0 / 600.0;
char expected_stress[64];
std::snprintf(expected_stress, sizeof(expected_stress), "%.6g", stress);
EXPECT_NE(result.find(expected_stress), std::string::npos) << result;
}
TEST_F(PluginExtensionsFixture, CaeSolverFailureIsolation) {
reset_manager();
std::string error;
ASSERT_TRUE(load(kCaePluginId, &error)) << error;
const std::string model = serialize_box(10.0, 10.0, 10.0);
ASSERT_FALSE(model.empty());
// 未知 solver
std::string result;
EXPECT_FALSE(PluginManager::instance().solve_cae("fea.does_not_exist", model.data(),
model.size(), "", &result, &error));
EXPECT_FALSE(error.empty());
EXPECT_NE(error.find("not registered"), std::string::npos) << error;
// 坏模型数据:插件返回错误(宿主失败隔离,不崩溃)
error.clear();
const char* garbage = "this-is-not-vde-serialized-data";
EXPECT_FALSE(PluginManager::instance().solve_cae(
"fea.linear_static", garbage, std::strlen(garbage), "", &result, &error));
EXPECT_FALSE(error.empty());
// 失败后合法调用仍可用(隔离)
error.clear();
EXPECT_TRUE(PluginManager::instance().solve_cae("fea.linear_static", model.data(),
model.size(), "", &result, &error))
<< error;
EXPECT_NE(result.find("\"ok\":true"), std::string::npos);
}
// ═══════════════════════════════════════════════════════════
// 2. ABI 1.2:CAM 策略扩展点
// ═══════════════════════════════════════════════════════════
TEST_F(PluginExtensionsFixture, CamStrategyRegistrationAndInvoke) {
reset_manager();
std::string error;
ASSERT_TRUE(load(kCamPluginId, &error)) << error;
const auto strategies = PluginManager::instance().cam_strategies();
ASSERT_EQ(strategies.size(), 1u);
EXPECT_EQ(strategies[0].plugin_id, kCamPluginId);
EXPECT_EQ(strategies[0].strategy_id, "cam.post.gcode");
EXPECT_EQ(strategies[0].postprocessor_id, "fanuc");
EXPECT_EQ(strategies[0].machine_id, "generic-3axis");
EXPECT_TRUE(PluginManager::instance().capabilities().has("cam_strategy:post.gcode"));
const std::string model = serialize_box(20.0, 30.0, 40.0);
ASSERT_FALSE(model.empty());
std::string gcode;
ASSERT_TRUE(PluginManager::instance().invoke_cam(
"cam.post.gcode", model.data(), model.size(),
"{\"stepover\":5,\"feed\":300}", &gcode, &error))
<< error;
EXPECT_NE(gcode.find("G21 G90"), std::string::npos) << gcode;
EXPECT_NE(gcode.find("G1 X"), std::string::npos) << gcode;
EXPECT_NE(gcode.find("M30"), std::string::npos) << gcode;
EXPECT_NE(gcode.find("; stock: X[-10,10]"), std::string::npos) << gcode;
EXPECT_NE(gcode.find("F300"), std::string::npos) << gcode;
}
TEST_F(PluginExtensionsFixture, CamStrategyFailureIsolation) {
reset_manager();
std::string error;
ASSERT_TRUE(load(kCamPluginId, &error)) << error;
const std::string model = serialize_box(10.0, 10.0, 10.0);
ASSERT_FALSE(model.empty());
std::string gcode;
EXPECT_FALSE(PluginManager::instance().invoke_cam("cam.post.unknown", model.data(),
model.size(), "", &gcode, &error));
EXPECT_FALSE(error.empty());
EXPECT_NE(error.find("not registered"), std::string::npos) << error;
error.clear();
const char* garbage = "garbage-model";
EXPECT_FALSE(PluginManager::instance().invoke_cam(
"cam.post.gcode", garbage, std::strlen(garbage), "", &gcode, &error));
EXPECT_FALSE(error.empty());
error.clear();
EXPECT_TRUE(PluginManager::instance().invoke_cam(
"cam.post.gcode", model.data(), model.size(), "", &gcode, &error))
<< error;
EXPECT_NE(gcode.find("M30"), std::string::npos);
}
// ═══════════════════════════════════════════════════════════
// 3. ABI 1.1 旧插件兼容 + 卸载清理
// ═══════════════════════════════════════════════════════════
TEST_F(PluginExtensionsFixture, OldAbi11PluginLoadsAndWorks) {
reset_manager();
const auto manifest = PluginManager::instance().manifest(kAbi11PluginId);
ASSERT_TRUE(manifest.has_value()) << "ABI 1.1 兼容插件未发现(构建产物缺失?)";
EXPECT_EQ(manifest->abi_major, 1);
EXPECT_EQ(manifest->abi_minor, 1);
std::string error;
ASSERT_TRUE(load(kAbi11PluginId, &error)) << error;
EXPECT_TRUE(PluginManager::instance().is_loaded(kAbi11PluginId));
const auto formats = PluginManager::instance().formats();
bool has_ab11 = false;
for (const auto& format : formats)
if (format.format_id == "ab11") has_ab11 = true;
EXPECT_TRUE(has_ab11);
const std::string path = temp_path("p2_old_abi11.ab11");
ASSERT_TRUE(write_text_file(path, "ab11 1 2 3 4\n"));
FormatImportResult imported;
ASSERT_TRUE(PluginManager::instance().import_file(path, &imported))
<< PluginManager::instance().last_error();
ASSERT_EQ(imported.bodies.size(), 1u);
VdeBodyInfo info{};
info.struct_size = sizeof(VdeBodyInfo);
ASSERT_EQ(host_.body_query(imported.bodies[0], &info), VDE_PLUGIN_OK);
EXPECT_EQ(info.num_faces, 6u);
EXPECT_TRUE(near_rel(info.volume, 24.0, 1e-9)) << info.volume;
host_.body_destroy(imported.bodies[0]);
std::remove(path.c_str());
}
TEST_F(PluginExtensionsFixture, UnloadClearsCaeCamRegistrations) {
reset_manager();
std::string error;
ASSERT_TRUE(load(kCaePluginId, &error)) << error;
ASSERT_TRUE(load(kCamPluginId, &error)) << error;
EXPECT_EQ(PluginManager::instance().cae_solvers().size(), 1u);
EXPECT_EQ(PluginManager::instance().cam_strategies().size(), 1u);
ASSERT_TRUE(PluginManager::instance().unload(kCaePluginId, &error)) << error;
EXPECT_TRUE(PluginManager::instance().cae_solvers().empty());
EXPECT_EQ(PluginManager::instance().cam_strategies().size(), 1u);
EXPECT_FALSE(PluginManager::instance().capabilities().has(
"cae_solver:fea.linear_static"));
EXPECT_TRUE(PluginManager::instance().capabilities().has("cam_strategy:post.gcode"));
// 已卸载插件调用 → 明确失败
std::string result;
EXPECT_FALSE(PluginManager::instance().solve_cae("fea.linear_static", "x", 1, "",
&result, &error));
EXPECT_FALSE(error.empty());
ASSERT_TRUE(PluginManager::instance().unload(kCamPluginId, &error)) << error;
EXPECT_TRUE(PluginManager::instance().cam_strategies().empty());
EXPECT_FALSE(PluginManager::instance().capabilities().has("cam_strategy:post.gcode"));
EXPECT_EQ(PluginManager::instance().capabilities().size(), 0u);
}
// ═══════════════════════════════════════════════════════════
// 4. 进程外服务协议(P2 草案):runner 发现 + 调用 + 超时
// ═══════════════════════════════════════════════════════════
namespace {
std::string external_runner_path() {
#ifdef _WIN32
return std::string(VDE_PLUGIN_EXTERNAL_DIR) + "/runner/vde_service_runner.exe";
#else
return std::string(VDE_PLUGIN_EXTERNAL_DIR) + "/runner/vde_service_runner";
#endif
}
std::string external_service_manifest() {
return std::string(VDE_PLUGIN_EXTERNAL_DIR) + "/sample_stl_converter/vde-service.json";
}
} // namespace
TEST_F(PluginExtensionsFixture, ExternalServiceRunnerDiscovery) {
const std::string runner = external_runner_path();
ASSERT_TRUE(fs::is_regular_file(runner)) << runner;
const std::string log = temp_path("p2_external_list.log");
const int exit_code = run_command(quoted(runner) + " --list " +
quoted(VDE_PLUGIN_EXTERNAL_DIR),
log);
const std::string output = read_text_file(log);
std::remove(log.c_str());
EXPECT_EQ(exit_code, 0) << output;
EXPECT_NE(output.find("com.vde.example.stl_converter"), std::string::npos) << output;
// P3-9:新增 sample_gcs_solver 后示例服务数量增加;按存在性断言(避免脆弱的固定计数)
EXPECT_NE(output.find("com.vde.example.gcs_solver"), std::string::npos) << output;
EXPECT_NE(output.find("discovered "), std::string::npos) << output;
}
TEST_F(PluginExtensionsFixture, ExternalServiceRunnerEndToEnd) {
const std::string runner = external_runner_path();
ASSERT_TRUE(fs::is_regular_file(runner)) << runner;
ASSERT_TRUE(fs::is_regular_file(external_service_manifest()))
<< external_service_manifest();
const CubeMesh cube = make_cube(2.0, 2.0, 2.0);
const std::string input = temp_path("p2_external_input.stl");
const std::string output_obj = temp_path("p2_external_output.obj");
const std::string request = temp_path("p2_external_request.json");
const std::string response_log = temp_path("p2_external_response.log");
ASSERT_TRUE(write_text_file(input, cube_to_stl_ascii(cube)));
std::string request_json = "{";
request_json += "\"protocol\":\"vde-service/0.1\",";
request_json += "\"request_id\":\"p2-e2e-1\",";
request_json += "\"operation\":\"stl_to_obj\",";
request_json += "\"input\":\"" + input + "\",";
request_json += "\"output\":\"" + output_obj + "\"";
request_json += "}";
ASSERT_TRUE(write_text_file(request, request_json));
const int exit_code = run_command(
quoted(runner) + " --run --manifest " + quoted(external_service_manifest()) +
" --request " + quoted(request) + " --timeout-ms 15000",
response_log);
const std::string log_text = read_text_file(response_log);
const std::string obj_text = read_text_file(output_obj);
std::remove(response_log.c_str());
std::remove(request.c_str());
std::remove(output_obj.c_str());
EXPECT_EQ(exit_code, 0) << log_text;
EXPECT_NE(log_text.find("\"status\":\"ok\""), std::string::npos) << log_text;
EXPECT_NE(log_text.find("\"triangles\":12"), std::string::npos) << log_text;
EXPECT_FALSE(obj_text.empty()) << log_text;
EXPECT_NE(obj_text.find("v "), std::string::npos);
EXPECT_NE(obj_text.find("f 1 2 3"), std::string::npos);
}
TEST_F(PluginExtensionsFixture, ExternalServiceRunnerTimeoutAndProtocolErrors) {
const std::string runner = external_runner_path();
ASSERT_TRUE(fs::is_regular_file(runner)) << runner;
// 超时:服务端 sleep_ms 远大于 runner --timeout-ms → 强制终止,退出码 4
const std::string request = temp_path("p2_external_slow_request.json");
const std::string log = temp_path("p2_external_timeout.log");
const std::string input = temp_path("p2_external_slow_input.stl");
ASSERT_TRUE(write_text_file(input, cube_to_stl_ascii(make_cube(1.0, 1.0, 1.0))));
std::string request_json = "{";
request_json += "\"request_id\":\"p2-timeout\",\"operation\":\"stl_to_obj\",";
request_json += "\"input\":\"" + input + "\",";
request_json += "\"output\":\"" + temp_path("p2_external_slow_output.obj") + "\",";
request_json += "\"sleep_ms\":5000}";
ASSERT_TRUE(write_text_file(request, request_json));
int exit_code = run_command(
quoted(runner) + " --run --manifest " + quoted(external_service_manifest()) +
" --request " + quoted(request) + " --timeout-ms 300",
log);
std::string output = read_text_file(log);
EXPECT_EQ(exit_code, 4) << output;
EXPECT_NE(output.find("timeout"), std::string::npos) << output;
// 清单缺失 → 协议/清单错误退出码 3
const std::string missing_log = temp_path("p2_external_missing.log");
exit_code = run_command(quoted(runner) + " --run --manifest " +
quoted(temp_path("p2_missing_manifest.json")) +
" --request " + quoted(request),
missing_log);
output = read_text_file(missing_log);
EXPECT_EQ(exit_code, 3) << output;
EXPECT_NE(output.find("manifest"), std::string::npos) << output;
// 示例服务协议错误:未知 operation → 服务写 error 响应,runner 退出码 3
const std::string bad_request = temp_path("p2_external_bad_request.json");
ASSERT_TRUE(write_text_file(
bad_request,
"{\"request_id\":\"p2-bad\",\"operation\":\"unknown_op\",\"input\":\"" + input +
"\",\"output\":\"" + temp_path("p2_external_bad_output.obj") + "\"}"));
const std::string bad_log = temp_path("p2_external_bad.log");
exit_code = run_command(quoted(runner) + " --run --manifest " +
quoted(external_service_manifest()) + " --request " +
quoted(bad_request) + " --timeout-ms 15000",
bad_log);
output = read_text_file(bad_log);
EXPECT_EQ(exit_code, 3) << output;
EXPECT_NE(output.find("unsupported_operation"), std::string::npos) << output;
std::remove(request.c_str());
std::remove(log.c_str());
std::remove(input.c_str());
std::remove(missing_log.c_str());
std::remove(bad_request.c_str());
std::remove(bad_log.c_str());
}