Skip to content

Commit c76229d

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

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

src/system/tests/TestEventLoopHandler.cpp

+16-10
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,21 @@ 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+
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+
};
6064
}
6165

6266
template <class Lambda>
@@ -125,10 +129,12 @@ TEST_F(TestEventLoopHandler, EventLoopHandlerWake)
125129
}
126130
} loopHandler;
127131

132+
// Schedule a fallback timer to ensure the test stops
133+
auto cancelFallback = Schedule(1000_ms, [] { DeviceLayer::PlatformMgr().StopEventLoopTask(); });
128134
SystemLayer().AddLoopHandler(loopHandler);
129-
Schedule(1000_ms, [] { DeviceLayer::PlatformMgr().StopEventLoopTask(); });
130135
chip::DeviceLayer::PlatformMgr().RunEventLoop();
131136
SystemLayer().RemoveLoopHandler(loopHandler);
137+
cancelFallback(); // avoid leaking the fallback timer
132138

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

0 commit comments

Comments
 (0)