Skip to content

Commit e2f5b79

Browse files
Avoid leaking the fallback timer in the test
1 parent a26133c commit e2f5b79

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

src/system/tests/TestEventLoopHandler.cpp

+13-10
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,18 @@ class TestEventLoopHandler : public ::testing::Test
4646

4747
static System::LayerSocketsLoop & SystemLayer() { return static_cast<System::LayerSocketsLoop &>(DeviceLayer::SystemLayer()); }
4848

49+
// Schedules a call to the provided lambda and returns a cancel function.
4950
template <class Lambda>
50-
static void Schedule(Timeout delay, Lambda lambda)
51+
static std::function<void()> Schedule(Timeout delay, Lambda lambda)
5152
{
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+
auto * function = new std::function<void()>(lambda);
54+
System::TimerCompleteCallback callback = [](System::Layer * layer, void * ctx) {
55+
auto * function = static_cast<std::function<void()> *>(ctx);
56+
(*function)();
57+
delete function;
58+
};
59+
SystemLayer().StartTimer(delay, callback, function);
60+
return [=] { SystemLayer().CancelTimer(callback, function); };
6061
}
6162

6263
template <class Lambda>
@@ -125,10 +126,12 @@ TEST_F(TestEventLoopHandler, EventLoopHandlerWake)
125126
}
126127
} loopHandler;
127128

129+
// Schedule a fallback timer to ensure the test stops
130+
auto cancelFallback = Schedule(1000_ms, [] { DeviceLayer::PlatformMgr().StopEventLoopTask(); });
128131
SystemLayer().AddLoopHandler(loopHandler);
129-
Schedule(1000_ms, [] { DeviceLayer::PlatformMgr().StopEventLoopTask(); });
130132
chip::DeviceLayer::PlatformMgr().RunEventLoop();
131133
SystemLayer().RemoveLoopHandler(loopHandler);
134+
cancelFallback(); // avoid leaking the fallback timer
132135

133136
Timestamp sleepDuration = loopHandler.wakeTimestamp - loopHandler.startTimestamp;
134137
EXPECT_GE(sleepDuration.count(), 400u); // loopHandler requested wake-up after 400ms

0 commit comments

Comments
 (0)