1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "timer_manager_test.h"
17 
18 #include <unistd.h>
19 
20 #undef LOG_TAG
21 #define LOG_TAG "TimerManagerTest"
22 
23 namespace OHOS {
24 namespace Msdp {
25 namespace DeviceStatus {
26 
27 using namespace testing::ext;
28 namespace {
29 struct device_status_epoll_event {
30     int32_t fd { -1 };
31     EpollEventType event_type { EPOLL_EVENT_BEGIN };
32 };
33 
34 ContextService *g_instance = nullptr;
35 constexpr int32_t TIME_WAIT_FOR_OP_MS { 100 };
36 constexpr int32_t DEFAULT_DELAY_TIME { 40 };
37 constexpr int32_t RETRY_TIME { 2 };
38 constexpr int32_t DEFAULT_TIMEOUT { 30 };
39 constexpr int32_t REPEAT_ONCE { 1 };
40 constexpr int32_t DEFAULT_UNLOAD_COOLING_TIME_MS { 600 };
41 constexpr int32_t ERROR_TIMERID { -1 };
42 constexpr size_t ERROR_REPEAT_COUNT { 128 };
43 constexpr int32_t ERROR_INTERVAL_MS { 1000000 };
44 } // namespace
45 
ContextService()46 ContextService::ContextService()
47 {
48     FI_HILOGI("OHOS_BUILD_ENABLE_INTENTION_FRAMEWORK is on");
49     OnStart();
50 }
51 
~ContextService()52 ContextService::~ContextService()
53 {
54     OnStop();
55 }
56 
GetDelegateTasks()57 IDelegateTasks& ContextService::GetDelegateTasks()
58 {
59     return delegateTasks_;
60 }
61 
GetDeviceManager()62 IDeviceManager& ContextService::GetDeviceManager()
63 {
64     return devMgr_;
65 }
66 
GetTimerManager()67 ITimerManager& ContextService::GetTimerManager()
68 {
69     return timerMgr_;
70 }
71 
GetDragManager()72 IDragManager& ContextService::GetDragManager()
73 {
74     return dragMgr_;
75 }
76 
GetInstance()77 __attribute__((no_sanitize("cfi"))) ContextService* ContextService::GetInstance()
78 {
79     static std::once_flag flag;
80     std::call_once(flag, [&]() {
81         ContextService *cooContext = new (std::nothrow) ContextService();
82         CHKPL(cooContext);
83         g_instance = cooContext;
84     });
85     return g_instance;
86 }
87 
GetSocketSessionManager()88 ISocketSessionManager& ContextService::GetSocketSessionManager()
89 {
90     return socketSessionMgr_;
91 }
92 
GetPluginManager()93 IPluginManager& ContextService::GetPluginManager()
94 {
95     return *pluginMgr_;
96 }
97 
GetInput()98 IInputAdapter& ContextService::GetInput()
99 {
100     return *input_;
101 }
102 
GetDSoftbus()103 IDSoftbusAdapter& ContextService::GetDSoftbus()
104 {
105     return *dsoftbusAda_;
106 }
107 
Init()108 bool ContextService::Init()
109 {
110     CALL_DEBUG_ENTER;
111     if (EpollCreate() != RET_OK) {
112         FI_HILOGE("Create epoll failed");
113         return false;
114     }
115     if (InitDelegateTasks() != RET_OK) {
116         FI_HILOGE("Delegate tasks init failed");
117         goto INIT_FAIL;
118     }
119 
120     if (InitTimerMgr() != RET_OK) {
121         FI_HILOGE("TimerMgr init failed");
122         goto INIT_FAIL;
123     }
124 
125     return true;
126 
127 INIT_FAIL:
128     EpollClose();
129     return false;
130 }
131 
InitTimerMgr()132 __attribute__((no_sanitize("cfi"))) int32_t ContextService::InitTimerMgr()
133 {
134     CALL_DEBUG_ENTER;
135     int32_t ret = timerMgr_.Init(this);
136     if (ret != RET_OK) {
137         FI_HILOGE("TimerMgr init failed");
138         return ret;
139     }
140 
141     ret = AddEpoll(EPOLL_EVENT_TIMER, timerMgr_.GetTimerFd());
142     if (ret != RET_OK) {
143         FI_HILOGE("AddEpoll for timer failed");
144     }
145     return ret;
146 }
147 
InitDelegateTasks()148 int32_t ContextService::InitDelegateTasks()
149 {
150     CALL_DEBUG_ENTER;
151     if (!delegateTasks_.Init()) {
152         FI_HILOGE("The delegate task init failed");
153         return RET_ERR;
154     }
155     int32_t ret = AddEpoll(EPOLL_EVENT_ETASK, delegateTasks_.GetReadFd());
156     if (ret != RET_OK) {
157         FI_HILOGE("AddEpoll error ret:%{public}d", ret);
158     }
159     FI_HILOGI("AddEpoll, epollfd:%{public}d, fd:%{public}d", epollFd_, delegateTasks_.GetReadFd());
160     return ret;
161 }
162 
EpollCreate()163 int32_t ContextService::EpollCreate()
164 {
165     CALL_DEBUG_ENTER;
166     epollFd_ = ::epoll_create1(EPOLL_CLOEXEC);
167     if (epollFd_ < 0) {
168         FI_HILOGE("epoll_create1 failed:%{public}s", ::strerror(errno));
169         return RET_ERR;
170     }
171     return RET_OK;
172 }
173 
AddEpoll(EpollEventType type,int32_t fd)174 int32_t ContextService::AddEpoll(EpollEventType type, int32_t fd)
175 {
176     CALL_DEBUG_ENTER;
177     if (!(type >= EPOLL_EVENT_BEGIN && type < EPOLL_EVENT_END)) {
178         FI_HILOGE("Invalid type:%{public}d", type);
179         return RET_ERR;
180     }
181     if (fd < 0) {
182         FI_HILOGE("Invalid fd:%{public}d", fd);
183         return RET_ERR;
184     }
185     auto eventData = static_cast<device_status_epoll_event*>(malloc(sizeof(device_status_epoll_event)));
186     if (!eventData) {
187         FI_HILOGE("Malloc failed");
188         return RET_ERR;
189     }
190     eventData->fd = fd;
191     eventData->event_type = type;
192     FI_HILOGD("EventData:[fd:%{public}d, type:%{public}d]", eventData->fd, eventData->event_type);
193 
194     struct epoll_event ev {};
195     ev.events = EPOLLIN;
196     ev.data.ptr = eventData;
197     if (EpollCtl(fd, EPOLL_CTL_ADD, ev) != RET_OK) {
198         free(eventData);
199         eventData = nullptr;
200         ev.data.ptr = nullptr;
201         FI_HILOGE("EpollCtl failed");
202         return RET_ERR;
203     }
204     return RET_OK;
205 }
206 
DelEpoll(EpollEventType type,int32_t fd)207 int32_t ContextService::DelEpoll(EpollEventType type, int32_t fd)
208 {
209     CALL_DEBUG_ENTER;
210     if (!(type >= EPOLL_EVENT_BEGIN && type < EPOLL_EVENT_END)) {
211         FI_HILOGE("Invalid type:%{public}d", type);
212         return RET_ERR;
213     }
214     if (fd < 0) {
215         FI_HILOGE("Invalid fd:%{public}d", fd);
216         return RET_ERR;
217     }
218     struct epoll_event ev {};
219     if (EpollCtl(fd, EPOLL_CTL_DEL, ev) != RET_OK) {
220         FI_HILOGE("DelEpoll failed");
221         return RET_ERR;
222     }
223     return RET_OK;
224 }
225 
EpollClose()226 void ContextService::EpollClose()
227 {
228     CALL_DEBUG_ENTER;
229     if (epollFd_ >= 0) {
230         if (close(epollFd_) < 0) {
231             FI_HILOGE("Close epoll fd failed, error:%{public}s, epollFd_:%{public}d", strerror(errno), epollFd_);
232         }
233         epollFd_ = -1;
234     }
235 }
236 
EpollCtl(int32_t fd,int32_t op,struct epoll_event & event)237 int32_t ContextService::EpollCtl(int32_t fd, int32_t op, struct epoll_event &event)
238 {
239     CALL_DEBUG_ENTER;
240     if (fd < 0) {
241         FI_HILOGE("Invalid fd:%{public}d", fd);
242         return RET_ERR;
243     }
244     if (epollFd_ < 0) {
245         FI_HILOGE("Invalid epollFd:%{public}d", epollFd_);
246         return RET_ERR;
247     }
248     if (::epoll_ctl(epollFd_, op, fd, &event) != 0) {
249         FI_HILOGE("epoll_ctl(%{public}d,%{public}d,%{public}d) failed:%{public}s", epollFd_, op, fd, ::strerror(errno));
250         return RET_ERR;
251     }
252     return RET_OK;
253 }
254 
EpollWait(int32_t maxevents,int32_t timeout,struct epoll_event & events)255 int32_t ContextService::EpollWait(int32_t maxevents, int32_t timeout, struct epoll_event &events)
256 {
257     if (epollFd_ < 0) {
258         FI_HILOGE("Invalid epollFd:%{public}d", epollFd_);
259         return RET_ERR;
260     }
261     return epoll_wait(epollFd_, &events, maxevents, timeout);
262 }
263 
OnTimeout(const struct epoll_event & ev)264 void ContextService::OnTimeout(const struct epoll_event &ev)
265 {
266     CALL_DEBUG_ENTER;
267     if ((ev.events & EPOLLIN) == EPOLLIN) {
268         uint64_t expiration {};
269         ssize_t ret = read(timerMgr_.GetTimerFd(), &expiration, sizeof(expiration));
270         if (ret < 0) {
271             FI_HILOGE("Read expiration failed:%{public}s", strerror(errno));
272         }
273         timerMgr_.ProcessTimers();
274     } else if ((ev.events & (EPOLLHUP | EPOLLERR)) != 0) {
275         FI_HILOGE("Epoll hangup:%{public}s", strerror(errno));
276     }
277 }
278 
OnStart()279 void ContextService::OnStart()
280 {
281     CALL_DEBUG_ENTER;
282     uint64_t tid = GetThisThreadId();
283     delegateTasks_.SetWorkerThreadId(tid);
284 
285     if (!Init()) {
286         FI_HILOGE("On start call init failed");
287         return;
288     }
289     state_ = ServiceRunningState::STATE_RUNNING;
290     ready_ = true;
291 
292     worker_ = std::thread(std::bind(&ContextService::OnThread, this));
293 }
294 
OnStop()295 void ContextService::OnStop()
296 {
297     CALL_DEBUG_ENTER;
298     if (timerMgr_.GetTimerFd() >= 0) {
299         if (close(timerMgr_.GetTimerFd()) < 0) {
300             FI_HILOGE("Close timer fd failed, error:%{public}s", strerror(errno));
301         }
302     }
303     if (!ready_) {
304         FI_HILOGI("ready state is false");
305         return;
306     }
307     ready_ = false;
308     state_ = ServiceRunningState::STATE_EXIT;
309 
310     delegateTasks_.PostAsyncTask([]() -> int32_t {
311         FI_HILOGD("No asynchronous operations");
312         return RET_OK;
313     });
314     if (worker_.joinable()) {
315         worker_.join();
316     }
317     EpollClose();
318     FI_HILOGI("OnStop leave");
319 }
320 
OnThread()321 void ContextService::OnThread()
322 {
323     CALL_DEBUG_ENTER;
324     SetThreadName(std::string("os_ds_service"));
325     uint64_t tid = GetThisThreadId();
326     delegateTasks_.SetWorkerThreadId(tid);
327     FI_HILOGD("Main worker thread start, tid:%{public}" PRId64 "", tid);
328 
329     while (state_ == ServiceRunningState::STATE_RUNNING) {
330         struct epoll_event ev[MAX_EVENT_SIZE] {};
331         int32_t count = EpollWait(MAX_EVENT_SIZE, -1, ev[0]);
332         for (int32_t i = 0; i < count && state_ == ServiceRunningState::STATE_RUNNING; i++) {
333             auto epollEvent = reinterpret_cast<device_status_epoll_event*>(ev[i].data.ptr);
334             CHKPC(epollEvent);
335             if (epollEvent->event_type == EPOLL_EVENT_TIMER) {
336                 OnTimeout(ev[i]);
337             } else if (epollEvent->event_type == EPOLL_EVENT_ETASK) {
338                 OnDelegateTask(ev[i]);
339             } else {
340                 FI_HILOGW("Unknown epoll event type:%{public}d", epollEvent->event_type);
341             }
342         }
343     }
344     FI_HILOGD("Main worker thread stop, tid:%{public}" PRId64 "", tid);
345 }
346 
OnDelegateTask(const struct epoll_event & ev)347 void ContextService::OnDelegateTask(const struct epoll_event &ev)
348 {
349     if ((ev.events & EPOLLIN) == 0) {
350         FI_HILOGW("Not epollin");
351         return;
352     }
353     DelegateTasks::TaskData data {};
354     ssize_t res = read(delegateTasks_.GetReadFd(), &data, sizeof(data));
355     if (res == -1) {
356         FI_HILOGW("Read failed erron:%{public}d", errno);
357     }
358     FI_HILOGD("RemoteRequest notify td:%{public}" PRId64 ", std:%{public}" PRId64 ""
359         ", taskId:%{public}d", GetThisThreadId(), data.tid, data.taskId);
360     delegateTasks_.ProcessTasks();
361 }
362 
SetUpTestCase()363 void TimerManagerTest::SetUpTestCase() {}
364 
TearDownTestCase()365 void TimerManagerTest::TearDownTestCase()
366 {
367     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
368 }
369 
SetUp()370 void TimerManagerTest::SetUp() {}
371 
TearDown()372 void TimerManagerTest::TearDown() {}
373 
374 /**
375  * @tc.name: TimerManagerTest_AddTimer001
376  * @tc.desc: Test AddTimer, Parameter correct expected success
377  * @tc.type: FUNC
378  */
379 HWTEST_F(TimerManagerTest, TimerManagerTest_AddTimer001, TestSize.Level1)
380 {
381     CALL_TEST_DEBUG;
382     auto env = ContextService::GetInstance();
383     ASSERT_NE(env, nullptr);
384 
__anon634b35e50402() 385     timerId_ = env->GetTimerManager().AddTimer(DEFAULT_DELAY_TIME, RETRY_TIME, [this, env]() {
386         if (timerInfo_.times == 0) {
387             FI_HILOGI("It will be retry to call callback next time");
388             timerInfo_.times++;
389             return;
390         }
391         env->GetTimerManager().RemoveTimer(timerInfo_.timerId);
392     });
393     if (timerId_ < 0) {
394         FI_HILOGE("AddTimer failed");
395     } else {
396         FI_HILOGI("Add the timer %{public}d success", timerId_);
397     }
398 
399     timerInfo_.timerId = timerId_;
400     timerInfo_.times = 0;
401 
402     EXPECT_GE(timerId_, 0);
403     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS * RETRY_TIME));
404     timerId_ = -1;
405     timerInfo_.timerId = -1;
406 }
407 
408 /**
409  * @tc.name: TimerManagerTest_AddTimer002
410  * @tc.desc: Test AddTimer, Parameter correct expected success
411  * @tc.type: FUNC
412  */
413 HWTEST_F(TimerManagerTest, TimerManagerTest_AddTimer002, TestSize.Level1)
414 {
415     CALL_TEST_DEBUG;
416     auto env = ContextService::GetInstance();
417     ASSERT_NE(env, nullptr);
__anon634b35e50502() 418     timerId_ = env->GetTimerManager().AddTimer(DEFAULT_TIMEOUT, REPEAT_ONCE, [this, env]() {
419         FI_HILOGI("Timer %{public}d excute one times", timerId_);
420         EXPECT_GE(timerId_, 0);
421         env->GetTimerManager().RemoveTimer(timerId_);
422     });
423     if (timerId_ < 0) {
424         FI_HILOGE("AddTimer failed");
425     } else {
426         FI_HILOGI("Add the timer %{public}d success", timerId_);
427     }
428 
429     EXPECT_GE(timerId_, 0);
430     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
431     timerId_ = -1;
432 }
433 
434 /**
435  * @tc.name: TimerManagerTest_AddTimer003
436  * @tc.desc: Test AddTimer, Parameter correct expected success
437  * @tc.type: FUNC
438  */
439 HWTEST_F(TimerManagerTest, TimerManagerTest_AddTimer003, TestSize.Level1)
440 {
441     CALL_TEST_DEBUG;
442     auto env = ContextService::GetInstance();
443     ASSERT_NE(env, nullptr);
444 
__anon634b35e50602() 445     timerId_ = env->GetTimerManager().AddTimer(DEFAULT_TIMEOUT, REPEAT_ONCE, [this, env]() {
446         if (timerId_ >= 0) {
447             env->GetTimerManager().RemoveTimer(timerId_);
448             EXPECT_GE(timerId_, 0);
449         }
450     });
451 
452     if (timerId_ < 0) {
453         FI_HILOGE("AddTimer failed");
454     } else {
455         FI_HILOGI("Add the timer %{public}d success", timerId_);
456     }
457     EXPECT_GE(timerId_, 0);
458     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
459     timerId_ = -1;
460 }
461 
462 /**
463  * @tc.name: TimerManagerTest_AddTimer004
464  * @tc.desc: Test AddTimer, Invalid number of repetitions, expected failure
465  * @tc.type: FUNC
466  */
467 HWTEST_F(TimerManagerTest, TimerManagerTest_AddTimer004, TestSize.Level1)
468 {
469     CALL_TEST_DEBUG;
470     auto env = ContextService::GetInstance();
471     ASSERT_NE(env, nullptr);
__anon634b35e50702() 472     timerId_ = env->GetTimerManager().AddTimer(DEFAULT_TIMEOUT, ERROR_REPEAT_COUNT, [this, env]() {
473         FI_HILOGI("Timer %{public}d excute onetimes", timerId_);
474         env->GetTimerManager().RemoveTimer(timerId_);
475         EXPECT_GE(timerId_, 0);
476         timerId_ = -1;
477     });
478     if (timerId_ < 0) {
479         FI_HILOGI("Invalid repeat-count value, then error, so success");
480     } else {
481         FI_HILOGE("Invalid repeat-count value, but okay, so failed");
482     }
483 
484     EXPECT_GE(timerId_, 0);
485     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
486 }
487 
488 /**
489  * @tc.name: TimerManagerTest_AddTimer005
490  * @tc.desc: Test AddTimer, Invalid interval time, expected failure
491  * @tc.type: FUNC
492  */
493 HWTEST_F(TimerManagerTest, TimerManagerTest_AddTimer005, TestSize.Level1)
494 {
495     CALL_TEST_DEBUG;
496     auto env = ContextService::GetInstance();
497     ASSERT_NE(env, nullptr);
__anon634b35e50802() 498     timerId_ = env->GetTimerManager().AddTimer(ERROR_INTERVAL_MS, REPEAT_ONCE, [this, env]() {
499         FI_HILOGI("Timer %{public}d excute onetimes", timerId_);
500         env->GetTimerManager().RemoveTimer(timerId_);
501         EXPECT_GE(timerId_, 0);
502     });
503     if (timerId_ < 0) {
504         FI_HILOGI("Invalid interval value, then error, so success");
505     } else {
506         FI_HILOGE("Invalid interval value, but okay, so failed");
507     }
508 
509     EXPECT_GE(timerId_, 0);
510     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
511     timerId_ = -1;
512 }
513 
514 /**
515  * @tc.name: TimerManagerTest_AddTimer006
516  * @tc.desc: Test AddTimer, Invalid callback function, expected failure
517  * @tc.type: FUNC
518  */
519 HWTEST_F(TimerManagerTest, TimerManagerTest_AddTimer006, TestSize.Level1)
520 {
521     CALL_TEST_DEBUG;
522     auto env = ContextService::GetInstance();
523     ASSERT_NE(env, nullptr);
524     timerId_ = env->GetTimerManager().AddTimer(ERROR_INTERVAL_MS, REPEAT_ONCE, nullptr);
525     if (timerId_ < 0) {
526         FI_HILOGI("Invalid callback value, then error, so success");
527     } else {
528         FI_HILOGE("Invalid callback value, but okay, so failed");
529     }
530 
531     EXPECT_LT(timerId_, 0);
532     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
533     timerId_ = -1;
534 }
535 
536 /**
537  * @tc.name: TimerManagerTest_GetTimerFd001
538  * @tc.desc: Test GetTimerFd, Obtaining initialized TimerFd, expected success
539  * @tc.type: FUNC
540  */
541 HWTEST_F(TimerManagerTest, TimerManagerTest_GetTimerFd001, TestSize.Level1)
542 {
543     CALL_TEST_DEBUG;
544     auto env = ContextService::GetInstance();
545     ASSERT_NE(env, nullptr);
546     TimerManager *timerMgr = static_cast<TimerManager *>(&env->GetTimerManager());
547     int32_t timerFd = timerMgr->GetTimerFd();
548     if (timerFd < 0) {
549         FI_HILOGE("AddTimer failed");
550     } else {
551         FI_HILOGI("Add the timer %{public}d success", timerId_);
552     }
553     EXPECT_GE(timerFd, 0);
554 }
555 
556 /**
557  * @tc.name: TimerManagerTest_GetTimerFd002
558  * @tc.desc: Test GetTimerFd, Uninitialized, directly obtaining TimerFd, expected failure
559  * @tc.type: FUNC
560  */
561 HWTEST_F(TimerManagerTest, TimerManagerTest_GetTimerFd002, TestSize.Level1)
562 {
563     CALL_TEST_DEBUG;
564     TimerManager timerMgr;
565     int32_t timerFd = timerMgr.GetTimerFd();
566     if (timerFd < 0) {
567         FI_HILOGI("TimerFd is less than zero. the value is %{public}d", timerFd);
568     } else {
569         FI_HILOGE("Get TimerFd failed. the value is %{public}d", timerFd);
570     }
571     EXPECT_LT(timerFd, 0);
572 }
573 
574 /**
575  * @tc.name: TimerManagerTest_IsExist001
576  * @tc.desc: Test IsExist, The newly added clock ID has been determined to exist and is expected to succeed
577  * @tc.type: FUNC
578  */
579 HWTEST_F(TimerManagerTest, TimerManagerTest_IsExist001, TestSize.Level1)
580 {
581     CALL_TEST_DEBUG;
582     auto env = ContextService::GetInstance();
583     ASSERT_NE(env, nullptr);
584 
__anon634b35e50902() 585     timerId_ = env->GetTimerManager().AddTimer(DEFAULT_TIMEOUT, REPEAT_ONCE, [this, env]() {
586         if (timerId_ >= 0) {
587             env->GetTimerManager().RemoveTimer(timerId_);
588             EXPECT_GE(timerId_, 0);
589         }
590     });
591 
592     if (timerId_ < 0) {
593         FI_HILOGE("AddTimer failed");
594     } else {
595         FI_HILOGI("Add the timer %{public}d success", timerId_);
596     }
597     EXPECT_GE(timerId_, 0);
598     TimerManager *timerMgr = static_cast<TimerManager *>(&env->GetTimerManager());
599     bool exist = timerMgr->IsExist(timerId_);
600     if (exist) {
601         FI_HILOGI("timerId_ is exist, so success");
602     } else {
603         FI_HILOGE("timerId_ is exist, but response unexist, so failed");
604     }
605     EXPECT_TRUE(exist);
606 
607     exist = timerMgr->IsExist(ERROR_TIMERID);
608     if (!exist) {
609         FI_HILOGI("The TimerFd(-1) does not exist, so success");
610     } else {
611         FI_HILOGE("The TimerFd(-1) does not exist, but response exist, so failed");
612     }
613     EXPECT_FALSE(exist);
614     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
615     timerId_ = -1;
616 }
617 
618 /**
619  * @tc.name: TimerManagerTest_IsExist002
620  * @tc.desc: Test IsExist, Invalid clock ID, determine if it does not exist
621  * @tc.type: FUNC
622  */
623 HWTEST_F(TimerManagerTest, TimerManagerTest_IsExist002, TestSize.Level1)
624 {
625     CALL_TEST_DEBUG;
626     TimerManager timerMgr;
627     bool exist = timerMgr.IsExist(ERROR_TIMERID);
628 
629     if (!exist) {
630         FI_HILOGI("The TimerFd(-1) is not exist, so success");
631     } else {
632         FI_HILOGE("The TimerFd(-1) is not exist, but response exist, so failed");
633     }
634     EXPECT_FALSE(exist);
635 }
636 
637 /**
638  * @tc.name: TimerManagerTest_ResetTimer001
639  * @tc.desc: Test ResetTimer, After adding the clock and resetting it, expected success
640  * @tc.type: FUNC
641  */
642 HWTEST_F(TimerManagerTest, TimerManagerTest_ResetTimer001, TestSize.Level1)
643 {
644     CALL_TEST_DEBUG;
645     auto env = ContextService::GetInstance();
646     ASSERT_NE(env, nullptr);
647 
__anon634b35e50a02() 648     timerId_ = env->GetTimerManager().AddTimer(DEFAULT_UNLOAD_COOLING_TIME_MS, REPEAT_ONCE, [this, env]() {
649         if (timerId_ >= 0) {
650             env->GetTimerManager().RemoveTimer(timerId_);
651             EXPECT_GE(timerId_, 0);
652         }
653     });
654 
655     if (timerId_ < 0) {
656         FI_HILOGE("AddTimer failed");
657     } else {
658         TimerManager *timerMgr = static_cast<TimerManager *>(&env->GetTimerManager());
659         int32_t ret = timerMgr->ResetTimer(timerId_);
660         if (ret == RET_OK) {
661             FI_HILOGI("Reset timer success");
662         } else {
663             FI_HILOGI("Reset timer %{public}d failed", timerId_);
664         }
665         EXPECT_EQ(ret, RET_OK);
666     }
667     EXPECT_GE(timerId_, 0);
668     std::this_thread::sleep_for(std::chrono::milliseconds(DEFAULT_UNLOAD_COOLING_TIME_MS));
669     timerId_ = -1;
670 }
671 
672 /**
673  * @tc.name: TimerManagerTest_ResetTimer002
674  * @tc.desc: Test ResetTimer, Reset after deleting clock, expected failure
675  * @tc.type: FUNC
676  */
677 HWTEST_F(TimerManagerTest, TimerManagerTest_ResetTimer002, TestSize.Level1)
678 {
679     CALL_TEST_DEBUG;
680     auto env = ContextService::GetInstance();
681     ASSERT_NE(env, nullptr);
682 
__anon634b35e50b02() 683     timerId_ = env->GetTimerManager().AddTimer(DEFAULT_TIMEOUT, REPEAT_ONCE, [this, env]() {
684         if (timerId_ >= 0) {
685             env->GetTimerManager().RemoveTimer(timerId_);
686             EXPECT_GE(timerId_, 0);
687             TimerManager *timerMgr = static_cast<TimerManager *>(&env->GetTimerManager());
688             int32_t ret = timerMgr->ResetTimer(timerId_);
689             if (ret == RET_ERR) {
690                 FI_HILOGI("Reset unexist timerid sucess");
691             } else {
692                 FI_HILOGE("Reset unexist timerid %{public}d failed", timerId_);
693             }
694             EXPECT_EQ(ret, RET_ERR);
695         }
696     });
697 
698     if (timerId_ < 0) {
699         FI_HILOGE("AddTimer failed");
700     } else {
701         FI_HILOGI("AddTimer success");
702     }
703     EXPECT_GE(timerId_, 0);
704     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
705     timerId_ = -1;
706 }
707 
708 /**
709  * @tc.name: TimerManagerTest_RemoveTimer001
710  * @tc.desc: Test RemoveTimer, Repeated deletion of clock, first successful, others failed
711  * @tc.type: FUNC
712  */
713 HWTEST_F(TimerManagerTest, TimerManagerTest_RemoveTimer001, TestSize.Level1)
714 {
715     CALL_TEST_DEBUG;
716     auto env = ContextService::GetInstance();
717     ASSERT_NE(env, nullptr);
718 
__anon634b35e50c02() 719     timerId_ = env->GetTimerManager().AddTimer(DEFAULT_TIMEOUT, REPEAT_ONCE, [this, env]() {
720         if (timerId_ >= 0) {
721             int32_t ret = env->GetTimerManager().RemoveTimer(timerId_);
722             ret = env->GetTimerManager().RemoveTimer(timerId_);
723             if (ret == RET_ERR) {
724                 FI_HILOGI("Remove timer two times, then error, this case success");
725             } else {
726                 FI_HILOGE("Remove timer two times, but okay, this case failed");
727             }
728             EXPECT_EQ(ret, RET_ERR);
729         }
730     });
731 
732     if (timerId_ < 0) {
733         FI_HILOGE("AddTimer failed");
734     } else {
735         FI_HILOGI("AddTimer success");
736     }
737     EXPECT_GE(timerId_, 0);
738     std::this_thread::sleep_for(std::chrono::milliseconds(TIME_WAIT_FOR_OP_MS));
739     timerId_ = -1;
740 }
741 } // namespace DeviceStatus
742 } // namespace Msdp
743 } // namespace OHOS