first commit

This commit is contained in:
2026-08-10 10:52:16 +07:00
commit 8e2a4182c5
20 changed files with 3413 additions and 0 deletions

View File

@@ -0,0 +1,267 @@
/*********************************************************************
*
* 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);
}
// ================================================================================================
// 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();
}

View File

@@ -0,0 +1,128 @@
# Config CHỈ dùng cho test của gói. Bản runtime nằm trong cây config của nav core (C2) — sửa tham
# số vận hành thì sửa ở đó, đừng sửa bản này.
#
# Chạy test kèm: PNKX_NAV_CORE_CONFIG_DIR=src/AMR_T800/Test/action_core/test/config
# (binary test tự setenv qua ACTION_CORE_TEST_CONFIG_DIR nên chạy được thẳng qua ctest.)
actions:
handlers:
- {name: quick, type: NoopActionHandler}
- {name: slow, type: NoopActionHandler}
quick:
action_types: [wait, pick]
duration: 0.0 # [s] xong ngay ở tick đầu
timeout: 30.0 # [s] timeout tầng 1, của chính handler
slow:
action_types: [charge]
duration: 1.0 # [s]
timeout: 10.0 # [s]
# Hai handler cùng nhận một actionType: registry phải TỪ CHỐI cái thứ hai thay vì ghi đè im lặng.
actions_duplicate_type:
handlers:
- {name: first, type: NoopActionHandler}
- {name: second, type: NoopActionHandler}
first:
action_types: [pick]
second:
action_types: [pick]
# Handler treo vĩnh viễn mà lại tắt timeout — configure() phải từ chối.
actions_hang_forever:
handlers:
- {name: ghost, type: NoopActionHandler}
ghost:
action_types: [wait]
hang: true
timeout: 0.0
# Type không khai library_path ở đâu cả.
actions_missing_library:
handlers:
- {name: nowhere, type: MissingActionHandler}
# Không có khoá `handlers`: hợp lệ, chỉ nghĩa là hệ không có thiết bị nào.
actions_empty:
something_else: 1
# Bộ handler default, mỗi cái một namespace riêng để test nạp độc lập.
actions_wait:
handlers:
- {name: waiter, type: WaitActionHandler}
waiter:
action_types: [wait]
default_duration: 0.0 # [s] khi order không kèm tham số `duration`
max_duration: 5.0 # [s] trần cứng; vượt trần thì action THẤT BẠI, không bị cắt ngắn
actions_log:
handlers:
- {name: reporter, type: LogReportActionHandler}
reporter:
action_types: [logReport]
# Handler dò — lấy mẫu frame thô, lọc, ghi ra frame ổn định.
actions_detect:
handlers:
- {name: detect, type: FrameSamplerActionHandler}
detect:
action_types: [DetectCharger]
output_frame: dock_target
settle_delay: 0.2 # [s]
sample_window: 1.0 # [s]
min_samples: 10
max_spread_xy: 0.03 # [m]
max_spread_yaw: 0.05 # [rad]
timeout: 5.0 # [s]
# output_frame trùng input_frame -> configure() phải từ chối.
actions_detect_same_frame:
handlers:
- {name: detect, type: FrameSamplerActionHandler}
detect:
action_types: [DetectCharger]
input_frame: charger_raw
output_frame: charger_raw
# timeout ngắn hơn settle_delay + sample_window -> action LUÔN hỏng, phải chặn lúc boot.
actions_detect_bad_timeout:
handlers:
- {name: detect, type: FrameSamplerActionHandler}
detect:
action_types: [DetectCharger]
output_frame: dock_target
settle_delay: 1.0
sample_window: 2.0
timeout: 1.0
# Bypass perception có chủ đích cho test sim: pose giả là offset trong base_link nhưng output vẫn
# phải là frame tĩnh trong map, nếu không đích sẽ chạy theo robot và docking không thể hoàn tất.
actions_detect_simulated:
handlers:
- {name: detect, type: FrameSamplerActionHandler}
detect:
action_types: [DetectPallet]
output_frame: dock_target
use_simulated_goal: true
simulated_parent_frame: base_link
simulated_offset_x: -1.5
simulated_offset_y: 0.2
simulated_offset_yaw: 0.0
NoopActionHandler:
library_path: libaction_core_noop_action_handler
FrameSamplerActionHandler:
library_path: libaction_core_frame_sampler_action_handler
WaitActionHandler:
library_path: libaction_core_wait_action_handler
LogReportActionHandler:
library_path: libaction_core_log_report_action_handler

352
test/frame_sampler_test.cpp Normal file
View File

@@ -0,0 +1,352 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm handler dò: lấy mẫu TF nhiễu, lọc, ghi ra frame ổn định.
*
* Trọng tâm là ba thứ mà một bản lọc viết vội sẽ sai: gộp góc quanh ±π, chống outlier, và cổng chất
* lượng khi dữ liệu tản. Cả ba đều dẫn tới robot lùi vào sai chỗ mà không có lỗi nào được báo.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <cstdlib>
#include <memory>
#include <string>
#include <robot/node_handle.h>
#include <tf3/buffer_core.h>
#include <action_core/action_registry.h>
namespace
{
using action_core::ActionContext;
using action_core::ActionHandler;
using action_core::ActionRegistry;
using action_core::ActionStatus;
constexpr const char* kGlobalFrame = "map";
constexpr const char* kRawFrame = "charger_raw";
constexpr const char* kOutFrame = "dock_target";
/// tf3::Time chỉ có ctor (sec, nsec) — không có ctor từ double như robot::Time.
tf3::Time toTf3Time(double t)
{
const uint32_t sec = static_cast<uint32_t>(t);
return tf3::Time(sec, static_cast<uint32_t>((t - sec) * 1e9));
}
robot_protocol_msgs::Action makeAction(const std::string& frame = kRawFrame,
const std::string& action_type = "DetectCharger")
{
robot_protocol_msgs::Action action;
action.actionType = action_type;
action.actionId = "detect-1";
if (!frame.empty())
{
robot_protocol_msgs::ActionParameter p;
p.key = "goal_frame";
p.value = frame;
action.actionParameters.push_back(p);
}
return action;
}
/// @brief Rig: một buffer TF thật + handler nạp qua đúng đường Boost.DLL.
class Rig
{
public:
explicit Rig(const std::string& ns = "actions_detect",
const std::string& action_type = "DetectCharger")
{
ctx.tf = &tf;
ctx.global_frame = kGlobalFrame;
registry.setContext(ctx);
loaded = registry.loadFromConfig(nh, ns);
handler = registry.find(action_type);
}
/// @brief Bơm một mẫu thô vào buffer. `stamp` phải TĂNG, nếu không mẫu bị bỏ (đúng contract).
void pushSample(double x, double y, double yaw, double stamp_s)
{
tf3::TransformStampedMsg t;
t.header.stamp = toTf3Time(stamp_s);
t.header.frame_id = kGlobalFrame;
t.child_frame_id = kRawFrame;
t.transform.translation.x = x;
t.transform.translation.y = y;
t.transform.rotation.z = std::sin(yaw * 0.5);
t.transform.rotation.w = std::cos(yaw * 0.5);
tf.setTransform(t, "test", /*is_static=*/false);
}
void pushTransform(const std::string& parent, const std::string& child, double x, double y,
double yaw, double stamp_s)
{
tf3::TransformStampedMsg t;
t.header.stamp = toTf3Time(stamp_s);
t.header.frame_id = parent;
t.child_frame_id = child;
t.transform.translation.x = x;
t.transform.translation.y = y;
t.transform.rotation.z = std::sin(yaw * 0.5);
t.transform.rotation.w = std::cos(yaw * 0.5);
tf.setTransform(t, "test", /*is_static=*/false);
}
bool readOutput(double& x, double& y, double& yaw)
{
try
{
const auto t = tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time());
x = t.transform.translation.x;
y = t.transform.translation.y;
const auto& q = t.transform.rotation;
yaw = std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
return true;
}
catch (const std::exception&)
{
return false;
}
}
robot::NodeHandle nh;
tf3::BufferCore tf;
ActionContext ctx;
ActionRegistry registry;
ActionHandler* handler = nullptr;
bool loaded = false;
};
/// @brief Chạy handler qua trọn một lượt: bơm @p n mẫu quanh (x,y,yaw) với nhiễu @p noise.
ActionStatus runSampling(Rig& rig, int n, double x, double y, double yaw, double noise_xy,
double noise_yaw = 0.0)
{
const robot::Time t0 = robot::Time(100.0);
EXPECT_TRUE(rig.handler->start(makeAction(), t0));
// settle_delay = 0.2, sample_window = 1.0 trong config test.
double stamp = 100.0;
ActionStatus last = ActionStatus::kRunning;
for (int i = 0; i < n; ++i)
{
stamp += 0.01;
// Nhiễu răng cưa: đổi dấu mỗi mẫu — biên độ đúng bằng `noise`, không phụ thuộc bộ sinh ngẫu nhiên.
const double s = (i % 2 == 0) ? 1.0 : -1.0;
rig.pushSample(x + s * noise_xy, y - s * noise_xy, yaw + s * noise_yaw, stamp);
last = rig.handler->update(robot::Time(100.3 + i * 0.01)).status;
if (last != ActionStatus::kRunning)
{
return last;
}
}
// Quá cửa sổ lấy mẫu -> handler chốt kết quả.
return rig.handler->update(robot::Time(101.5)).status;
}
// ================================================================================================
// Đường thành công
// ================================================================================================
TEST(FrameSampler, LoadsAndPublishesAStableFrame)
{
Rig rig;
ASSERT_TRUE(rig.loaded);
ASSERT_NE(rig.handler, nullptr);
EXPECT_EQ(runSampling(rig, 30, 2.0, 1.0, 0.5, 0.002), ActionStatus::kSucceeded);
double x = 0.0, y = 0.0, yaw = 0.0;
ASSERT_TRUE(rig.readOutput(x, y, yaw));
EXPECT_NEAR(x, 2.0, 0.005);
EXPECT_NEAR(y, 1.0, 0.005);
EXPECT_NEAR(yaw, 0.5, 0.01);
}
TEST(FrameSampler, MedianRejectsAnOutlier)
{
Rig rig;
ASSERT_NE(rig.handler, nullptr);
const robot::Time t0 = robot::Time(100.0);
ASSERT_TRUE(rig.handler->start(makeAction(), t0));
double stamp = 100.0;
for (int i = 0; i < 30; ++i)
{
stamp += 0.01;
// Một mẫu nhận nhầm chân kệ khác, lệch 1 m. Trung bình sẽ bị kéo ~3 cm; trung vị thì không.
const double x = (i == 7) ? 3.0 : 2.0;
rig.pushSample(x, 1.0, 0.0, stamp);
rig.handler->update(robot::Time(100.3 + i * 0.01));
}
ASSERT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kSucceeded);
double x = 0.0, y = 0.0, yaw = 0.0;
ASSERT_TRUE(rig.readOutput(x, y, yaw));
EXPECT_NEAR(x, 2.0, 0.001) << "trung vị phải loại được outlier";
}
TEST(FrameSampler, AveragesYawAcrossTheWrapAround)
{
Rig rig;
ASSERT_NE(rig.handler, nullptr);
const robot::Time t0 = robot::Time(100.0);
ASSERT_TRUE(rig.handler->start(makeAction(), t0));
// Mẫu nằm hai bên đường cắt ±π. Trung bình SỐ HỌC cho ra ~0 — lệch 180°, robot vào trạm ngược đầu.
double stamp = 100.0;
for (int i = 0; i < 30; ++i)
{
stamp += 0.01;
const double yaw = (i % 2 == 0) ? (M_PI - 0.01) : (-M_PI + 0.01);
rig.pushSample(2.0, 1.0, yaw, stamp);
rig.handler->update(robot::Time(100.3 + i * 0.01));
}
ASSERT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kSucceeded);
double x = 0.0, y = 0.0, yaw = 0.0;
ASSERT_TRUE(rig.readOutput(x, y, yaw));
EXPECT_NEAR(std::fabs(yaw), M_PI, 0.02) << "gộp góc phải dùng vector đơn vị, không phải trung bình";
}
TEST(FrameSampler, SimulatedGoalIsFrozenInTheGlobalFrame)
{
Rig rig("actions_detect_simulated", "DetectPallet");
ASSERT_TRUE(rig.loaded);
ASSERT_NE(rig.handler, nullptr);
rig.pushTransform(kGlobalFrame, "base_link", 10.0, 5.0, M_PI_2, 100.0);
EXPECT_TRUE(rig.handler->start(makeAction("", "DetectPallet"), robot::Time(100.0)));
EXPECT_EQ(rig.handler->update(robot::Time(100.0)).status, ActionStatus::kSucceeded);
double x = 0.0, y = 0.0, yaw = 0.0;
ASSERT_TRUE(rig.readOutput(x, y, yaw));
EXPECT_NEAR(x, 9.8, 1e-6);
EXPECT_NEAR(y, 3.5, 1e-6);
EXPECT_NEAR(yaw, M_PI_2, 1e-6);
// Output là static trong map, không được chạy theo parent ở cycle sau.
rig.pushTransform(kGlobalFrame, "base_link", 20.0, 5.0, M_PI_2, 101.0);
ASSERT_TRUE(rig.readOutput(x, y, yaw));
EXPECT_NEAR(x, 9.8, 1e-6);
EXPECT_NEAR(y, 3.5, 1e-6);
}
// ================================================================================================
// Đường lỗi — mỗi ca phải fail được
// ================================================================================================
TEST(FrameSampler, FailsWhenDetectionIsTooScattered)
{
Rig rig;
ASSERT_NE(rig.handler, nullptr);
// max_spread_xy = 0.03 trong config test; nhiễu ±0.05 cho độ tản 0.1 m.
EXPECT_EQ(runSampling(rig, 30, 2.0, 1.0, 0.0, 0.05), ActionStatus::kFailed);
double x = 0.0, y = 0.0, yaw = 0.0;
EXPECT_FALSE(rig.readOutput(x, y, yaw)) << "dữ liệu tản thì KHÔNG được ghi frame nào";
}
TEST(FrameSampler, FailsWithTooFewSamples)
{
Rig rig;
ASSERT_NE(rig.handler, nullptr);
const robot::Time t0 = robot::Time(100.0);
ASSERT_TRUE(rig.handler->start(makeAction(), t0));
rig.pushSample(2.0, 1.0, 0.0, 100.5);
rig.handler->update(robot::Time(100.5));
// min_samples = 10 trong config test.
EXPECT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kFailed);
}
TEST(FrameSampler, DuplicateTimestampsDoNotCountAsSamples)
{
Rig rig;
ASSERT_NE(rig.handler, nullptr);
const robot::Time t0 = robot::Time(100.0);
ASSERT_TRUE(rig.handler->start(makeAction(), t0));
// TF cập nhật chậm hơn control loop: cùng một pose bị đọc 30 lần. Không lọc theo timestamp thì
// min_samples mất hết ý nghĩa và một mẫu duy nhất trông như ba mươi mẫu.
rig.pushSample(2.0, 1.0, 0.0, 100.5);
for (int i = 0; i < 30; ++i)
{
rig.handler->update(robot::Time(100.3 + i * 0.01));
}
EXPECT_EQ(rig.handler->update(robot::Time(101.5)).status, ActionStatus::kFailed);
}
TEST(FrameSampler, FailsWhenTheRawFrameNeverAppears)
{
Rig rig;
ASSERT_NE(rig.handler, nullptr);
const robot::Time t0 = robot::Time(100.0);
ASSERT_TRUE(rig.handler->start(makeAction(), t0));
EXPECT_EQ(rig.handler->update(robot::Time(100.5)).status, ActionStatus::kRunning);
// timeout = 5.0 trong config test.
EXPECT_EQ(rig.handler->update(robot::Time(105.1)).status, ActionStatus::kFailed);
}
TEST(FrameSampler, RefusesToStartWithoutAFrameParameter)
{
Rig rig;
ASSERT_NE(rig.handler, nullptr);
// Không có `goal_frame` và config cũng không khai `input_frame` -> không biết dò cái gì.
EXPECT_FALSE(rig.handler->start(makeAction(""), robot::Time(100.0)));
}
TEST(FrameSampler, RefusesToLoadWithoutATfBuffer)
{
// Handler cần TF; thiếu thì phải từ chối lúc NẠP, không phải lúc order đầu tiên tới.
robot::NodeHandle nh;
ActionRegistry registry; // context mặc định: tf == nullptr
EXPECT_FALSE(registry.loadFromConfig(nh, "actions_detect"));
EXPECT_EQ(registry.size(), 0u);
}
TEST(FrameSampler, RefusesOutputFrameEqualToInputFrame)
{
Rig rig("actions_detect_same_frame");
EXPECT_FALSE(rig.loaded) << "ghi đè chính frame thô là tranh chấp với bên publish nó";
EXPECT_EQ(rig.registry.size(), 0u);
}
TEST(FrameSampler, RefusesTimeoutShorterThanTheSamplingWindow)
{
Rig rig("actions_detect_bad_timeout");
EXPECT_FALSE(rig.loaded) << "action sẽ LUÔN hỏng — gần như chắc chắn gõ nhầm";
EXPECT_EQ(rig.registry.size(), 0u);
}
} // namespace
int main(int argc, char** argv)
{
#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();
}

View File

@@ -0,0 +1,100 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm handler `logReport` — hiện thực tối thiểu nhưng ĐẦY ĐỦ của contract.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cstdlib>
#include <string>
#include <robot/node_handle.h>
#include <action_core/action_registry.h>
namespace
{
using action_core::ActionHandler;
using action_core::ActionRegistry;
using action_core::ActionStatus;
robot_protocol_msgs::Action makeReport()
{
robot_protocol_msgs::Action action;
action.actionType = "logReport";
action.actionId = "log-1";
action.actionDescription = "checkpoint";
robot_protocol_msgs::ActionParameter parameter;
parameter.key = "reason";
parameter.value = "shift-change";
action.actionParameters.push_back(parameter);
return action;
}
TEST(LogReportActionHandler, FinishesOnTheFirstTick)
{
robot::NodeHandle nh;
ActionRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "actions_log"));
ActionHandler* handler = registry.find("logReport");
ASSERT_NE(handler, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(handler->start(makeReport(), now));
// Việc đã xong trong start(), nhưng kết quả VẪN phải đi qua update(): caller không suy kết quả từ
// giá trị trả về của start().
const auto tick = handler->update(now);
EXPECT_EQ(tick.status, ActionStatus::kSucceeded);
EXPECT_NE(tick.message.find("log-1"), std::string::npos) << tick.message;
}
TEST(LogReportActionHandler, HandlesAnActionWithNoParameters)
{
robot::NodeHandle nh;
ActionRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "actions_log"));
ActionHandler* handler = registry.find("logReport");
ASSERT_NE(handler, nullptr);
robot_protocol_msgs::Action bare;
bare.actionType = "logReport";
bare.actionId = "log-2";
const robot::Time now = robot::Time::now();
ASSERT_TRUE(handler->start(bare, now));
EXPECT_EQ(handler->update(now).status, ActionStatus::kSucceeded);
}
TEST(LogReportActionHandler, CancelIsSafe)
{
robot::NodeHandle nh;
ActionRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "actions_log"));
ActionHandler* handler = registry.find("logReport");
ASSERT_NE(handler, nullptr);
EXPECT_NO_THROW(handler->cancel());
}
} // namespace
int main(int argc, char** argv)
{
#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();
}

View File

@@ -0,0 +1,116 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm hành vi của handler mặc định qua đúng đường nạp plugin.
*
* `NoopActionHandler` là ví dụ tham chiếu cho contract, nên hành vi của nó phải được khoá lại —
* đặc biệt là các guard cấu hình, vì chúng là thứ ngăn một file YAML gõ nhầm biến thành action
* chạy vĩnh viễn trên robot.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cstdlib>
#include <string>
#include <robot/node_handle.h>
#include <action_core/action_registry.h>
namespace
{
using action_core::ActionHandler;
using action_core::ActionRegistry;
using action_core::ActionStatus;
robot_protocol_msgs::Action makeAction(const std::string& type)
{
robot_protocol_msgs::Action action;
action.actionType = type;
action.actionId = type + "-id";
return action;
}
ActionHandler* load(ActionRegistry& registry, robot::NodeHandle& nh, const std::string& type)
{
if (!registry.loadFromConfig(nh, "actions"))
{
return nullptr;
}
return registry.find(type);
}
TEST(NoopActionHandler, ZeroDurationFinishesOnTheFirstTick)
{
robot::NodeHandle nh;
ActionRegistry registry;
ActionHandler* handler = load(registry, nh, "wait");
ASSERT_NE(handler, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(handler->start(makeAction("wait"), now));
EXPECT_EQ(handler->update(now).status, ActionStatus::kSucceeded);
}
TEST(NoopActionHandler, MessageNamesTheActionId)
{
robot::NodeHandle nh;
ActionRegistry registry;
ActionHandler* handler = load(registry, nh, "wait");
ASSERT_NE(handler, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(handler->start(makeAction("wait"), now));
// Message chỉ để log, nhưng phải chỉ đúng action nào — log không truy được về action nào thì vô
// dụng khi một chặng có nhiều action.
const std::string message = handler->update(now).message;
EXPECT_NE(message.find("wait-id"), std::string::npos) << message;
}
TEST(NoopActionHandler, CancelDoesNotThrowAndCanBeCalledWithoutStart)
{
robot::NodeHandle nh;
ActionRegistry registry;
ActionHandler* handler = load(registry, nh, "wait");
ASSERT_NE(handler, nullptr);
// Caller huỷ một action chưa kịp start là chuyện bình thường (cancel tới trong cùng cycle).
EXPECT_NO_THROW(handler->cancel());
}
TEST(NoopActionHandler, RestartResetsTheClock)
{
robot::NodeHandle nh;
ActionRegistry registry;
ActionHandler* handler = load(registry, nh, "charge");
ASSERT_NE(handler, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(handler->start(makeAction("charge"), now));
EXPECT_EQ(handler->update(now + robot::Duration(10.0)).status, ActionStatus::kFailed);
// Handler được dùng lại cho action sau: mốc thời gian phải được gieo lại, nếu không action thứ
// hai hỏng ngay lập tức vì thừa hưởng đồng hồ của action trước.
const robot::Time later = now + robot::Duration(20.0);
ASSERT_TRUE(handler->start(makeAction("charge"), later));
EXPECT_EQ(handler->update(later).status, ActionStatus::kRunning);
EXPECT_EQ(handler->update(later + robot::Duration(1.0)).status, ActionStatus::kSucceeded);
}
} // namespace
int main(int argc, char** argv)
{
#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();
}

View File

@@ -0,0 +1,136 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm handler `wait` — handler default duy nhất lấy tham số từ CHÍNH action, không từ YAML.
*
* Trọng tâm là các đường từ chối: một `duration` hỏng phải làm action thất bại có lý do, chứ không
* được biến thành một khoảng chờ đoán bừa mà không ai giải thích được vì sao robot đứng im.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cstdlib>
#include <string>
#include <robot/node_handle.h>
#include <action_core/action_registry.h>
namespace
{
using action_core::ActionHandler;
using action_core::ActionRegistry;
using action_core::ActionStatus;
robot_protocol_msgs::Action makeWait(const std::string& duration_value)
{
robot_protocol_msgs::Action action;
action.actionType = "wait";
action.actionId = "wait-1";
if (!duration_value.empty())
{
robot_protocol_msgs::ActionParameter parameter;
parameter.key = "duration";
parameter.value = duration_value;
action.actionParameters.push_back(parameter);
}
return action;
}
class WaitRig
{
public:
WaitRig()
{
loaded_ = registry_.loadFromConfig(nh_, "actions_wait");
handler_ = registry_.find("wait");
}
bool loaded_ = false;
robot::NodeHandle nh_;
ActionRegistry registry_;
ActionHandler* handler_ = nullptr;
};
TEST(WaitActionHandler, TakesDurationFromTheActionItself)
{
WaitRig rig;
ASSERT_TRUE(rig.loaded_);
ASSERT_NE(rig.handler_, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(rig.handler_->start(makeWait("2.0"), now));
EXPECT_EQ(rig.handler_->update(now).status, ActionStatus::kRunning);
EXPECT_EQ(rig.handler_->update(now + robot::Duration(1.9)).status, ActionStatus::kRunning);
EXPECT_EQ(rig.handler_->update(now + robot::Duration(2.0)).status, ActionStatus::kSucceeded);
}
TEST(WaitActionHandler, FallsBackToDefaultWhenTheActionCarriesNoDuration)
{
WaitRig rig;
ASSERT_NE(rig.handler_, nullptr);
// default_duration = 0 trong config test -> xong ngay ở tick đầu.
const robot::Time now = robot::Time::now();
ASSERT_TRUE(rig.handler_->start(makeWait(""), now));
EXPECT_EQ(rig.handler_->update(now).status, ActionStatus::kSucceeded);
}
TEST(WaitActionHandler, RefusesNonNumericDuration)
{
WaitRig rig;
ASSERT_NE(rig.handler_, nullptr);
// Từ chối tại start(): caller coi như action hỏng và fleet nhận được lý do.
EXPECT_FALSE(rig.handler_->start(makeWait("mot-luc-nua"), robot::Time::now()));
}
TEST(WaitActionHandler, RefusesNegativeDuration)
{
WaitRig rig;
ASSERT_NE(rig.handler_, nullptr);
EXPECT_FALSE(rig.handler_->start(makeWait("-1.0"), robot::Time::now()));
}
TEST(WaitActionHandler, RefusesDurationAboveTheConfiguredCeiling)
{
WaitRig rig;
ASSERT_NE(rig.handler_, nullptr);
// max_duration = 5 s trong config test. Vượt trần phải là THẤT BẠI, không phải bị cắt xuống 5 s:
// im lặng rút ngắn là giấu đi một lỗi cấu hình của fleet.
EXPECT_FALSE(rig.handler_->start(makeWait("120.0"), robot::Time::now()));
}
TEST(WaitActionHandler, RestartResetsTheClock)
{
WaitRig rig;
ASSERT_NE(rig.handler_, nullptr);
const robot::Time now = robot::Time::now();
ASSERT_TRUE(rig.handler_->start(makeWait("1.0"), now));
EXPECT_EQ(rig.handler_->update(now + robot::Duration(1.0)).status, ActionStatus::kSucceeded);
const robot::Time later = now + robot::Duration(10.0);
ASSERT_TRUE(rig.handler_->start(makeWait("1.0"), later));
EXPECT_EQ(rig.handler_->update(later).status, ActionStatus::kRunning);
}
} // namespace
int main(int argc, char** argv)
{
#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();
}