@@ -46,17 +46,21 @@ class TestEventLoopHandler : public ::testing::Test
46
46
47
47
static System::LayerSocketsLoop & SystemLayer () { return static_cast <System::LayerSocketsLoop &>(DeviceLayer::SystemLayer ()); }
48
48
49
+ // Schedules a call to the provided lambda and returns a cancel function.
49
50
template <class Lambda >
50
- static void Schedule (Timeout delay, Lambda lambda)
51
+ static std::function< void ()> Schedule (Timeout delay, Lambda lambda)
51
52
{
52
- SystemLayer ().StartTimer (
53
- delay,
54
- [](System::Layer * layer, void * ctx) {
55
- auto * function = static_cast <std::function<void ()> *>(ctx);
56
- (*function)();
57
- delete function;
58
- },
59
- new std::function<void ()>(lambda));
53
+ System::TimerCompleteCallback callback = [](System::Layer * layer, void * ctx) {
54
+ auto * function = static_cast <std::function<void ()> *>(ctx);
55
+ (*function)();
56
+ delete function;
57
+ };
58
+ auto * function = new std::function<void ()>(lambda);
59
+ SystemLayer ().StartTimer (delay, callback, function);
60
+ return [=] {
61
+ SystemLayer ().CancelTimer (callback, function);
62
+ delete function;
63
+ };
60
64
}
61
65
62
66
template <class Lambda >
@@ -125,10 +129,12 @@ TEST_F(TestEventLoopHandler, EventLoopHandlerWake)
125
129
}
126
130
} loopHandler;
127
131
132
+ // Schedule a fallback timer to ensure the test stops
133
+ auto cancelFallback = Schedule(1000_ms, [] { DeviceLayer::PlatformMgr ().StopEventLoopTask (); });
128
134
SystemLayer ().AddLoopHandler(loopHandler);
129
- Schedule (1000_ms, [] { DeviceLayer::PlatformMgr ().StopEventLoopTask (); });
130
135
chip::DeviceLayer::PlatformMgr ().RunEventLoop();
131
136
SystemLayer ().RemoveLoopHandler(loopHandler);
137
+ cancelFallback (); // avoid leaking the fallback timer
132
138
133
139
Timestamp sleepDuration = loopHandler.wakeTimestamp - loopHandler.startTimestamp;
134
140
EXPECT_GE (sleepDuration.count(), 400u ); // loopHandler requested wake-up after 400ms
0 commit comments