Files
action_core/test/action_registry_test.cpp
duongtd 669c3f7c06 feat: ActionHandler pause/resume + kCancelled status + ABI version guard
- ActionStatus::kCancelled (new, string "CANCELLED"): the missing "stopped
  on request" terminal status — previously a cancelled action only had
  Running/Succeeded/Failed to report through, so move_base2's state
  machine couldn't tell a cancelled action from a failed one.
- ActionHandler::cancelNeedsTicks() (default false), pause(now) and
  resume(now) (default no-ops): lets a handler opt into "I need more
  ticks to actually stop" (device handshake) instead of being torn down
  immediately, and gives handlers a real pause/resume contract instead of
  move_base2 having to freeze/unfreeze them from outside.
- action_abi.h (new) + ACTION_CORE_EXPORT_HANDLER macro, same pattern as
  recovery_core commit 254c7fc: exports a version symbol next to the
  factory alias; action_registry.cpp refuses a handler .so whose version
  doesn't match instead of dlsym+reinterpret_cast blindly onto a grown
  vtable.
- frame_sampler / wait / noop handlers implement pause/resume via
  paused_at_ / started_at_ += (now - paused_at_) so their own internal
  timers don't count paused time; paused_ is reset on start() so a reused
  handler instance can't come up already paused.
- test/plugins/stale_abi_action_handler.cpp (new) for the registry refusal
  test.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 22:07:00 +07:00

286 lines
9.2 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm đường nạp plugin thật: YAML -> library_path -> Boost.DLL -> configure -> tra theo actionType.
*
* Đây là đường mà runtime đi, nên nó phải được kiểm bằng `.so` thật chứ không phải bằng handler
* dựng sẵn. Phần đăng ký trực tiếp (registerHandler) được kiểm riêng bên dưới bằng handler giả.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <robot/node_handle.h>
#include <action_core/action_registry.h>
namespace
{
using action_core::ActionHandler;
using action_core::ActionRegistry;
using action_core::ActionStatus;
using action_core::ActionTick;
/// @brief Handler giả, không qua Boost.DLL — dùng cho phần contract của registerHandler().
class FakeHandler final : public ActionHandler
{
public:
explicit FakeHandler(std::vector<std::string> types) : types_(std::move(types))
{
}
bool configure(const std::string&, const action_core::ActionContext&,
robot::NodeHandle&) override
{
return true;
}
std::vector<std::string> supportedActionTypes() const override
{
return types_;
}
bool start(const robot_protocol_msgs::Action&, const robot::Time&) override
{
return true;
}
ActionTick update(const robot::Time&) override
{
ActionTick tick;
tick.status = ActionStatus::kSucceeded;
return tick;
}
void cancel() override
{
}
private:
std::vector<std::string> types_;
};
robot_protocol_msgs::Action makeAction(const std::string& type)
{
robot_protocol_msgs::Action action;
action.actionType = type;
action.actionId = type + "-1";
return action;
}
// ================================================================================================
// Đường nạp thật
// ================================================================================================
TEST(ActionRegistry, LoadsDeclaredHandlersAndRoutesByActionType)
{
robot::NodeHandle nh;
ActionRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "actions"));
EXPECT_EQ(registry.size(), 2u);
// Định tuyến theo TÊN, không theo thứ tự khai — một handler nhận nhiều actionType.
ASSERT_NE(registry.find("wait"), nullptr);
ASSERT_NE(registry.find("pick"), nullptr);
ASSERT_NE(registry.find("charge"), nullptr);
EXPECT_EQ(registry.find("wait"), registry.find("pick"));
EXPECT_NE(registry.find("wait"), registry.find("charge"));
EXPECT_EQ(registry.find("khong-ton-tai"), nullptr);
}
TEST(ActionRegistry, LoadedHandlerActuallyRuns)
{
robot::NodeHandle nh;
ActionRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "actions"));
ActionHandler* handler = registry.find("wait");
ASSERT_NE(handler, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(handler->start(makeAction("wait"), now));
// `quick` có duration 0 -> xong ngay ở tick đầu.
const ActionTick tick = handler->update(now);
EXPECT_EQ(tick.status, ActionStatus::kSucceeded);
EXPECT_FALSE(tick.message.empty());
}
TEST(ActionRegistry, SlowHandlerStaysRunningUntilItsDuration)
{
robot::NodeHandle nh;
ActionRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "actions"));
ActionHandler* handler = registry.find("charge");
ASSERT_NE(handler, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(handler->start(makeAction("charge"), now));
EXPECT_EQ(handler->update(now).status, ActionStatus::kRunning);
EXPECT_EQ(handler->update(now + robot::Duration(0.5)).status, ActionStatus::kRunning);
EXPECT_EQ(handler->update(now + robot::Duration(1.0)).status, ActionStatus::kSucceeded);
}
TEST(ActionRegistry, HandlerTimeoutIsTheHandlersOwnResponsibility)
{
robot::NodeHandle nh;
ActionRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "actions"));
ActionHandler* handler = registry.find("charge");
ASSERT_NE(handler, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(handler->start(makeAction("charge"), now));
// Tầng 1 của contract 3 tầng: handler tự cắt, không chờ action_patience của state machine.
EXPECT_EQ(handler->update(now + robot::Duration(10.0)).status, ActionStatus::kFailed);
}
// ================================================================================================
// Đường lỗi — mỗi ca phải fail được, không được im lặng
// ================================================================================================
TEST(ActionRegistry, MissingHandlerListIsNotAnError)
{
// Hệ không có thiết bị nào thì mọi mission đều nav-only. Caller mới là chỗ từ chối yêu cầu mang
// action, và nó từ chối kèm lý do rõ ràng.
robot::NodeHandle nh;
ActionRegistry registry;
EXPECT_TRUE(registry.loadFromConfig(nh, "actions_empty"));
EXPECT_EQ(registry.size(), 0u);
EXPECT_EQ(registry.find("wait"), nullptr);
}
TEST(ActionRegistry, RejectsSecondHandlerClaimingTheSameActionType)
{
robot::NodeHandle nh;
ActionRegistry registry;
// Định tuyến khi đó phụ thuộc thứ tự dòng trong YAML — không ai đọc config mà đoán ra được.
EXPECT_FALSE(registry.loadFromConfig(nh, "actions_duplicate_type"));
// Handler đầu vẫn dùng được: một entry hỏng không xoá các entry còn lại.
EXPECT_EQ(registry.size(), 1u);
EXPECT_NE(registry.find("pick"), nullptr);
}
TEST(ActionRegistry, RejectsHandlerThatCouldNeverFinish)
{
robot::NodeHandle nh;
ActionRegistry registry;
// hang=true + timeout=0 nghĩa là action chạy vĩnh viễn — đúng thứ contract cấm, và handler tự
// từ chối ở configure().
EXPECT_FALSE(registry.loadFromConfig(nh, "actions_hang_forever"));
EXPECT_EQ(registry.size(), 0u);
}
TEST(ActionRegistry, ReportsMissingLibraryPath)
{
robot::NodeHandle nh;
ActionRegistry registry;
// Thiếu `library_path` là nguyên nhân phổ biến nhất của "plugin build xong nhưng runtime báo
// không tìm thấy".
EXPECT_FALSE(registry.loadFromConfig(nh, "actions_missing_library"));
EXPECT_EQ(registry.size(), 0u);
}
TEST(ActionRegistry, RefusesAPluginBuiltForAnotherAbiVersion)
{
// 2026-09-11: header ActionHandler thêm virtual; plugin build với header cũ có vtable ngắn hơn và
// sẽ crash ở lời gọi pause(). Registry tra `<Type>_abi` trước factory và từ chối khi lệch.
robot::NodeHandle nh;
ActionRegistry registry;
EXPECT_FALSE(registry.loadFromConfig(nh, "actions_stale_abi"));
EXPECT_EQ(registry.size(), 0u) << "a plugin with a mismatching _abi must not be registered";
}
TEST(ActionRegistry, RefusesAPluginWithoutAnAbiSymbol)
{
robot::NodeHandle nh;
ActionRegistry registry;
EXPECT_FALSE(registry.loadFromConfig(nh, "actions_no_abi"));
EXPECT_EQ(registry.size(), 0u) << "a plugin built before the ABI guard must not be registered";
}
// ================================================================================================
// Contract của registerHandler
// ================================================================================================
TEST(ActionRegistry, RejectsNullHandler)
{
ActionRegistry registry;
EXPECT_FALSE(registry.registerHandler(nullptr));
}
TEST(ActionRegistry, RejectsHandlerWithNoActionType)
{
ActionRegistry registry;
EXPECT_FALSE(registry.registerHandler(std::make_shared<FakeHandler>(std::vector<std::string>{})));
}
TEST(ActionRegistry, RejectsEmptyActionTypeString)
{
ActionRegistry registry;
EXPECT_FALSE(registry.registerHandler(
std::make_shared<FakeHandler>(std::vector<std::string>{ "pick", "" })));
// Từ chối phải là NGUYÊN TỬ: 'pick' đứng trước chuỗi rỗng không được lọt vào bảng.
EXPECT_EQ(registry.size(), 0u);
EXPECT_EQ(registry.find("pick"), nullptr);
}
TEST(ActionRegistry, ActionTypesListsEveryClaimedType)
{
ActionRegistry registry;
ASSERT_TRUE(registry.registerHandler(
std::make_shared<FakeHandler>(std::vector<std::string>{ "pick", "drop" })));
ASSERT_TRUE(
registry.registerHandler(std::make_shared<FakeHandler>(std::vector<std::string>{ "wait" })));
const std::vector<std::string> types = registry.actionTypes();
ASSERT_EQ(types.size(), 3u);
EXPECT_EQ(registry.size(), 2u); // size() đếm HANDLER, không đếm actionType
}
TEST(ActionRegistry, ClearDropsEverything)
{
ActionRegistry registry;
ASSERT_TRUE(
registry.registerHandler(std::make_shared<FakeHandler>(std::vector<std::string>{ "pick" })));
registry.clear();
EXPECT_EQ(registry.size(), 0u);
EXPECT_EQ(registry.find("pick"), nullptr);
}
} // namespace
int main(int argc, char** argv)
{
// Trỏ vào cây config và thư mục .so của gói. `overwrite = 0` để shell vẫn override được khi cần
// chạy tay với cây khác — cùng cách `test_costmap` làm.
#ifdef ACTION_CORE_TEST_CONFIG_DIR
setenv("PNKX_NAV_CORE_CONFIG_DIR", ACTION_CORE_TEST_CONFIG_DIR, 0);
#endif
#ifdef ACTION_CORE_TEST_LIBRARY_DIR
setenv("PNKX_NAV_CORE_LIBRARY_PATH", ACTION_CORE_TEST_LIBRARY_DIR, 0);
#endif
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}