1 /*
2 * Copyright (C) 2021 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 #include "time_service_test.h"
16
17 #include <chrono>
18 #include <climits>
19 #include <cstdlib>
20 #include <ctime>
21 #include <fstream>
22 #include <sys/stat.h>
23
24 #include "accesstoken_kit.h"
25 #include "ipc_skeleton.h"
26 #include "nativetoken_kit.h"
27 #include "time_common.h"
28 #include "timer_info_test.h"
29 #include "token_setproc.h"
30 #include "want_agent.h"
31 #include "timer_call_back.h"
32 #include "time_common.h"
33 #include "event_manager.h"
34 #include "ntp_update_time.h"
35 #include "cjson_helper.h"
36
37 #define private public
38 #define protected public
39 #include "sntp_client.h"
40 #include "ntp_update_time.h"
41 #include "time_system_ability.h"
42 #include "ntp_trusted_time.h"
43 #include "time_tick_notify.h"
44 #include "timer_proxy.h"
45 #include "time_service_test.h"
46
47 namespace {
48 using namespace testing::ext;
49 using namespace OHOS;
50 using namespace OHOS::MiscServices;
51 using namespace std::chrono;
52 using namespace OHOS::Security::AccessToken;
53
54 const int32_t RESERVED_UID = 99999;
55 std::set<int> RESERVED_PIDLIST = {1111, 2222};
56 const std::string NETWORK_TIME_STATUS_OFF = "OFF";
57 const std::string NETWORK_TIME_STATUS_ON = "ON";
58 const std::string AUTO_TIME_STATUS_ON = "ON";
59 uint64_t g_idleTimerId = 0;
60 const uint64_t TIMER_ID = 88888;
61 const uint32_t MAX_EXEMPTION_SIZE = 1000;
62 const int UID = 999998;
63 const int PID = 999999;
64 constexpr int ONE_HUNDRED = 100;
65 constexpr int FIVE_HUNDRED = 500;
66 constexpr uint64_t MICRO_TO_MILLISECOND = 1000;
67 constexpr int TIMER_ALARM_COUNT = 50;
68 constexpr int64_t MINUTE_TO_MILLISECOND = 60000;
69 constexpr char BYTE_SNTP_MESSAGE = 0xD8;
70 constexpr const char* DEFAULT_NTP_SERVER = "1.cn.pool.ntp.org";
71 static const int MAX_PID_LIST_SIZE = 1024;
72
73 static HapPolicyParams g_policyA = {
74 .apl = APL_SYSTEM_CORE,
75 .domain = "test.domain",
76 .permList = {
77 {
78 .permissionName = "ohos.permission.SET_TIME",
79 .bundleName = "ohos.permission_test.demoB",
80 .grantMode = 1,
81 .availableLevel = APL_NORMAL,
82 .label = "label",
83 .labelId = 1,
84 .description = "test",
85 .descriptionId = 1
86 },
87 {
88 .permissionName = "ohos.permission.SET_TIME_ZONE",
89 .bundleName = "ohos.permission_test.demoB",
90 .grantMode = 1,
91 .availableLevel = APL_NORMAL,
92 .label = "label",
93 .labelId = 1,
94 .description = "test",
95 .descriptionId = 1
96 },
97 {
98 .permissionName = "ohos.permission.MANAGE_LOCAL_ACCOUNTS",
99 .bundleName = "ohos.permission_test.demoB",
100 .grantMode = 1,
101 .availableLevel = APL_NORMAL,
102 .label = "label",
103 .labelId = 1,
104 .description = "test",
105 .descriptionId = 1
106 }
107 },
108 .permStateList = {
109 {
110 .permissionName = "ohos.permission.SET_TIME",
111 .isGeneral = true,
112 .resDeviceID = { "local" },
113 .grantStatus = { PermissionState::PERMISSION_GRANTED },
114 .grantFlags = { 1 }
115 },
116 {
117 .permissionName = "ohos.permission.SET_TIME_ZONE",
118 .isGeneral = true,
119 .resDeviceID = { "local" },
120 .grantStatus = { PermissionState::PERMISSION_GRANTED },
121 .grantFlags = { 1 }
122 },
123 {
124 .permissionName = "ohos.permission.MANAGE_LOCAL_ACCOUNTS",
125 .isGeneral = true,
126 .resDeviceID = { "local" },
127 .grantStatus = { PermissionState::PERMISSION_GRANTED },
128 .grantFlags = { 1 }
129 }
130 }
131 };
132
133 static HapInfoParams g_systemInfoParams = {
134 .userID = 1,
135 .bundleName = "timer",
136 .instIndex = 0,
137 .appIDDesc = "test",
138 .apiVersion = 8,
139 .isSystemApp = true
140 };
141
142 static HapPolicyParams g_policyB = { .apl = APL_NORMAL, .domain = "test.domain" };
143
144 static HapInfoParams g_notSystemInfoParams = {
145 .userID = 100,
146 .bundleName = "timer",
147 .instIndex = 0,
148 .appIDDesc = "test",
149 .apiVersion = 8,
150 .isSystemApp = false
151 };
152
153 class TimeServiceTest : public testing::Test {
154 public:
155 static void SetUpTestCase(void);
156 static void TearDownTestCase(void);
157 void SetUp();
158 void TearDown();
159 void AddPermission();
160 void DeletePermission();
161 void StartIdleTimer();
162 void DestroyIdleTimer();
163 };
164
SetUpTestCase(void)165 void TimeServiceTest::SetUpTestCase(void)
166 {
167 }
168
TearDownTestCase(void)169 void TimeServiceTest::TearDownTestCase(void)
170 {
171 }
172
SetUp(void)173 void TimeServiceTest::SetUp(void)
174 {
175 }
176
TearDown(void)177 void TimeServiceTest::TearDown(void)
178 {
179 }
180
AddPermission()181 void TimeServiceTest::AddPermission()
182 {
183 AccessTokenIDEx tokenIdEx = { 0 };
184 tokenIdEx = AccessTokenKit::AllocHapToken(g_systemInfoParams, g_policyA);
185 SetSelfTokenID(tokenIdEx.tokenIDEx);
186 }
187
DeletePermission()188 void TimeServiceTest::DeletePermission()
189 {
190 AccessTokenIDEx tokenIdEx = { 0 };
191 tokenIdEx = AccessTokenKit::AllocHapToken(g_notSystemInfoParams, g_policyB);
192 SetSelfTokenID(tokenIdEx.tokenIDEx);
193 }
194
StartIdleTimer()195 void TimeServiceTest::StartIdleTimer()
196 {
197 auto timerInfo = std::make_shared<TimerInfoTest>();
198 timerInfo->SetType(timerInfo->TIMER_TYPE_IDLE);
199 timerInfo->SetRepeat(false);
200 TimeServiceClient::GetInstance()->CreateTimerV9(timerInfo, g_idleTimerId);
201 struct timeval currentTime {};
202 gettimeofday(¤tTime, nullptr);
203 int64_t time = currentTime.tv_sec * 1000 + currentTime.tv_usec / 1000;
204 // 5000 means timer triggers after 5s
205 TimeServiceClient::GetInstance()->StartTimerV9(g_idleTimerId, time + 5000);
206 }
207
DestroyIdleTimer()208 void TimeServiceTest::DestroyIdleTimer()
209 {
210 TimeServiceClient::GetInstance()->DestroyTimerV9(g_idleTimerId);
211 }
212
TestNtpThread(const char * name)213 void TestNtpThread(const char *name)
214 {
215 {
216 std::lock_guard<std::mutex> autoLock(NtpUpdateTime::requestMutex_);
217 }
218 NtpUpdateTime::SetSystemTime();
219 }
220
221 /**
222 * @brief Wait for timer trigger
223 * @param data the global variable that callback function changes
224 * @param interval the time need to wait
225 */
WaitForAlarm(std::atomic<int> * data,int interval)226 void WaitForAlarm(std::atomic<int> * data, int interval)
227 {
228 int i = 0;
229 if (interval > 0) {
230 usleep(interval);
231 }
232 while (*data == 0 && i < ONE_HUNDRED) {
233 ++i;
234 usleep(ONE_HUNDRED*MICRO_TO_MILLISECOND);
235 }
236 }
237
238 /**
239 * @brief Check timeId in json table
240 * @param tableName the tableName
241 * @param timerId the timerId need check
242 */
CheckInJson(std::string tableName,uint64_t timerId)243 bool CheckInJson(std::string tableName, uint64_t timerId)
244 {
245 bool flag = false;
246 cJSON* db1 = NULL;
247 cJSON* data1 = CjsonHelper::GetInstance().QueryTable(tableName, &db1);
248 if (data1 != NULL) {
249 int size = cJSON_GetArraySize(data1);
250 for (int i = 0; i < size; ++i) {
251 cJSON* obj = cJSON_GetArrayItem(data1, i);
252
253 if (cJSON_GetObjectItem(obj, "timerId")->valuestring == std::to_string(timerId)) {
254 flag = true;
255 break;
256 }
257 }
258 }
259 cJSON_Delete(db1);
260 return flag;
261 }
262
263 /**
264 * @tc.name: PidProxyTimer001.
265 * @tc.desc: proxy timer.
266 * @tc.type: FUNC
267 */
268 HWTEST_F(TimeServiceTest, PidProxyTimer001, TestSize.Level0)
269 {
270 auto ret = TimeServiceClient::GetInstance()->ProxyTimer(RESERVED_UID, RESERVED_PIDLIST, true, true);
271 EXPECT_TRUE(ret);
272 ret = TimeServiceClient::GetInstance()->ProxyTimer(RESERVED_UID, RESERVED_PIDLIST, false, true);
273 EXPECT_TRUE(ret);
274 }
275
276 /**
277 * @tc.name: PidProxyTimer002.
278 * @tc.desc: proxy timer.
279 * @tc.type: FUNC
280 */
281 HWTEST_F(TimeServiceTest, PidProxyTimer002, TestSize.Level0)
282 {
283 std::set<int> pidList;
284 auto ret = TimeServiceClient::GetInstance()->ProxyTimer(RESERVED_UID, RESERVED_PIDLIST, true, true);
285 EXPECT_TRUE(ret);
286 ret = TimeServiceClient::GetInstance()->ResetAllProxy();
287 EXPECT_TRUE(ret);
288 }
289
290 /**
291 * @tc.name: PidProxyTimer003.
292 * @tc.desc: proxy timer.
293 * @tc.type: FUNC
294 */
295 HWTEST_F(TimeServiceTest, PidProxyTimer003, TestSize.Level0)
296 {
297 auto ret = TimeServiceClient::GetInstance()->ProxyTimer(RESERVED_UID, RESERVED_PIDLIST, false, true);
298 EXPECT_FALSE(ret);
299 }
300
301 /**
302 * @tc.name: PidProxyTimer004.
303 * @tc.desc: proxy timer.
304 * @tc.type: FUNC
305 * @tc.require:
306 */
307 HWTEST_F(TimeServiceTest, PidProxyTimer004, TestSize.Level0)
308 {
309 auto ret = TimeServiceClient::GetInstance()->ProxyTimer(RESERVED_UID, RESERVED_PIDLIST, true, false);
310 EXPECT_TRUE(ret);
311 ret = TimeServiceClient::GetInstance()->ProxyTimer(RESERVED_UID, RESERVED_PIDLIST, false, false);
312 EXPECT_TRUE(ret);
313 }
314
315 /**
316 * @tc.name: AdjustTimer001.
317 * @tc.desc: adjust timer.
318 * @tc.type: FUNC
319 * @tc.require:
320 */
321 HWTEST_F(TimeServiceTest, AdjustTimer001, TestSize.Level0)
322 {
323 auto errCode = TimeServiceClient::GetInstance()->AdjustTimer(true, 5, 0);
324 EXPECT_EQ(errCode, TimeError::E_TIME_OK);
325 errCode = TimeServiceClient::GetInstance()->AdjustTimer(false, 0, 0);
326 EXPECT_EQ(errCode, TimeError::E_TIME_OK);
327 }
328
329 /**
330 * @tc.name: AdjustTimer002.
331 * @tc.desc: exemption timer.
332 * @tc.type: FUNC
333 * @tc.require:
334 */
335 HWTEST_F(TimeServiceTest, AdjustTimer002, TestSize.Level0)
336 {
337 std::unordered_set<std::string> nameArr{"timer"};
338 auto errCode = TimeServiceClient::GetInstance()->SetTimerExemption(nameArr, false);
339 EXPECT_EQ(errCode, TimeError::E_TIME_OK);
340 errCode = TimeServiceClient::GetInstance()->SetTimerExemption(nameArr, true);
341 EXPECT_EQ(errCode, TimeError::E_TIME_OK);
342 }
343
344 /**
345 * @tc.name: AdjustTimer003
346 * @tc.desc: Check AdjustTimer.
347 * @tc.type: FUNC
348 */
349 HWTEST_F(TimeServiceTest, AdjustTimer003, TestSize.Level1)
350 {
351 auto res = TimeSystemAbility::GetInstance()->AdjustTimer(true, 0, 0);
352 EXPECT_EQ(res, E_TIME_READ_PARCEL_ERROR);
353 res = TimeSystemAbility::GetInstance()->AdjustTimer(true, 1, 0);
354 EXPECT_NE(res, E_TIME_READ_PARCEL_ERROR);
355 res = TimeSystemAbility::GetInstance()->AdjustTimer(false, 0, 0);
356 EXPECT_NE(res, E_TIME_READ_PARCEL_ERROR);
357 res = TimeSystemAbility::GetInstance()->AdjustTimer(false, 1, 0);
358 EXPECT_NE(res, E_TIME_READ_PARCEL_ERROR);
359 }
360
361 /**
362 * @tc.name: SetTimerExemption001
363 * @tc.desc: Check clear proxy.
364 * @tc.type: FUNC
365 */
366 HWTEST_F(TimeServiceTest, SetTimerExemption001, TestSize.Level1)
367 {
368 std::unordered_set<std::string> nameArr{"timer"};
369 for (int i = 0; i <= MAX_EXEMPTION_SIZE + 1; i++) {
370 nameArr.insert("timer" + std::to_string(i));
371 }
372 auto res = TimeServiceClient::GetInstance()->SetTimerExemption(nameArr, false);
373 EXPECT_EQ(res, E_TIME_PARAMETERS_INVALID);
374 }
375
376 /**
377 * @tc.name: ProxyTimer001
378 * @tc.desc: Check ProxyTimer.
379 * @tc.type: FUNC
380 */
381 HWTEST_F(TimeServiceTest, ProxyTimer001, TestSize.Level1)
382 {
383 std::vector<int> pidList{};
384 auto res = TimeSystemAbility::GetInstance()->ProxyTimer(0, pidList, false, false);
385 EXPECT_EQ(res, E_TIME_PARAMETERS_INVALID);
386 for (int i = 0; i <= MAX_PID_LIST_SIZE + 1; i++) {
387 pidList.push_back(0);
388 }
389 res = TimeSystemAbility::GetInstance()->ProxyTimer(0, pidList, false, false);
390 EXPECT_EQ(res, E_TIME_PARAMETERS_INVALID);
391 }
392
393 /**
394 * @tc.name: IdleTimer001.
395 * @tc.desc: test create idle timer for app.
396 * @tc.type: FUNC
397 * @tc.require:
398 */
399 HWTEST_F(TimeServiceTest, IdleTimer001, TestSize.Level0)
400 {
401 auto timerInfo = std::make_shared<TimerInfoTest>();
402 timerInfo->SetType(timerInfo->TIMER_TYPE_IDLE);
403 timerInfo->SetRepeat(false);
404 uint64_t timerId = 0;
405 TimeServiceClient::GetInstance()->CreateTimerV9(timerInfo, timerId);
406 EXPECT_NE(timerId, static_cast<uint64_t>(0));
407 TimeServiceClient::GetInstance()->DestroyTimerV9(timerId);
408 }
409
410 /**
411 * @tc.name: IdleTimer002
412 * @tc.desc: test public app start timer when device is sleeping and device sleep quit greater than timer callback.
413 * @tc.type: FUNC
414 * @tc.require:
415 */
416 HWTEST_F(TimeServiceTest, IdleTimer002, TestSize.Level0)
417 {
418 g_data1 = 0;
419 auto timerInfo = std::make_shared<TimerInfoTest>();
420 timerInfo->SetType(timerInfo->TIMER_TYPE_INEXACT_REMINDER);
421 timerInfo->SetRepeat(false);
422 timerInfo->SetCallbackInfo(TimeOutCallback1);
423 uint64_t timerId = 0;
424 TimeServiceClient::GetInstance()->CreateTimerV9(timerInfo, timerId);
425 EXPECT_NE(timerId, static_cast<uint64_t>(0));
426 StartIdleTimer();
427 struct timeval currentTime {};
428 gettimeofday(¤tTime, nullptr);
429 int64_t time = currentTime.tv_sec * 1000 + currentTime.tv_usec / 1000;
430 TimeServiceClient::GetInstance()->StartTimerV9(timerId, static_cast<uint64_t>(time) + FIVE_HUNDRED);
431 usleep(FIVE_HUNDRED*MICRO_TO_MILLISECOND);
432 EXPECT_EQ(g_data1, 0);
433 DestroyIdleTimer();
434 WaitForAlarm(&g_data1, FIVE_HUNDRED * MICRO_TO_MILLISECOND);
435 EXPECT_EQ(g_data1, 1);
436 TimeServiceClient::GetInstance()->DestroyTimerV9(timerId);
437 }
438
439 /**
440 * @tc.name: IdleTimer003
441 * @tc.desc: test public app start timer when device is sleeping and device sleep quit less than timer callback.
442 * @tc.type: FUNC
443 * @tc.require:
444 */
445 HWTEST_F(TimeServiceTest, IdleTimer003, TestSize.Level0)
446 {
447 g_data1 = 0;
448 auto timerInfo = std::make_shared<TimerInfoTest>();
449 timerInfo->SetType(timerInfo->TIMER_TYPE_INEXACT_REMINDER);
450 timerInfo->SetRepeat(false);
451 timerInfo->SetCallbackInfo(TimeOutCallback1);
452 uint64_t timerId = 0;
453 TimeServiceClient::GetInstance()->CreateTimerV9(timerInfo, timerId);
454 EXPECT_NE(timerId, static_cast<uint64_t>(0));
455 StartIdleTimer();
456 struct timeval currentTime {};
457 gettimeofday(¤tTime, nullptr);
458 int64_t time = currentTime.tv_sec * 1000 + currentTime.tv_usec / 1000;
459 TimeServiceClient::GetInstance()->StartTimerV9(timerId, static_cast<uint64_t>(time) + FIVE_HUNDRED);
460 EXPECT_EQ(g_data1, 0);
461 DestroyIdleTimer();
462 WaitForAlarm(&g_data1, FIVE_HUNDRED * MICRO_TO_MILLISECOND);
463 EXPECT_EQ(g_data1, 1);
464 TimeServiceClient::GetInstance()->DestroyTimerV9(timerId);
465 }
466
467 /**
468 * @tc.name: IdleTimer004
469 * @tc.desc: test public app start timer when device is working, device sleep immediately
470 * and timer callback greater than idle quit.
471 * @tc.type: FUNC
472 * @tc.require:
473 */
474 HWTEST_F(TimeServiceTest, IdleTimer004, TestSize.Level0)
475 {
476 g_data1 = 0;
477 auto timerInfo = std::make_shared<TimerInfoTest>();
478 timerInfo->SetType(timerInfo->TIMER_TYPE_INEXACT_REMINDER);
479 timerInfo->SetRepeat(false);
480 timerInfo->SetCallbackInfo(TimeOutCallback1);
481 uint64_t timerId = 0;
482 TimeServiceClient::GetInstance()->CreateTimerV9(timerInfo, timerId);
483 EXPECT_NE(timerId, static_cast<uint64_t>(0));
484 struct timeval currentTime {};
485 gettimeofday(¤tTime, nullptr);
486 int64_t time = currentTime.tv_sec * 1000 + currentTime.tv_usec / 1000;
487 TimeServiceClient::GetInstance()->StartTimerV9(timerId, static_cast<uint64_t>(time + FIVE_HUNDRED));
488 StartIdleTimer();
489 usleep(FIVE_HUNDRED * MICRO_TO_MILLISECOND);
490 DestroyIdleTimer();
491 WaitForAlarm(&g_data1, ONE_HUNDRED * MICRO_TO_MILLISECOND);
492 EXPECT_EQ(g_data1, 1);
493 TimeServiceClient::GetInstance()->DestroyTimerV9(timerId);
494 }
495
496 /**
497 * @tc.name: SetTime001
498 * @tc.desc: set system time.
499 * @tc.type: FUNC
500 */
501 HWTEST_F(TimeServiceTest, SetTime001, TestSize.Level1)
502 {
503 AddPermission();
504 struct timeval currentTime {
505 };
506 gettimeofday(¤tTime, NULL);
507 int64_t time = (currentTime.tv_sec + 1000) * 1000 + currentTime.tv_usec / 1000;
508 ASSERT_GT(time, 0);
509 TIME_HILOGI(TIME_MODULE_CLIENT, "Time now : %{public}" PRId64 "", time);
510 bool result = TimeServiceClient::GetInstance()->SetTime(time);
511 EXPECT_TRUE(result);
512 DeletePermission();
513 }
514
515 /**
516 * @tc.name: SetTime002
517 * @tc.desc: set system time.
518 * @tc.type: FUNC
519 */
520 HWTEST_F(TimeServiceTest, SetTime002, TestSize.Level1)
521 {
522 bool result = TimeServiceClient::GetInstance()->SetTime(-1);
523 EXPECT_FALSE(result);
524 }
525
526 /**
527 * @tc.name: SetTime003
528 * @tc.desc: set system time.
529 * @tc.type: FUNC
530 */
531 HWTEST_F(TimeServiceTest, SetTime003, TestSize.Level1)
532 {
533 bool result = TimeServiceClient::GetInstance()->SetTime(LLONG_MAX);
534 EXPECT_FALSE(result);
535 }
536
537 /**
538 * @tc.name: SetTime004
539 * @tc.desc: set system time.
540 * @tc.type: FUNC
541 */
542 HWTEST_F(TimeServiceTest, SetTime004, TestSize.Level1)
543 {
544 AddPermission();
545 struct timeval currentTime {
546 };
547 gettimeofday(¤tTime, NULL);
548 int64_t time = (currentTime.tv_sec + 1000) * 1000 + currentTime.tv_usec / 1000;
549 ASSERT_GT(time, 0);
550 TIME_HILOGI(TIME_MODULE_CLIENT, "Time now : %{public}" PRId64 "", time);
551 int32_t code;
552 bool result = TimeServiceClient::GetInstance()->SetTime(time, code);
553 EXPECT_TRUE(result);
554 EXPECT_EQ(code, 0);
555 DeletePermission();
556 }
557
558 /**
559 * @tc.name: SetTimeZone001
560 * @tc.desc: set system time zone.
561 * @tc.type: FUNC
562 */
563 HWTEST_F(TimeServiceTest, SetTimeZone001, TestSize.Level1)
564 {
565 AddPermission();
566 time_t t;
567 (void)time(&t);
568 TIME_HILOGI(TIME_MODULE_CLIENT, "Time before: %{public}s", asctime(localtime(&t)));
569 auto getCurrentTimeZone = TimeServiceClient::GetInstance()->GetTimeZone();
570 EXPECT_FALSE(getCurrentTimeZone.empty());
571
572 std::string timeZoneNicosia("Asia/Nicosia");
573 bool result = TimeServiceClient::GetInstance()->SetTimeZone(timeZoneNicosia);
574 EXPECT_TRUE(result);
575 auto getTimeZoneNicosia = TimeServiceClient::GetInstance()->GetTimeZone();
576 EXPECT_EQ(timeZoneNicosia, getTimeZoneNicosia);
577 bool ret = TimeServiceClient::GetInstance()->SetTimeZone(getCurrentTimeZone);
578 EXPECT_TRUE(ret);
579 DeletePermission();
580 }
581
582 /**
583 * @tc.name: SetTimeZone002
584 * @tc.desc: set system time zone.
585 * @tc.type: FUNC
586 */
587 HWTEST_F(TimeServiceTest, SetTimeZone002, TestSize.Level1)
588 {
589 bool result = TimeServiceClient::GetInstance()->SetTimeZone("123");
590 EXPECT_FALSE(result);
591 }
592
593 /**
594 * @tc.name: SetTimeZone003
595 * @tc.desc: set system time zone.
596 * @tc.type: FUNC
597 */
598 HWTEST_F(TimeServiceTest, SetTimeZone003, TestSize.Level1)
599 {
600 AddPermission();
601 time_t t;
602 (void)time(&t);
603 TIME_HILOGI(TIME_MODULE_CLIENT, "Time before: %{public}s", asctime(localtime(&t)));
604 auto getCurrentTimeZone = TimeServiceClient::GetInstance()->GetTimeZone();
605 EXPECT_FALSE(getCurrentTimeZone.empty());
606
607 std::string timeZoneShanghai("Asia/Shanghai");
608 int32_t code;
609 bool result = TimeServiceClient::GetInstance()->SetTimeZone(timeZoneShanghai, code);
610 EXPECT_TRUE(result);
611 EXPECT_EQ(code, 0);
612 auto getTimeZone = TimeServiceClient::GetInstance()->GetTimeZone();
613 EXPECT_EQ(getTimeZone, timeZoneShanghai);
614 bool ret = TimeServiceClient::GetInstance()->SetTimeZone(getCurrentTimeZone);
615 EXPECT_TRUE(ret);
616 DeletePermission();
617 }
618
619 /**
620 * @tc.name: GetWallTimeMs001
621 * @tc.desc: get wall time (ms).
622 * @tc.type: FUNC
623 */
624 HWTEST_F(TimeServiceTest, GetWallTimeMs001, TestSize.Level1)
625 {
626 auto time1 = TimeServiceClient::GetInstance()->GetWallTimeMs();
627 EXPECT_NE(time1, -1);
628 auto time2 = TimeServiceClient::GetInstance()->GetWallTimeMs();
629 EXPECT_GE(time2, time1);
630 }
631
632 /**
633 * @tc.name: GetWallTimeNs001
634 * @tc.desc: get wall time (ns).
635 * @tc.type: FUNC
636 */
637 HWTEST_F(TimeServiceTest, GetWallTimeNs001, TestSize.Level1)
638 {
639 auto time1 = TimeServiceClient::GetInstance()->GetWallTimeNs();
640 EXPECT_NE(time1, -1);
641 auto time2 = TimeServiceClient::GetInstance()->GetWallTimeNs();
642 EXPECT_GE(time2, time1);
643 }
644
645 /**
646 * @tc.name: GetBootTimeNs001
647 * @tc.desc: get boot time (ns).
648 * @tc.type: FUNC
649 */
650 HWTEST_F(TimeServiceTest, GetBootTimeNs001, TestSize.Level1)
651 {
652 auto time1 = TimeServiceClient::GetInstance()->GetBootTimeNs();
653 EXPECT_NE(time1, -1);
654 auto time2 = TimeServiceClient::GetInstance()->GetBootTimeNs();
655 EXPECT_GE(time2, time1);
656 }
657
658 /**
659 * @tc.name: GetMonotonicTimeMs001
660 * @tc.desc: get monotonic time (ms).
661 * @tc.type: FUNC
662 */
663 HWTEST_F(TimeServiceTest, GetMonotonicTimeMs001, TestSize.Level1)
664 {
665 auto time1 = TimeServiceClient::GetInstance()->GetMonotonicTimeMs();
666 EXPECT_NE(time1, -1);
667 auto time2 = TimeServiceClient::GetInstance()->GetMonotonicTimeMs();
668 EXPECT_GE(time2, time1);
669 }
670
671 /**
672 * @tc.name: GetMonotonicTimeNs001
673 * @tc.desc: get monotonic time (ns).
674 * @tc.type: FUNC
675 */
676 HWTEST_F(TimeServiceTest, GetMonotonicTimeNs001, TestSize.Level1)
677 {
678 auto time1 = TimeServiceClient::GetInstance()->GetMonotonicTimeNs();
679 EXPECT_NE(time1, -1);
680 auto time2 = TimeServiceClient::GetInstance()->GetMonotonicTimeNs();
681 EXPECT_GE(time2, time1);
682 }
683
684 /**
685 * @tc.name: GetThreadTimeMs001
686 * @tc.desc: get thread time (ms).
687 * @tc.type: FUNC
688 */
689 HWTEST_F(TimeServiceTest, GetThreadTimeMs001, TestSize.Level1)
690 {
691 auto time1 = TimeServiceClient::GetInstance()->GetThreadTimeMs();
692 EXPECT_NE(time1, -1);
693 }
694
695 /**
696 * @tc.name: GetThreadTimeNs001
697 * @tc.desc: get thread time (ns).
698 * @tc.type: FUNC
699 */
700 HWTEST_F(TimeServiceTest, GetThreadTimeNs001, TestSize.Level1)
701 {
702 auto time1 = TimeServiceClient::GetInstance()->GetThreadTimeNs();
703 EXPECT_NE(time1, -1);
704 }
705
706 /**
707 * @tc.name: CreateTimer001
708 * @tc.desc: Create system timer.
709 * @tc.type: FUNC
710 */
711 HWTEST_F(TimeServiceTest, CreateTimer001, TestSize.Level1)
712 {
713 AddPermission();
714 uint64_t timerId = 0;
715 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, 5);
716 EXPECT_FALSE(ret);
717 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
718 EXPECT_FALSE(ret);
719 ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId);
720 EXPECT_FALSE(ret);
721 DeletePermission();
722 }
723
724 /**
725 * @tc.name: CreateTimer002
726 * @tc.desc: Create system timer.
727 * @tc.type: FUNC
728 */
729 HWTEST_F(TimeServiceTest, CreateTimer002, TestSize.Level1)
730 {
731 AddPermission();
732 auto timerInfo = std::make_shared<TimerInfoTest>();
733 timerInfo->SetType(timerInfo->TIMER_TYPE_REALTIME);
734 timerInfo->SetRepeat(false);
735 timerInfo->SetInterval(0);
736 timerInfo->SetWantAgent(nullptr);
737 timerInfo->SetCallbackInfo(TimeOutCallback1);
738 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
739 TIME_HILOGI(TIME_MODULE_CLIENT, "timerId now : %{public}" PRId64 "", timerId);
740 EXPECT_GT(timerId, 0);
741 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, 2000);
742 EXPECT_TRUE(ret);
743 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
744 EXPECT_TRUE(ret);
745 ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId);
746 EXPECT_TRUE(ret);
747 DeletePermission();
748 }
749
750 /**
751 * @tc.name: CreateTimer003
752 * @tc.desc: Create system timer.
753 * @tc.type: FUNC
754 */
755 HWTEST_F(TimeServiceTest, CreateTimer003, TestSize.Level1)
756 {
757 AddPermission();
758 auto timerInfo = std::make_shared<TimerInfoTest>();
759 timerInfo->SetType(timerInfo->TIMER_TYPE_REALTIME);
760 timerInfo->SetRepeat(false);
761 timerInfo->SetInterval(0);
762 auto ability = std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent>();
763 timerInfo->SetWantAgent(ability);
764 timerInfo->SetCallbackInfo(TimeOutCallback1);
765 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
766 EXPECT_GT(timerId, 0);
767 DeletePermission();
768 }
769
770 /**
771 * @tc.name: CreateTimer004
772 * @tc.desc: Create system timer.
773 * @tc.type: FUNC
774 */
775 HWTEST_F(TimeServiceTest, CreateTimer004, TestSize.Level1)
776 {
777 AddPermission();
778 g_data1 = 0;
779 auto timerInfo = std::make_shared<TimerInfoTest>();
780 timerInfo->SetType(timerInfo->TIMER_TYPE_REALTIME);
781 timerInfo->SetRepeat(false);
782 timerInfo->SetInterval(0);
783 timerInfo->SetWantAgent(nullptr);
784 timerInfo->SetCallbackInfo(TimeOutCallback1);
785 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
786 EXPECT_GT(timerId, 0);
787 auto BootTimeNano = system_clock::now().time_since_epoch().count();
788 auto BootTimeMilli = BootTimeNano / NANO_TO_MILESECOND;
789 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, BootTimeMilli + 2000);
790 EXPECT_TRUE(ret);
791 ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId);
792 EXPECT_TRUE(ret);
793 EXPECT_EQ(g_data1, 0);
794 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
795 EXPECT_FALSE(ret);
796 DeletePermission();
797 }
798
799 /**
800 * @tc.name: CreateTimer005
801 * @tc.desc: Create system timer.
802 * @tc.type: FUNC
803 */
804 HWTEST_F(TimeServiceTest, CreateTimer005, TestSize.Level1)
805 {
806 AddPermission();
807 g_data1 = 1;
808 auto timerInfo = std::make_shared<TimerInfoTest>();
809 timerInfo->SetType(0);
810 timerInfo->SetRepeat(false);
811 timerInfo->SetInterval(0);
812 timerInfo->SetWantAgent(nullptr);
813 timerInfo->SetCallbackInfo(TimeOutCallback1);
814
815 struct timeval timeOfDay {
816 };
817 gettimeofday(&timeOfDay, NULL);
818 int64_t currentTime = (timeOfDay.tv_sec + 100) * 1000 + timeOfDay.tv_usec / 1000;
819 if (currentTime < 0) {
820 currentTime = 0;
821 }
822 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
823 EXPECT_GT(timerId, 0);
824
825 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, static_cast<uint64_t>(currentTime));
826 EXPECT_TRUE(ret);
827 ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId);
828 EXPECT_TRUE(ret);
829 EXPECT_EQ(g_data1, 1);
830
831 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
832 EXPECT_FALSE(ret);
833 DeletePermission();
834 }
835
836 /**
837 * @tc.name: CreateTimer006
838 * @tc.desc: Create system timer.
839 * @tc.type: FUNC
840 */
841 HWTEST_F(TimeServiceTest, CreateTimer006, TestSize.Level1)
842 {
843 AddPermission();
844 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(nullptr);
845 uint64_t ret = 0;
846 EXPECT_EQ(timerId, ret);
847 DeletePermission();
848 }
849
850 /**
851 * @tc.name: CreateTimer007
852 * @tc.desc: Create system timer with TIMER_TYPE_EXACT, then start timer with uint64_t::max.
853 * @tc.type: FUNC
854 */
855 HWTEST_F(TimeServiceTest, CreateTimer007, TestSize.Level1)
856 {
857 AddPermission();
858 g_data1 = 0;
859 auto timerInfo = std::make_shared<TimerInfoTest>();
860 timerInfo->SetType(timerInfo->TIMER_TYPE_EXACT);
861 timerInfo->SetRepeat(false);
862 timerInfo->SetInterval(0);
863 timerInfo->SetWantAgent(nullptr);
864 timerInfo->SetCallbackInfo(TimeOutCallback1);
865 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
866 EXPECT_GT(timerId, 0);
867 uint64_t max = std::numeric_limits<uint64_t>::max();
868 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, max);
869 EXPECT_TRUE(ret);
870 EXPECT_EQ(g_data1, 0);
871 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
872 EXPECT_TRUE(ret);
873 ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId);
874 EXPECT_TRUE(ret);
875 DeletePermission();
876 }
877
878 /**
879 * @tc.name: CreateTimer008
880 * @tc.desc: Create system timer with TIMER_TYPE_REALTIME and TIMER_TYPE_EXACT, then start timer with uint64_t::max.
881 * @tc.type: FUNC
882 */
883 HWTEST_F(TimeServiceTest, CreateTimer008, TestSize.Level1)
884 {
885 AddPermission();
886 g_data1 = 0;
887 auto timerInfo = std::make_shared<TimerInfoTest>();
888 timerInfo->SetType(timerInfo->TIMER_TYPE_REALTIME | timerInfo->TIMER_TYPE_EXACT);
889 timerInfo->SetRepeat(false);
890 timerInfo->SetInterval(0);
891 timerInfo->SetWantAgent(nullptr);
892 timerInfo->SetCallbackInfo(TimeOutCallback1);
893 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
894 EXPECT_GT(timerId, 0);
895 uint64_t max = std::numeric_limits<uint64_t>::max();
896 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, max);
897 EXPECT_TRUE(ret);
898 EXPECT_EQ(g_data1, 0);
899 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
900 EXPECT_TRUE(ret);
901 ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId);
902 EXPECT_TRUE(ret);
903 DeletePermission();
904 }
905
906 /**
907 * @tc.name: CreateTimer009
908 * @tc.desc: Create system timer start with one day later, then setTime to one day later.
909 * @tc.type: FUNC
910 */
911 HWTEST_F(TimeServiceTest, CreateTimer009, TestSize.Level1)
912 {
913 AddPermission();
914 g_data1 = 0;
915 struct timeval currentTime {
916 };
917 gettimeofday(¤tTime, NULL);
918 // Set the time to one day later
919 int64_t time = (currentTime.tv_sec + 86400) * 1000 + currentTime.tv_usec / 1000;
920 TIME_HILOGI(TIME_MODULE_CLIENT, "Time now : %{public}" PRId64 "", time);
921 ASSERT_GT(time, 0);
922
923 auto timerInfo = std::make_shared<TimerInfoTest>();
924 timerInfo->SetType(timerInfo->TIMER_TYPE_EXACT);
925 timerInfo->SetRepeat(true);
926 timerInfo->SetInterval(1000);
927 timerInfo->SetWantAgent(nullptr);
928 timerInfo->SetCallbackInfo(TimeOutCallback1);
929 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
930 EXPECT_GT(timerId, 0);
931 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, time);
932 EXPECT_TRUE(ret);
933
934 ret = TimeServiceClient::GetInstance()->SetTime(time);
935 EXPECT_TRUE(ret);
936
937 // wait for the second trigger success
938 while (g_data1 < 2) {
939 usleep(100000);
940 }
941 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
942 EXPECT_TRUE(ret);
943 ret = TimeServiceClient::GetInstance()->DestroyTimer(timerId);
944 EXPECT_TRUE(ret);
945 DeletePermission();
946 }
947
948 /**
949 * @tc.name: CreateTimer010
950 * @tc.desc: Create system timer.
951 * @tc.type: FUNC
952 */
953 HWTEST_F(TimeServiceTest, CreateTimer010, TestSize.Level1) {
954 AddPermission();
955 uint64_t timerId = 0;
956 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, 5);
957 EXPECT_FALSE(ret);
958 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
959 EXPECT_FALSE(ret);
960 ret = TimeServiceClient::GetInstance()->DestroyTimerAsync(timerId);
961 EXPECT_TRUE(ret);
962 DeletePermission();
963 }
964
965 /**
966 * @tc.name: CreateTimer011
967 * @tc.desc: Create system timer.
968 * @tc.type: FUNC
969 */
970 HWTEST_F(TimeServiceTest, CreateTimer011, TestSize.Level1) {
971 AddPermission();
972 g_data1 = 0;
973 auto timerInfo = std::make_shared<TimerInfoTest>();
974 timerInfo->SetType(timerInfo->TIMER_TYPE_REALTIME |
975 timerInfo->TIMER_TYPE_EXACT);
976 timerInfo->SetRepeat(false);
977 timerInfo->SetInterval(0);
978 timerInfo->SetWantAgent(nullptr);
979 timerInfo->SetCallbackInfo(TimeOutCallback1);
980 auto timerId = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
981 EXPECT_GT(timerId, 0);
982 uint64_t max = std::numeric_limits<uint64_t>::max();
983 auto ret = TimeServiceClient::GetInstance()->StartTimer(timerId, max);
984 EXPECT_TRUE(ret);
985 EXPECT_EQ(g_data1, 0);
986 ret = TimeServiceClient::GetInstance()->StopTimer(timerId);
987 EXPECT_TRUE(ret);
988 ret = TimeServiceClient::GetInstance()->DestroyTimerAsync(timerId);
989 EXPECT_TRUE(ret);
990 DeletePermission();
991 }
992
993 /**
994 * @tc.name: SntpClient001.
995 * @tc.desc: test SntpClient.
996 * @tc.type: FUNC
997 * @tc.require:
998 */
999 HWTEST_F(TimeServiceTest, SntpClient001, TestSize.Level0)
1000 {
1001 std::shared_ptr<SNTPClient> ntpClient = std::make_shared<SNTPClient>();
1002
1003 auto buffer = std::string("31234114451");
1004 auto millisecond = ntpClient->GetNtpTimestamp64(0, buffer.c_str());
1005 EXPECT_GT(millisecond, 0);
1006 millisecond = 0;
1007 millisecond = ntpClient->GetNtpField32(0, buffer.c_str());
1008 EXPECT_GT(millisecond, 0);
1009
1010 auto timeStamp = ntpClient->ConvertNtpToStamp(0);
1011 EXPECT_EQ(timeStamp, 0);
1012 timeStamp = ntpClient->ConvertNtpToStamp(100);
1013 EXPECT_EQ(timeStamp, 0);
1014 timeStamp = ntpClient->ConvertNtpToStamp(2147483648);
1015 EXPECT_EQ(timeStamp, 0);
1016 timeStamp = ntpClient->ConvertNtpToStamp(31234114451);
1017 EXPECT_EQ(timeStamp, 0);
1018 uint64_t time = 999999999911;
1019 timeStamp = ntpClient->ConvertNtpToStamp(time << 32);
1020 EXPECT_GT(timeStamp, 0);
1021 }
1022
1023 /**
1024 * @tc.name: SntpClient002.
1025 * @tc.desc: test RequestTime of SntpClient.
1026 * @tc.type: FUNC
1027 * @tc.require:
1028 */
1029 HWTEST_F(TimeServiceTest, SntpClient002, TestSize.Level0)
1030 {
1031 std::shared_ptr<SNTPClient> ntpClient = std::make_shared<SNTPClient>();
1032 auto res = ntpClient -> RequestTime("");
1033 EXPECT_FALSE(res);
1034 res = ntpClient -> RequestTime(DEFAULT_NTP_SERVER);
1035 EXPECT_TRUE(res);
1036 }
1037
1038 /**
1039 * @tc.name: SntpClient003.
1040 * @tc.desc: test SetClockOffset of SntpClient.
1041 * @tc.type: FUNC
1042 * @tc.require:
1043 */
1044 HWTEST_F(TimeServiceTest, SntpClient003, TestSize.Level0)
1045 {
1046 std::shared_ptr<SNTPClient> ntpClient = std::make_shared<SNTPClient>();
1047 ntpClient -> SetClockOffset(1);
1048 EXPECT_EQ(ntpClient -> m_clockOffset, 1);
1049 }
1050
1051 /**
1052 * @tc.name: SntpClient004.
1053 * @tc.desc: test ConvertUnixToNtp of SntpClient.
1054 * @tc.type: FUNC
1055 * @tc.require:
1056 */
1057 HWTEST_F(TimeServiceTest, SntpClient004, TestSize.Level0)
1058 {
1059 std::shared_ptr<SNTPClient> ntpClient = std::make_shared<SNTPClient>();
1060
1061 OHOS::MiscServices::SNTPClient::ntp_timestamp ntp{.second = 0, .fraction = 0};
1062 struct timeval unix;
1063 gettimeofday(&unix, nullptr);
1064 ntpClient -> ConvertUnixToNtp(&ntp, &unix);
1065 EXPECT_NE(ntp.second, 0);
1066 EXPECT_NE(ntp.fraction, 0);
1067 }
1068
1069 /**
1070 * @tc.name: SntpClient005.
1071 * @tc.desc: test CreateMessage of SntpClient.
1072 * @tc.type: FUNC
1073 * @tc.require:
1074 */
1075 HWTEST_F(TimeServiceTest, SntpClient005, TestSize.Level0)
1076 {
1077 std::shared_ptr<SNTPClient> ntpClient = std::make_shared<SNTPClient>();
1078 char sendBuf[48] = { 0 };
1079 ntpClient -> CreateMessage(sendBuf);
1080 EXPECT_EQ(sendBuf[0], '\x1B');
1081 }
1082
1083 /**
1084 * @tc.name: SntpClient006.
1085 * @tc.desc: test ReceivedMessage of SntpClient.
1086 * @tc.type: FUNC
1087 * @tc.require:
1088 */
1089 HWTEST_F(TimeServiceTest, SntpClient006, TestSize.Level0)
1090 {
1091 std::shared_ptr<SNTPClient> ntpClient = std::make_shared<SNTPClient>();
1092 char Buf[48] = {0};
1093 auto res = ntpClient -> ReceivedMessage(Buf);
1094 EXPECT_FALSE(res);
1095 Buf[32] = BYTE_SNTP_MESSAGE;
1096 res = ntpClient -> ReceivedMessage(Buf);
1097 EXPECT_FALSE(res);
1098 Buf[40] = BYTE_SNTP_MESSAGE;
1099 res = ntpClient -> ReceivedMessage(Buf);
1100 EXPECT_TRUE(res);
1101 Buf[32] = 0;
1102 res = ntpClient -> ReceivedMessage(Buf);
1103 EXPECT_FALSE(res);
1104 }
1105
1106 /**
1107 * @tc.name: SntpClient007.
1108 * @tc.desc: test GetReferenceId of SntpClient.
1109 * @tc.type: FUNC
1110 * @tc.require:
1111 */
1112 HWTEST_F(TimeServiceTest, SntpClient007, TestSize.Level0)
1113 {
1114 char Buf[5] = {'1', '2', '3', '4', '5'};
1115 int Array[5] = {0};
1116 std::shared_ptr<SNTPClient> ntpClient = std::make_shared<SNTPClient>();
1117 ntpClient -> GetReferenceId(0, Buf, Array);
1118 EXPECT_EQ(Array[0], '1');
1119 }
1120
1121 /**
1122 * @tc.name: SntpClient008.
1123 * @tc.desc: test Get of SntpClient.
1124 * @tc.type: FUNC
1125 * @tc.require:
1126 */
1127 HWTEST_F(TimeServiceTest, SntpClient008, TestSize.Level0)
1128 {
1129 std::shared_ptr<SNTPClient> ntpClient = std::make_shared<SNTPClient>();
1130 std::shared_ptr<SNTPClient::SNTPMessage> sntpMessage = std::make_shared<SNTPClient::SNTPMessage>();
1131 sntpMessage -> clear();
1132 ntpClient -> mNtpTime = 1;
1133 ntpClient -> mNtpTimeReference = 2;
1134 ntpClient -> mRoundTripTime = 3;
1135 EXPECT_EQ(ntpClient -> getNtpTime(), 1);
1136 EXPECT_EQ(ntpClient -> getNtpTimeReference(), 2);
1137 EXPECT_EQ(ntpClient -> getRoundTripTime(), 3);
1138 }
1139 /**
1140 * @tc.name: NtpTrustedTime001.
1141 * @tc.desc: test NtpTrustedTime.
1142 * @tc.type: FUNC
1143 * @tc.require:
1144 */
1145 HWTEST_F(TimeServiceTest, NtpTrustedTime001, TestSize.Level0)
1146 {
1147 std::shared_ptr<NtpTrustedTime> ntpTrustedTime = std::make_shared<NtpTrustedTime>();
1148 ntpTrustedTime->mTimeResult = nullptr;
1149 int64_t errCode = ntpTrustedTime->CurrentTimeMillis();
1150 EXPECT_EQ(errCode, -1);
1151 errCode = ntpTrustedTime->GetCacheAge();
1152 EXPECT_EQ(errCode, INT_MAX);
1153
1154 ntpTrustedTime->mTimeResult = std::make_shared<NtpTrustedTime::TimeResult>(1, 1, 0);
1155 int64_t time = ntpTrustedTime->CurrentTimeMillis();
1156 EXPECT_GT(time, 0);
1157 int64_t cacheAge = ntpTrustedTime->GetCacheAge();
1158 EXPECT_GT(cacheAge, 0);
1159 }
1160
1161 /**
1162 * @tc.name: NtpTrustedTime002.
1163 * @tc.desc: test NtpTrustedTime clear.
1164 * @tc.type: FUNC
1165 * @tc.require:
1166 */
1167 HWTEST_F(TimeServiceTest, NtpTrustedTime002, TestSize.Level0)
1168 {
1169 auto TimeResult = std::make_shared<OHOS::MiscServices::NtpTrustedTime::TimeResult>();
1170 TimeResult->Clear();
1171 EXPECT_EQ(TimeResult->mTimeMillis, 0);
1172 EXPECT_EQ(TimeResult->mElapsedRealtimeMillis, 0);
1173 EXPECT_EQ(TimeResult->mCertaintyMillis, 0);
1174 }
1175
1176 /**
1177 * @tc.name: NtpTrustedTime003.
1178 * @tc.desc: test GetTimeMillis.
1179 * @tc.type: FUNC
1180 * @tc.require:
1181 */
1182 HWTEST_F(TimeServiceTest, NtpTrustedTime003, TestSize.Level0)
1183 {
1184 auto TimeResult = std::make_shared<OHOS::MiscServices::NtpTrustedTime::TimeResult>();
1185 TimeResult->Clear();
1186 auto res = TimeResult->GetTimeMillis();
1187 EXPECT_EQ(res, 0);
1188 }
1189
1190 /**
1191 * @tc.name: TimeTick001
1192 * @tc.desc: Check RefreshNextTriggerTime().
1193 * @tc.type: FUNC
1194 * @tc.require:
1195 */
1196 HWTEST_F(TimeServiceTest, TimeTick001, TestSize.Level0)
1197 {
1198 AddPermission();
1199 int64_t time = 0;
1200 TimeUtils::GetWallTimeMs(time);
1201 time = (time / MINUTE_TO_MILLISECOND) * MINUTE_TO_MILLISECOND;
1202 bool result = TimeServiceClient::GetInstance()->SetTime(time);
1203 EXPECT_TRUE(result);
1204 auto pair = TimeTickNotify::GetInstance().RefreshNextTriggerTime();
1205 EXPECT_EQ(pair.first, time + MINUTE_TO_MILLISECOND);
1206 EXPECT_TRUE(pair.second);
1207 DeletePermission();
1208 }
1209
1210 /**
1211 * @tc.name: SetSystemTime001
1212 * @tc.desc: get ntp time.
1213 * @tc.type: FUNC
1214 */
1215 HWTEST_F(TimeServiceTest, SetSystemTime001, TestSize.Level1)
1216 {
1217 NtpUpdateTime::GetInstance().Init();
1218 std::string tmp = NtpUpdateTime::autoTimeInfo_.status;
1219 NtpUpdateTime::autoTimeInfo_.status = AUTO_TIME_STATUS_ON;
1220
1221 std::thread thread1(TestNtpThread, "thread1");
1222 std::thread thread2(TestNtpThread, "thread2");
1223 std::thread thread3(TestNtpThread, "thread3");
1224 std::thread thread4(TestNtpThread, "thread4");
1225 thread1.join();
1226 thread2.join();
1227 thread3.join();
1228 thread4.join();
1229
1230 NtpUpdateTime::autoTimeInfo_.status = tmp;
1231 }
1232
1233 /**
1234 * @tc.name: Batch001.
1235 * @tc.desc: test Batch.
1236 * @tc.type: FUNC
1237 */
1238 HWTEST_F(TimeServiceTest, Batch001, TestSize.Level0)
1239 {
1240 Batch batch;
1241 EXPECT_EQ(batch.GetStart(), std::chrono::steady_clock::time_point::min());
1242 EXPECT_EQ(batch.GetEnd(), std::chrono::steady_clock::time_point::max());
1243 EXPECT_EQ(batch.GetFlags(), 0);
1244 }
1245
1246 /**
1247 * @tc.name: TimerManager001.
1248 * @tc.desc: test ReCreateTimer.
1249 * @tc.type: FUNC
1250 */
1251 HWTEST_F(TimeServiceTest, TimerManager001, TestSize.Level0)
1252 {
1253 auto timerId1 = TIMER_ID;
1254 auto entry = std::make_shared<TimerEntry>(
1255 TimerEntry{"", timerId1, 0, 0, 0, 0, false, nullptr, nullptr, 0, 0, "bundleName"});
1256 TimerManager::GetInstance()->ReCreateTimer(timerId1, entry);
1257 std::lock_guard<std::mutex> lock(TimerManager::GetInstance()->entryMapMutex_);
1258
1259 auto map = TimerManager::GetInstance()->timerEntryMap_;
1260 auto it = map.find(timerId1);
1261 EXPECT_NE(it, map.end());
1262 if (it != map.end()) {
1263 map.erase(it);
1264 }
1265 }
1266
1267 /**
1268 * @tc.name: TimerManager002.
1269 * @tc.desc: test SetHandler with interval = milliseconds(10) < second(1).
1270 * @tc.type: FUNC
1271 */
1272 HWTEST_F(TimeServiceTest, TimerManager002, TestSize.Level0)
1273 {
1274 uint64_t max = std::numeric_limits<uint64_t>::max();
1275 TimerManager::GetInstance()->SetHandler("",
1276 TIMER_ID,
1277 0,
1278 max,
1279 10,
1280 0,
1281 1,
1282 false,
1283 nullptr,
1284 nullptr,
1285 0,
1286 0,
1287 "bundleName");
1288 std::lock_guard<std::mutex> lock(TimerManager::GetInstance()->entryMapMutex_);
1289 auto map = TimerManager::GetInstance()->timerEntryMap_;
1290 auto it = map.find(TIMER_ID);
1291 EXPECT_NE(it, map.end());
1292 if (it != map.end()) {
1293 map.erase(it);
1294 }
1295 }
1296
1297 /**
1298 * @tc.name: TimerManager003.
1299 * @tc.desc: test Set() with type > ALARM_TYPE_COUNT.
1300 * @tc.type: FUNC
1301 */
1302 HWTEST_F(TimeServiceTest, TimerManager003, TestSize.Level0)
1303 {
1304 auto when = std::chrono::nanoseconds::zero();
1305 auto bootTime = std::chrono::steady_clock::now();
1306 auto res = TimerManager::GetInstance()->handler_->Set(6, when, bootTime);
1307 EXPECT_EQ(res, -1);
1308 }
1309
1310 /**
1311 * @tc.name: TimerManager004.
1312 * @tc.desc: test StartTimer with UidProxy and PidProxy.
1313 * @tc.type: FUNC
1314 */
1315 HWTEST_F(TimeServiceTest, TimerManager004, TestSize.Level0)
1316 {
1317 TimerManager::GetInstance()->DestroyTimer(TIMER_ID);
1318 auto entry = std::make_shared<TimerEntry>(
1319 TimerEntry{"", TIMER_ID, 0, 0, 0, 0, false, nullptr, nullptr, UID, PID, "bundleName"});
1320 TimerManager::GetInstance()->ReCreateTimer(TIMER_ID, entry);
1321 auto key1 = GetProxyKey(UID, 0);
1322 auto key2 = GetProxyKey(UID, PID);
1323 {
1324 std::lock_guard<std::mutex> lock(TimerProxy::GetInstance().proxyMutex_);
1325 std::vector<uint64_t> timerList;
1326 TimerProxy::GetInstance().proxyTimers_.insert(std::make_pair(key1, timerList));
1327 }
1328 auto res = TimerManager::GetInstance()->StartTimer(TIMER_ID, 0);
1329 EXPECT_EQ(res, E_TIME_OK);
1330
1331 {
1332 std::lock_guard<std::mutex> lock(TimerProxy::GetInstance().proxyMutex_);
1333 auto map = TimerProxy::GetInstance().proxyTimers_;
1334 auto it = map.find(key1);
1335 if (it != map.end()) {
1336 map.erase(it);
1337 }
1338 }
1339 {
1340 std::lock_guard<std::mutex> lock(TimerProxy::GetInstance().proxyMutex_);
1341 auto map = TimerProxy::GetInstance().proxyTimers_;
1342 std::vector<uint64_t> timerList;
1343 TimerProxy::GetInstance().proxyTimers_.insert(std::make_pair(key2, timerList));
1344 }
1345 res = TimerManager::GetInstance()->StartTimer(TIMER_ID, 0);
1346 EXPECT_EQ(res, E_TIME_OK);
1347
1348 {
1349 std::lock_guard<std::mutex> lock(TimerProxy::GetInstance().proxyMutex_);
1350 auto map = TimerProxy::GetInstance().proxyTimers_;
1351 auto it = map.find(key2);
1352 if (it != map.end()) {
1353 map.erase(it);
1354 }
1355 }
1356
1357 TimerManager::GetInstance()->DestroyTimer(TIMER_ID);
1358 }
1359
1360 /**
1361 * @tc.name: TimerManager005.
1362 * @tc.desc: test NotifyWantAgent.
1363 * @tc.type: FUNC
1364 */
1365 HWTEST_F(TimeServiceTest, TimerManager005, TestSize.Level0)
1366 {
1367 TimerManager::GetInstance()->NotifyWantAgentRetry(nullptr);
1368
1369 auto duration = std::chrono::milliseconds::zero();
1370 auto timePoint = std::chrono::steady_clock::now();
1371 auto timerInfo = std::make_shared<TimerInfo>("", TIMER_ID, 0, duration, timePoint, duration, timePoint, duration,
1372 nullptr, nullptr, 0, false, 0, 0, "");
1373 auto res = TimerManager::GetInstance()->NotifyWantAgent(timerInfo);
1374 EXPECT_FALSE(res);
1375 #ifdef RDB_ENABLE
1376 OHOS::NativeRdb::ValuesBucket insertValues;
1377 insertValues.PutLong("timerId", TIMER_ID);
1378 insertValues.PutInt("type", 0);
1379 insertValues.PutInt("flag", 0);
1380 insertValues.PutLong("windowLength", 0);
1381 insertValues.PutLong("interval", 0);
1382 insertValues.PutInt("uid", 0);
1383 insertValues.PutString("bundleName", "");
1384 std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent = nullptr;
1385 insertValues.PutString("wantAgent", OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(wantAgent));
1386 insertValues.PutInt("state", 0);
1387 insertValues.PutLong("triggerTime", static_cast<int64_t>(std::numeric_limits<int64_t>::max()));
1388 TimeDatabase::GetInstance().Insert(HOLD_ON_REBOOT, insertValues);
1389 #else
1390 auto entry = std::make_shared<TimerEntry>(
1391 TimerEntry{"", TIMER_ID, 0, 0, 0, 0, false, nullptr, nullptr, 0, 0, "bundleName"});
1392 CjsonHelper::GetInstance().Insert(HOLD_ON_REBOOT, entry);
1393 #endif
1394 res = TimerManager::GetInstance()->NotifyWantAgent(timerInfo);
1395 EXPECT_FALSE(res);
1396 #ifdef RDB_ENABLE
1397 OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(HOLD_ON_REBOOT);
1398 rdbPredicatesDelete.EqualTo("timerId", static_cast<int64_t>(TIMER_ID));
1399 TimeDatabase::GetInstance().Delete(rdbPredicatesDelete);
1400 #else
1401 CjsonHelper::GetInstance().Delete(HOLD_ON_REBOOT, TIMER_ID);
1402 #endif
1403 }
1404
1405 /**
1406 * @tc.name: TimerManager006.
1407 * @tc.desc: test AdjustTimer.
1408 * @tc.type: FUNC
1409 */
1410 HWTEST_F(TimeServiceTest, TimerManager006, TestSize.Level0)
1411 {
1412 uint32_t interval;
1413 bool isAdjust;
1414 // Set 1000 as interval, because interval can not be 0;
1415 uint32_t intervalSet = 1000;
1416 {
1417 std::lock_guard<std::mutex> lock(TimerManager::GetInstance()->mutex_);
1418 interval = TimerManager::GetInstance()->adjustInterval_;
1419 TimerManager::GetInstance()->adjustInterval_ = intervalSet;
1420 isAdjust = TimerManager::GetInstance()->adjustPolicy_;
1421 }
1422
1423 auto res = TimerManager::GetInstance()->AdjustTimer(isAdjust, intervalSet, 0);
1424 EXPECT_FALSE(res);
1425 res = TimerManager::GetInstance()->AdjustTimer(!isAdjust, intervalSet, 0);
1426 EXPECT_TRUE(res);
1427 res = TimerManager::GetInstance()->AdjustTimer(isAdjust, intervalSet + 1, 0);
1428 EXPECT_TRUE(res);
1429 res = TimerManager::GetInstance()->AdjustTimer(isAdjust, intervalSet, 0);
1430 EXPECT_TRUE(res);
1431
1432 std::lock_guard<std::mutex> lock(TimerManager::GetInstance()->mutex_);
1433 TimerManager::GetInstance()->adjustInterval_ = interval;
1434 TimerManager::GetInstance()->adjustPolicy_ = isAdjust;
1435 }
1436
1437 /**
1438 * @tc.name: TimerManager007.
1439 * @tc.desc: test AdjustDeliveryTimeBasedOnDeviceIdle.
1440 * @tc.type: FUNC
1441 */
1442 HWTEST_F(TimeServiceTest, TimerManager007, TestSize.Level0)
1443 {
1444 auto duration = std::chrono::milliseconds::zero();
1445 auto timePoint = std::chrono::steady_clock::now();
1446 auto timerInfo1 = std::make_shared<TimerInfo>("", TIMER_ID, 0, duration, timePoint, duration, timePoint, duration,
1447 nullptr, nullptr, 0, false, 0, 0, "");
1448 std::lock_guard<std::mutex> lock(TimerManager::GetInstance()->mutex_);
1449 auto alarm = TimerManager::GetInstance()->mPendingIdleUntil_;
1450 TimerManager::GetInstance()->mPendingIdleUntil_ = timerInfo1;
1451 auto res = TimerManager::GetInstance()->AdjustDeliveryTimeBasedOnDeviceIdle(timerInfo1);
1452 EXPECT_FALSE(res);
1453
1454 TimerManager::GetInstance()->mPendingIdleUntil_ = nullptr;
1455 TimerManager::GetInstance()->delayedTimers_[TIMER_ID] = std::chrono::steady_clock::now();
1456 res = TimerManager::GetInstance()->AdjustDeliveryTimeBasedOnDeviceIdle(timerInfo1);
1457 EXPECT_TRUE(res);
1458 auto duration1 = std::chrono::duration_cast<std::chrono::milliseconds>(
1459 (timePoint + std::chrono::hours(1)).time_since_epoch());
1460 auto timerInfo2 = std::make_shared<TimerInfo>("", TIMER_ID, 1, duration1, timePoint, duration, timePoint, duration,
1461 nullptr, nullptr, 0, false, 0, 0, "");
1462 res = TimerManager::GetInstance()->AdjustDeliveryTimeBasedOnDeviceIdle(timerInfo2);
1463 EXPECT_TRUE(res);
1464 auto timerInfo3 = std::make_shared<TimerInfo>("", TIMER_ID, 2, duration, timePoint, duration, timePoint, duration,
1465 nullptr, nullptr, 0, false, 0, 0, "");
1466 res = TimerManager::GetInstance()->AdjustDeliveryTimeBasedOnDeviceIdle(timerInfo3);
1467 EXPECT_TRUE(res);
1468
1469 TimerManager::GetInstance()->mPendingIdleUntil_ = alarm;
1470 }
1471
1472 #ifdef HIDUMPER_ENABLE
1473 /**
1474 * @tc.name: TimerManager008.
1475 * @tc.desc: test ShowTimerEntryById TIMER_ID not in timerEntryMap_.
1476 * @tc.type: FUNC
1477 */
1478 HWTEST_F(TimeServiceTest, TimerManager008, TestSize.Level0)
1479 {
1480 TimerManager::GetInstance()->DestroyTimer(TIMER_ID);
1481
1482 auto res = TimerManager::GetInstance()->ShowTimerEntryById(0, TIMER_ID);
1483 EXPECT_FALSE(res);
1484 }
1485
1486 /**
1487 * @tc.name: TimerManager009.
1488 * @tc.desc: test ShowTimerTriggerById TIMER_ID in alarmBatches_.
1489 * @tc.type: FUNC
1490 */
1491 HWTEST_F(TimeServiceTest, TimerManager009, TestSize.Level0)
1492 {
1493 auto entry = std::make_shared<TimerEntry>(
1494 TimerEntry{"", TIMER_ID, 0, 0, 0, 0, false, nullptr, nullptr, 0, 0, "bundleName"});
1495 TimerManager::GetInstance()->ReCreateTimer(TIMER_ID, entry);
1496 uint64_t triggerTime = std::numeric_limits<uint64_t>::max();
1497 TimerManager::GetInstance()->StartTimer(TIMER_ID, triggerTime);
1498 auto res = TimerManager::GetInstance()->ShowTimerTriggerById(0, TIMER_ID);
1499 TimerManager::GetInstance()->DestroyTimer(TIMER_ID);
1500 EXPECT_TRUE(res);
1501 }
1502 #endif
1503
1504 /**
1505 * @tc.name: TimerManager010.
1506 * @tc.desc: test HandleRSSDeath.
1507 * @tc.type: FUNC
1508 */
1509 HWTEST_F(TimeServiceTest, TimerManager010, TestSize.Level0)
1510 {
1511 std::shared_ptr<TimerInfo> alarm;
1512 {
1513 std::lock_guard <std::mutex> lock(TimerManager::GetInstance()->mutex_);
1514 alarm = TimerManager::GetInstance()->mPendingIdleUntil_;
1515 TimerManager::GetInstance()->mPendingIdleUntil_ = nullptr;
1516 }
1517 TimerManager::GetInstance()->HandleRSSDeath();
1518
1519 auto duration = std::chrono::milliseconds::zero();
1520 auto timePoint = std::chrono::steady_clock::now();
1521 auto timerInfo = std::make_shared<TimerInfo>("", TIMER_ID, 0, duration, timePoint, duration, timePoint, duration,
1522 nullptr, nullptr, 0, false, 0, 0, "");
1523 {
1524 std::lock_guard <std::mutex> lock(TimerManager::GetInstance()->mutex_);
1525 TimerManager::GetInstance()->mPendingIdleUntil_ = timerInfo;
1526 }
1527 auto entry = std::make_shared<TimerEntry>(
1528 TimerEntry{"", TIMER_ID, 0, 0, 0, 0, false, nullptr, nullptr, 0, 0, "bundleName"});
1529 TimerManager::GetInstance()->ReCreateTimer(TIMER_ID, entry);
1530 TimerManager::GetInstance()->HandleRSSDeath();
1531 auto res = TimerManager::GetInstance()->DestroyTimer(TIMER_ID);
1532 EXPECT_EQ(res, E_TIME_NOT_FOUND);
1533
1534 {
1535 std::lock_guard <std::mutex> lock(TimerManager::GetInstance()->mutex_);
1536 TimerManager::GetInstance()->mPendingIdleUntil_ = alarm;
1537 }
1538 }
1539
1540 /**
1541 * @tc.name: TimerManager011.
1542 * @tc.desc: test OnPackageRemoved.
1543 * @tc.type: FUNC
1544 */
1545 HWTEST_F(TimeServiceTest, TimerManager011, TestSize.Level0)
1546 {
1547 auto timerManager = TimerManager::GetInstance();
1548 {
1549 std::lock_guard<std::mutex> lock(timerManager->entryMapMutex_);
1550 timerManager->timerEntryMap_.clear();
1551 }
1552
1553 auto entry = std::make_shared<TimerEntry>(
1554 TimerEntry{"", TIMER_ID, 0, 0, 0, 0, false, nullptr, nullptr, UID, 0, "bundleName"});
1555 timerManager->ReCreateTimer(TIMER_ID, entry);
1556 timerManager->OnPackageRemoved(UID);
1557
1558 {
1559 std::lock_guard<std::mutex> lock(timerManager->entryMapMutex_);
1560 auto map = timerManager->timerEntryMap_;
1561 auto it = map.find(TIMER_ID);
1562 EXPECT_EQ(it, map.end());
1563 if (it != map.end()) {
1564 map.erase(it);
1565 }
1566 }
1567 }
1568
1569 /**
1570 * @tc.name: TimerManager012.
1571 * @tc.desc: test record and delete of timerCount_.
1572 * @tc.type: FUNC
1573 */
1574 HWTEST_F(TimeServiceTest, TimerManager012, TestSize.Level0)
1575 {
1576 int uid1 = UID;
1577 int uid2 = UID + 1;
1578 TimerManager::GetInstance()->timerCount_.clear();
1579 for (int i = 0; i < 10; ++i) {
1580 TimerManager::GetInstance()->IncreaseTimerCount(uid1);
1581 }
1582 EXPECT_EQ(TimerManager::GetInstance()->timerCount_.size(), 1);
1583 auto it = std::find_if(TimerManager::GetInstance()->timerCount_.begin(),
1584 TimerManager::GetInstance()->timerCount_.end(),
__anon98203f020202(const std::pair<int32_t, size_t>& pair) 1585 [uid1](const std::pair<int32_t, size_t>& pair) {
1586 return pair.first == uid1;
1587 });
1588 EXPECT_EQ(it->second, 10);
1589 for (int i = 0; i < 10; ++i) {
1590 TimerManager::GetInstance()->IncreaseTimerCount(uid2);
1591 }
1592 EXPECT_EQ(TimerManager::GetInstance()->timerCount_.size(), 2);
1593 for (int i = 0; i < 5; ++i) {
1594 TimerManager::GetInstance()->DecreaseTimerCount(uid2);
1595 }
1596 it = std::find_if(TimerManager::GetInstance()->timerCount_.begin(),
1597 TimerManager::GetInstance()->timerCount_.end(),
__anon98203f020302(const std::pair<int32_t, size_t>& pair) 1598 [uid2](const std::pair<int32_t, size_t>& pair) {
1599 return pair.first == uid2;
1600 });
1601 EXPECT_EQ(it->second, 5);
1602 }
1603
1604 /**
1605 * @tc.name: TimerManager013.
1606 * @tc.desc: test when create and delete timer, the change of timerOutOfRangeTimes_.
1607 * @tc.type: FUNC
1608 */
1609 HWTEST_F(TimeServiceTest, TimerManager013, TestSize.Level0)
1610 {
1611 TimerManager::GetInstance()->timerEntryMap_.clear();
1612 TimerManager::GetInstance()->timerCount_.clear();
1613 TimerManager::GetInstance()->timerOutOfRangeTimes_ = 0;
1614 uint64_t i = 0;
1615 for (; i <= TIMER_ALARM_COUNT; ++i) {
1616 auto entry = std::make_shared<TimerEntry>(
1617 TimerEntry{"", i, 0, 0, 0, 0, false, nullptr, nullptr, 0, 0, "bundleName"});
1618 TimerManager::GetInstance()->ReCreateTimer(i, entry);
1619 }
1620 EXPECT_EQ(TimerManager::GetInstance()->timerOutOfRangeTimes_, 1);
1621 for (; i <= TIMER_ALARM_COUNT * 2; ++i) {
1622 auto entry = std::make_shared<TimerEntry>(
1623 TimerEntry{"", i, 0, 0, 0, 0, false, nullptr, nullptr, 0, 0, "bundleName"});
1624 TimerManager::GetInstance()->ReCreateTimer(i, entry);
1625 }
1626 EXPECT_EQ(TimerManager::GetInstance()->timerOutOfRangeTimes_, 2);
1627 }
1628
1629 /**
1630 * @tc.name: TimerManager014.
1631 * @tc.desc: test create two timer with same name.
1632 * @tc.type: FUNC
1633 */
1634 HWTEST_F(TimeServiceTest, TimerManager014, TestSize.Level0)
1635 {
1636 TIME_HILOGI(TIME_MODULE_CLIENT, "TimerManager014 start");
1637 TimerManager::GetInstance()->timerNameMap_.clear();
1638 auto entry = std::make_shared<TimerEntry>(
1639 TimerEntry{"name", TIMER_ID, 0, 0, 0, 0, false, nullptr, nullptr, UID, 0, "bundleName"});
1640 TimerManager::GetInstance()->ReCreateTimer(TIMER_ID, entry);
1641 auto timerNameMap = TimerManager::GetInstance()->timerNameMap_;
1642 EXPECT_NE(timerNameMap.find(UID), timerNameMap.end());
1643 EXPECT_NE(timerNameMap[UID].find("name"), timerNameMap[UID].end());
1644 EXPECT_EQ(timerNameMap[UID]["name"], TIMER_ID);
1645
1646 entry = std::make_shared<TimerEntry>(
1647 TimerEntry{"name", TIMER_ID + 1, 0, 0, 0, 0, false, nullptr, nullptr, UID, 0, "bundleName"});
1648 TimerManager::GetInstance()->ReCreateTimer(TIMER_ID + 1, entry);
1649 timerNameMap = TimerManager::GetInstance()->timerNameMap_;
1650 EXPECT_NE(timerNameMap.find(UID), timerNameMap.end());
1651 EXPECT_NE(timerNameMap[UID].find("name"), timerNameMap[UID].end());
1652 EXPECT_EQ(timerNameMap[UID]["name"], TIMER_ID + 1);
1653 auto ret = TimerManager::GetInstance()->DestroyTimer(TIMER_ID);
1654 EXPECT_NE(ret, E_TIME_OK);
1655 }
1656
1657 /**
1658 * @tc.name: TimerManager015.
1659 * @tc.desc: test check timer .
1660 * @tc.type: FUNC
1661 */
1662 HWTEST_F(TimeServiceTest, TimerManager015, TestSize.Level0)
1663 {
1664 TimerManager::GetInstance()->timerNameMap_.clear();
1665 for (int i = 0; i < 101; i++)
1666 {
1667 auto entry = std::make_shared<TimerEntry>(
1668 TimerEntry{"name", TIMER_ID + i, 0, 0, 0, 0, false, nullptr, nullptr, UID, 0, "bundleName"});
1669 TimerManager::GetInstance()->ReCreateTimer(TIMER_ID, entry);
1670 }
1671 auto lastTimer = std::chrono::steady_clock::now() - std::chrono::minutes(61);
1672 TimerManager::GetInstance()->lastTimerOutOfRangeTime_ = lastTimer;
1673 TimerManager::GetInstance()->CheckTimerCount();
1674 EXPECT_NE(TimerManager::GetInstance()->lastTimerOutOfRangeTime_, lastTimer);
1675 TimerManager::GetInstance()->timerNameMap_.clear();
1676 }
1677
1678 /**
1679 * @tc.name: TimerManager016.
1680 * @tc.desc: test update or delete database .
1681 * @tc.type: FUNC
1682 */
1683 HWTEST_F(TimeServiceTest, TimerManager016, TestSize.Level0)
1684 {
1685 OHOS::NativeRdb::ValuesBucket insertValues;
1686 insertValues.PutLong("timerId", TIMER_ID);
1687 insertValues.PutInt("type", 0);
1688 insertValues.PutInt("flag", 0);
1689 insertValues.PutLong("windowLength", 0);
1690 insertValues.PutLong("interval", 0);
1691 insertValues.PutInt("uid", 0);
1692 insertValues.PutString("bundleName", "");
1693 std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent = nullptr;
1694 insertValues.PutString("wantAgent", OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(wantAgent));
1695 insertValues.PutInt("state", 0);
1696 insertValues.PutLong("triggerTime", static_cast<int64_t>(std::numeric_limits<int64_t>::max()));
1697 TimeDatabase::GetInstance().Insert(HOLD_ON_REBOOT, insertValues);
1698 TimerManager::GetInstance()->UpdateOrDeleteDatabase(true, TIMER_ID, true);
1699 OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(HOLD_ON_REBOOT);
1700 rdbPredicatesDelete.EqualTo("timerId", static_cast<int64_t>(TIMER_ID));
1701 int count = 0;
1702 TimeDatabase::GetInstance().Query(rdbPredicatesDelete, {"timerId"})->GetRowCount(count);
1703 EXPECT_EQ(count, 0);
1704 }
1705
1706 /**
1707 * @tc.name: TimerManager017.
1708 * @tc.desc: test timer database when store is nullptr.
1709 * @tc.type: FUNC
1710 */
1711 HWTEST_F(TimeServiceTest, TimerManager017, TestSize.Level0)
1712 {
1713 auto DataBase = TimeDatabase::GetInstance();
1714 DataBase.ClearDropOnReboot();
1715 DataBase.ClearInvaildDataInHoldOnReboot();
1716 auto storeptr = DataBase.store_;
1717 DataBase.store_ = nullptr;
1718 OHOS::NativeRdb::ValuesBucket Values;
1719 OHOS::NativeRdb::RdbPredicates rdbPredicates(HOLD_ON_REBOOT);
1720 DataBase.ClearDropOnReboot();
1721 DataBase.ClearInvaildDataInHoldOnReboot();
1722 auto res = DataBase.Insert(HOLD_ON_REBOOT, Values);
1723 EXPECT_FALSE(res);
1724 res = DataBase.Update(Values, rdbPredicates);
1725 EXPECT_FALSE(res);
1726 auto queryres = DataBase.Query(rdbPredicates, {"something"});
1727 EXPECT_EQ(queryres, nullptr);
1728 res = DataBase.Delete(rdbPredicates);
1729 EXPECT_FALSE(res);
1730 DataBase.store_ = storeptr;
1731 }
1732
1733 /**
1734 * @tc.name: SystemAbility001.
1735 * @tc.desc: test OnStop.
1736 * @tc.type: FUNC
1737 */
1738 HWTEST_F(TimeServiceTest, SystemAbility001, TestSize.Level0)
1739 {
1740 TimeSystemAbility::GetInstance()->OnStop();
1741 EXPECT_EQ(TimeSystemAbility::GetInstance()->state_, ServiceRunningState::STATE_NOT_START);
1742 TimeSystemAbility::GetInstance()->OnStop();
1743 EXPECT_EQ(TimeSystemAbility::GetInstance()->state_, ServiceRunningState::STATE_NOT_START);
1744 }
1745
1746 #ifdef RDB_ENABLE
1747 /**
1748 * @tc.name: SystemAbility002.
1749 * @tc.desc: test RecoverTimer.
1750 * @tc.type: FUNC
1751 */
1752 HWTEST_F(TimeServiceTest, SystemAbility002, TestSize.Level0)
1753 {
1754 uint64_t timerId1 = TIMER_ID;
1755 uint64_t timerId2 = TIMER_ID + 1;
1756
1757 auto map = TimerManager::GetInstance()->timerEntryMap_;
1758 auto it = map.find(timerId1);
1759 if (it != map.end()) {
1760 map.erase(it);
1761 }
1762 it = map.find(timerId2);
1763 if (it != map.end()) {
1764 map.erase(it);
1765 }
1766
1767 OHOS::NativeRdb::ValuesBucket insertValues1;
1768 insertValues1.PutLong("timerId", timerId1);
1769 insertValues1.PutInt("type", 0);
1770 insertValues1.PutInt("flag", 0);
1771 insertValues1.PutLong("windowLength", 0);
1772 insertValues1.PutLong("interval", 0);
1773 insertValues1.PutInt("uid", 0);
1774 insertValues1.PutString("bundleName", "");
1775 std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent = nullptr;
1776 insertValues1.PutString("wantAgent", OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(wantAgent));
1777 insertValues1.PutInt("state", 0);
1778 insertValues1.PutLong("triggerTime", static_cast<int64_t>(std::numeric_limits<int64_t>::max()));
1779 TimeDatabase::GetInstance().Insert(HOLD_ON_REBOOT, insertValues1);
1780
1781 OHOS::NativeRdb::ValuesBucket insertValues2;
1782 insertValues2.PutLong("timerId", timerId2);
1783 insertValues2.PutInt("type", 0);
1784 insertValues2.PutInt("flag", 0);
1785 insertValues2.PutLong("windowLength", 0);
1786 insertValues2.PutLong("interval", 0);
1787 insertValues2.PutInt("uid", 0);
1788 insertValues2.PutString("bundleName", "");
1789 wantAgent = std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent>();
1790 insertValues2.PutString("wantAgent", OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(wantAgent));
1791 insertValues2.PutInt("state", 0);
1792 insertValues2.PutLong("triggerTime", static_cast<int64_t>(std::numeric_limits<int64_t>::max()));
1793 TimeDatabase::GetInstance().Insert(DROP_ON_REBOOT, insertValues2);
1794
1795 TimeSystemAbility::GetInstance()->RecoverTimer();
1796
1797 it = map.find(timerId1);
1798 EXPECT_EQ(it, map.end());
1799 it = map.find(timerId2);
1800 EXPECT_EQ(it, map.end());
1801
1802 OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete1(HOLD_ON_REBOOT);
1803 rdbPredicatesDelete1.EqualTo("timerId", static_cast<int64_t>(timerId1));
1804 TimeDatabase::GetInstance().Delete(rdbPredicatesDelete1);
1805
1806 OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete2(DROP_ON_REBOOT);
1807 rdbPredicatesDelete2.EqualTo("timerId", static_cast<int64_t>(timerId2));
1808 TimeDatabase::GetInstance().Delete(rdbPredicatesDelete2);
1809 }
1810 #endif
1811
1812 #ifdef SET_AUTO_REBOOT_ENABLE
1813 /**
1814 * @tc.name: SystemAbility003.
1815 * @tc.desc: test SetAutoReboot.
1816 * @tc.type: FUNC
1817 */
1818 HWTEST_F(TimeServiceTest, SystemAbility003, TestSize.Level0)
1819 {
1820 uint64_t timerId1 = TIMER_ID;
1821
1822 TimeSystemAbility::GetInstance()->SetAutoReboot();
1823
1824 OHOS::NativeRdb::ValuesBucket insertValues1;
1825 insertValues1.PutLong("timerId", timerId1);
1826 insertValues1.PutInt("type", 0);
1827 insertValues1.PutInt("flag", 0);
1828 insertValues1.PutLong("windowLength", 0);
1829 insertValues1.PutLong("interval", 0);
1830 insertValues1.PutInt("uid", 0);
1831 insertValues1.PutString("bundleName", "anything");
1832 insertValues1.PutString("wantAgent", "");
1833 insertValues1.PutInt("state", 1);
1834 insertValues1.PutLong("triggerTime", static_cast<int64_t>(0));
1835 auto res = TimeDatabase::GetInstance().Insert(HOLD_ON_REBOOT, insertValues1);
1836 EXPECT_EQ(res, true);
1837
1838 TimeSystemAbility::GetInstance()->SetAutoReboot();
1839
1840 OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete1(HOLD_ON_REBOOT);
1841 rdbPredicatesDelete1.EqualTo("timerId", static_cast<int64_t>(timerId1));
1842 TimeDatabase::GetInstance().Delete(rdbPredicatesDelete1);
1843 }
1844 #endif
1845
1846 /**
1847 * @tc.name: SystemAbility004.
1848 * @tc.desc: test SetRealTime.
1849 * @tc.type: FUNC
1850 */
1851 HWTEST_F(TimeServiceTest, SystemAbility004, TestSize.Level0)
1852 {
1853 auto res = TimeSystemAbility::GetInstance()->SetRealTime(-1);
1854 EXPECT_FALSE(res);
1855 }
1856
1857 /**
1858 * @tc.name: SystemAbility005.
1859 * @tc.desc: test SetAutoReboot.
1860 * @tc.type: FUNC
1861 */
1862 HWTEST_F(TimeServiceTest, SystemAbility005, TestSize.Level0)
1863 {
1864 uint64_t timerId1 = TIMER_ID;
1865
1866 TimeSystemAbility::GetInstance()->SetAutoReboot();
1867
1868 OHOS::NativeRdb::ValuesBucket insertValues1;
1869 insertValues1.PutLong("timerId", timerId1);
1870 insertValues1.PutInt("type", 0);
1871 insertValues1.PutInt("flag", 0);
1872 insertValues1.PutLong("windowLength", 0);
1873 insertValues1.PutLong("interval", 0);
1874 insertValues1.PutInt("uid", 0);
1875 insertValues1.PutString("bundleName", "anything");
1876 insertValues1.PutString("wantAgent", "");
1877 insertValues1.PutInt("state", 1);
1878 insertValues1.PutLong("triggerTime", std::numeric_limits<int64_t>::max());
1879 insertValues1.PutString("name", "");
1880 auto res = TimeDatabase::GetInstance().Insert(HOLD_ON_REBOOT, insertValues1);
1881 EXPECT_EQ(res, true);
1882
1883 TimeSystemAbility::GetInstance()->SetAutoReboot();
1884
1885 OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete1(HOLD_ON_REBOOT);
1886 rdbPredicatesDelete1.EqualTo("timerId", static_cast<int64_t>(timerId1));
1887 TimeDatabase::GetInstance().Delete(rdbPredicatesDelete1);
1888 }
1889
1890 #ifdef RDB_ENABLE
1891 /**
1892 * @tc.name: TimeDatabase001.
1893 * @tc.desc: test TimeDatabase Insert.
1894 * @tc.type: FUNC
1895 */
1896 HWTEST_F(TimeServiceTest, TimeDatabase001, TestSize.Level0)
1897 {
1898 OHOS::NativeRdb::ValuesBucket insertValues;
1899 insertValues.PutLong("something", 0);
1900 auto res = TimeDatabase::GetInstance().Insert(DROP_ON_REBOOT, insertValues);
1901 EXPECT_FALSE(res);
1902 }
1903
1904 /**
1905 * @tc.name: TimeDatabase002.
1906 * @tc.desc: test TimeDatabase Update.
1907 * @tc.type: FUNC
1908 */
1909 HWTEST_F(TimeServiceTest, TimeDatabase002, TestSize.Level0)
1910 {
1911 OHOS::NativeRdb::ValuesBucket values;
1912 values.PutInt("something", 1);
1913 OHOS::NativeRdb::RdbPredicates rdbPredicates(DROP_ON_REBOOT);
1914 rdbPredicates.EqualTo("something", 0)->And()->EqualTo("something", static_cast<int64_t>(0));
1915 auto res = TimeDatabase::GetInstance().Update(values, rdbPredicates);
1916 EXPECT_FALSE(res);
1917 }
1918
1919 /**
1920 * @tc.name: TimeDatabase003.
1921 * @tc.desc: test TimeDatabase Delete.
1922 * @tc.type: FUNC
1923 */
1924 HWTEST_F(TimeServiceTest, TimeDatabase003, TestSize.Level0)
1925 {
1926 OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(DROP_ON_REBOOT);
1927 rdbPredicatesDelete.EqualTo("something", static_cast<int64_t>(0));
1928 auto res = TimeDatabase::GetInstance().Delete(rdbPredicatesDelete);
1929 EXPECT_FALSE(res);
1930 }
1931 #endif
1932
1933 /**
1934 * @tc.name: TimerInfo001.
1935 * @tc.desc: test UpdateWhenElapsedFromNow.
1936 * @tc.type: FUNC
1937 */
1938 HWTEST_F(TimeServiceTest, TimerInfo001, TestSize.Level0)
1939 {
1940 auto duration = std::chrono::milliseconds::zero();
1941 auto timePoint = std::chrono::steady_clock::now();
1942 auto timerInfo = TimerInfo("", 0, 0, duration, timePoint, duration, timePoint, duration, nullptr,
1943 nullptr, 0, false, 0, 0, "");
1944 auto res = timerInfo.UpdateWhenElapsedFromNow(timePoint, duration);
1945 EXPECT_FALSE(res);
1946 }
1947
1948 /**
1949 * @tc.name: Cjson001.
1950 * @tc.desc: cjson.
1951 * @tc.type: FUNC
1952 */
1953 HWTEST_F(TimeServiceTest, Cjson001, TestSize.Level0)
1954 {
1955 auto timerId2 = TIMER_ID + 1;
1956
1957 auto entry1 = std::make_shared<TimerEntry>(
1958 TimerEntry{"", TIMER_ID, 1, 1, 1, 1, false, nullptr, nullptr, 1, 1, "bundleName1"});
1959 auto ret = CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), entry1);
1960 EXPECT_TRUE(ret);
1961 auto entry2 = std::make_shared<TimerEntry>(
1962 TimerEntry{"", timerId2, 2, 2, 2, 2, true, nullptr, nullptr, 2, 2, "bundleName2"});
1963 ret = CjsonHelper::GetInstance().Insert(std::string(HOLD_ON_REBOOT), entry2);
1964 EXPECT_TRUE(ret);
1965
1966 EXPECT_TRUE(CheckInJson(DROP_ON_REBOOT, TIMER_ID));
1967 EXPECT_TRUE(CheckInJson(HOLD_ON_REBOOT, timerId2));
1968
1969 CjsonHelper::GetInstance().Delete(std::string(DROP_ON_REBOOT), TIMER_ID);
1970 CjsonHelper::GetInstance().Delete(std::string(HOLD_ON_REBOOT), timerId2);
1971
1972 EXPECT_FALSE(CheckInJson(DROP_ON_REBOOT, TIMER_ID));
1973 EXPECT_FALSE(CheckInJson(HOLD_ON_REBOOT, timerId2));
1974 }
1975
1976 /**
1977 * @tc.name: Cjson002.
1978 * @tc.desc: cjson.
1979 * @tc.type: FUNC
1980 */
1981 HWTEST_F(TimeServiceTest, Cjson002, TestSize.Level0)
1982 {
1983 auto timerId2 = TIMER_ID + 1;
1984
1985 auto entry1 = std::make_shared<TimerEntry>(
1986 TimerEntry{"", TIMER_ID, 1, 1, 1, 1, false, nullptr, nullptr, 1, 1, "bundleName1"});
1987 auto ret = CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), entry1);
1988 EXPECT_TRUE(ret);
1989 auto entry2 = std::make_shared<TimerEntry>(
1990 TimerEntry{"", timerId2, 2, 2, 2, 2, true, nullptr, nullptr, 2, 2, "bundleName2"});
1991 ret = CjsonHelper::GetInstance().Insert(std::string(HOLD_ON_REBOOT), entry2);
1992 EXPECT_TRUE(ret);
1993
1994 EXPECT_TRUE(CheckInJson(DROP_ON_REBOOT, TIMER_ID));
1995 EXPECT_TRUE(CheckInJson(HOLD_ON_REBOOT, timerId2));
1996
1997 CjsonHelper::GetInstance().Clear(std::string(DROP_ON_REBOOT));
1998 CjsonHelper::GetInstance().Clear(std::string(HOLD_ON_REBOOT));
1999
2000 EXPECT_FALSE(CheckInJson(DROP_ON_REBOOT, TIMER_ID));
2001 EXPECT_FALSE(CheckInJson(HOLD_ON_REBOOT, timerId2));
2002 }
2003
2004 /**
2005 * @tc.name: Cjson003.
2006 * @tc.desc: cjson.
2007 * @tc.type: FUNC
2008 */
2009 HWTEST_F(TimeServiceTest, Cjson003, TestSize.Level0)
2010 {
2011 auto triggerTime = 200;
2012 auto entry1 = std::make_shared<TimerEntry>(
2013 TimerEntry{"", TIMER_ID, 1, 1, 1, 1, false, nullptr, nullptr, 1, 1, "bundleName1"});
2014 CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), entry1);
2015
2016 CjsonHelper::GetInstance().UpdateTrigger(std::string(DROP_ON_REBOOT), TIMER_ID, triggerTime);
2017
2018 bool flag = false;
2019 cJSON* db1 = NULL;
2020 cJSON* data1 = CjsonHelper::GetInstance().QueryTable(DROP_ON_REBOOT, &db1);
2021 if (data1 != NULL) {
2022 int size = cJSON_GetArraySize(data1);
2023 for (int i = 0; i < size; ++i) {
2024 cJSON* obj = cJSON_GetArrayItem(data1, i);
2025
2026 if (cJSON_GetObjectItem(obj, "timerId")->valuestring == std::to_string(TIMER_ID)) {
2027 auto state = cJSON_GetObjectItem(obj, "state")->valueint;
2028 EXPECT_EQ(state, 1);
2029 string triggerTimeStr = cJSON_GetObjectItem(obj, "triggerTime")->valuestring;
2030 EXPECT_EQ(triggerTimeStr, std::to_string(triggerTime));
2031 flag = true;
2032 break;
2033 }
2034 }
2035 }
2036 cJSON_Delete(db1);
2037 EXPECT_TRUE(flag);
2038 CjsonHelper::GetInstance().UpdateState(std::string(DROP_ON_REBOOT), TIMER_ID);
2039 flag = false;
2040 db1 = NULL;
2041 data1 = CjsonHelper::GetInstance().QueryTable(DROP_ON_REBOOT, &db1);
2042 if (data1 != NULL) {
2043 int size = cJSON_GetArraySize(data1);
2044 for (int i = 0; i < size; ++i) {
2045 cJSON* obj = cJSON_GetArrayItem(data1, i);
2046
2047 if (cJSON_GetObjectItem(obj, "timerId")->valuestring == std::to_string(TIMER_ID)) {
2048 auto state = cJSON_GetObjectItem(obj, "state")->valueint;
2049 EXPECT_EQ(state, 0);
2050 flag = true;
2051 break;
2052 }
2053 }
2054 }
2055 cJSON_Delete(db1);
2056 EXPECT_TRUE(flag);
2057
2058 CjsonHelper::GetInstance().Delete(std::string(DROP_ON_REBOOT), TIMER_ID);
2059 }
2060
2061
2062 /**
2063 * @tc.name: Cjson004.
2064 * @tc.desc: cjson.
2065 * @tc.type: FUNC
2066 */
2067 HWTEST_F(TimeServiceTest, Cjson004, TestSize.Level0)
2068 {
2069 auto entry1 = std::make_shared<TimerEntry>(
2070 TimerEntry{"", TIMER_ID, 1, 1, 1, 1, false, nullptr, nullptr, 1, 1, "bundleName1"});
2071 CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), entry1);
2072 std::string want1 = CjsonHelper::GetInstance().QueryWant(std::string(DROP_ON_REBOOT), TIMER_ID);
2073 EXPECT_EQ(want1, "");
2074 CjsonHelper::GetInstance().Delete(std::string(DROP_ON_REBOOT), TIMER_ID);
2075 }
2076
2077 /**
2078 * @tc.name: Cjson005.
2079 * @tc.desc: cjson.
2080 * @tc.type: FUNC
2081 */
2082 HWTEST_F(TimeServiceTest, Cjson005, TestSize.Level0)
2083 {
2084 auto entry1 = std::make_shared<TimerEntry>(
2085 TimerEntry{"", TIMER_ID, 1, 1, 1, 1, true, nullptr, nullptr, 1, 1, "bundleName1"});
2086 CjsonHelper::GetInstance().Insert(std::string(HOLD_ON_REBOOT), entry1);
2087 CjsonHelper::GetInstance().UpdateTrigger(std::string(HOLD_ON_REBOOT), TIMER_ID, 200);
2088 auto data = CjsonHelper::GetInstance().QueryAutoReboot();
2089 EXPECT_TRUE(data.size() > 0);
2090 CjsonHelper::GetInstance().Delete(std::string(HOLD_ON_REBOOT), TIMER_ID);
2091 }
2092
2093 /**
2094 * @tc.name: Cjson006.
2095 * @tc.desc: cjson get entry.
2096 * @tc.type: FUNC
2097 */
2098 HWTEST_F(TimeServiceTest, Cjson006, TestSize.Level0)
2099 {
2100 cJSON* obj = cJSON_CreateObject();
2101 auto res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2102 EXPECT_EQ(res, nullptr);
2103 cJSON_AddStringToObject(obj, "name", "");
2104 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2105 EXPECT_EQ(res, nullptr);
2106 cJSON_AddStringToObject(obj, "timerId", "timerId");
2107 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2108 EXPECT_EQ(res, nullptr);
2109 cJSON *new_item = cJSON_CreateString(std::to_string(TIMER_ID).c_str());
2110 cJSON_ReplaceItemInObject(obj, "timerId", new_item);
2111 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2112 EXPECT_EQ(res, nullptr);
2113 cJSON_AddNumberToObject(obj, "type", 1);
2114 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2115 EXPECT_EQ(res, nullptr);
2116 cJSON_AddNumberToObject(obj, "windowLength", 1);
2117 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2118 EXPECT_EQ(res, nullptr);
2119 cJSON_AddNumberToObject(obj, "interval", 1);
2120 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2121 EXPECT_EQ(res, nullptr);
2122 cJSON_AddNumberToObject(obj, "flag", 1);
2123 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2124 EXPECT_EQ(res, nullptr);
2125 cJSON_AddStringToObject(obj, "wantAgent",
2126 OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(nullptr).c_str());
2127 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2128 EXPECT_EQ(res, nullptr);
2129 cJSON_AddNumberToObject(obj, "uid", 1);
2130 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2131 EXPECT_EQ(res, nullptr);
2132 cJSON_AddNumberToObject(obj, "pid", 1);
2133 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2134 EXPECT_EQ(res, nullptr);
2135 cJSON_AddStringToObject(obj, "bundleName", "bundleName1");
2136 res = TimeSystemAbility::GetInstance()->GetEntry(obj, true);
2137 EXPECT_NE(res, nullptr);
2138 cJSON_Delete(obj);
2139 }
2140
2141 /**
2142 * @tc.name: Cjson007.
2143 * @tc.desc: cjson get entry.
2144 * @tc.type: FUNC
2145 */
2146 HWTEST_F(TimeServiceTest, Cjson007, TestSize.Level0)
2147 {
2148 cJSON* resultSet = cJSON_CreateArray();
2149 cJSON* obj1 = cJSON_CreateObject();
2150 cJSON_AddItemToArray(resultSet, obj1);
2151 cJSON* obj2 = cJSON_CreateObject();
2152 cJSON_AddStringToObject(obj2, "name", "");
2153 cJSON_AddStringToObject(obj2, "timerId", "88888");
2154 cJSON_AddNumberToObject(obj2, "type", 1);
2155 cJSON_AddNumberToObject(obj2, "windowLength", 1);
2156 cJSON_AddNumberToObject(obj2, "interval", 1);
2157 cJSON_AddNumberToObject(obj2, "flag", 1);
2158 cJSON_AddStringToObject(obj2, "wantAgent", "");
2159 cJSON_AddNumberToObject(obj2, "uid", 1);
2160 cJSON_AddNumberToObject(obj2, "pid", 1);
2161 cJSON_AddStringToObject(obj2, "bundleName", "bundleName1");
2162 cJSON_AddItemToArray(resultSet, obj2);
2163 TimeSystemAbility::GetInstance()->CjsonIntoDatabase(resultSet, true, HOLD_ON_REBOOT);
2164 OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(HOLD_ON_REBOOT);
2165 rdbPredicatesDelete.EqualTo("timerId", static_cast<int64_t>(TIMER_ID));
2166 int count = 0;
2167 TimeDatabase::GetInstance().Query(rdbPredicatesDelete, {"timerId"})->GetRowCount(count);
2168 EXPECT_EQ(count, 0);
2169 cJSON_Delete(resultSet);
2170 }
2171
2172 /**
2173 * @tc.name: TimerInfo002.
2174 * @tc.desc: test AdjustTimer.
2175 * @tc.type: FUNC
2176 */
2177 HWTEST_F(TimeServiceTest, TimerInfo002, TestSize.Level0)
2178 {
2179 auto duration = std::chrono::milliseconds(0);
2180 auto timePoint = std::chrono::steady_clock::now();
2181 auto timerInfo = TimerInfo("", 0, 0, duration, timePoint, duration, timePoint, duration, nullptr,
2182 nullptr, 0, false, 0, 0, "");
2183 auto res = timerInfo.AdjustTimer(timePoint, 1, 0);
2184 EXPECT_TRUE(res);
2185 }
2186
2187 /**
2188 * @tc.name: NtpTime001.
2189 * @tc.desc: test SplitNtpAddrs return max size.
2190 * @tc.type: FUNC
2191 */
2192 HWTEST_F(TimeServiceTest, NtpTime001, TestSize.Level0)
2193 {
2194 const std::string ntpStr = "aaa,bbb,ccc,ddd,eee,fff";
2195 auto res = NtpUpdateTime::GetInstance().SplitNtpAddrs(ntpStr);
2196 EXPECT_EQ(res.size(), 5);
2197 }
2198
2199 /**
2200 * @tc.name: NtpTime002.
2201 * @tc.desc: test RefreshNetworkTimeByTimer.
2202 * @tc.type: FUNC
2203 */
2204 HWTEST_F(TimeServiceTest, NtpTime002, TestSize.Level0)
2205 {
2206 auto status = NtpUpdateTime::GetInstance().autoTimeInfo_.status;
2207
2208 NtpUpdateTime::GetInstance().autoTimeInfo_.status = NETWORK_TIME_STATUS_OFF;
2209 NtpUpdateTime::GetInstance().RefreshNetworkTimeByTimer(TIMER_ID);
2210
2211 NtpUpdateTime::GetInstance().autoTimeInfo_.status = NETWORK_TIME_STATUS_ON;
2212 NtpUpdateTime::GetInstance().RefreshNetworkTimeByTimer(TIMER_ID);
2213
2214 NtpUpdateTime::GetInstance().nitzUpdateTimeMilli_ = 0;
2215 auto res = NtpUpdateTime::GetInstance().IsValidNITZTime();
2216 EXPECT_FALSE(res);
2217
2218 NtpUpdateTime::GetInstance().UpdateNITZSetTime();
2219 res = NtpUpdateTime::GetInstance().IsValidNITZTime();
2220 EXPECT_TRUE(res);
2221 NtpUpdateTime::GetInstance().RefreshNetworkTimeByTimer(TIMER_ID);
2222
2223 NtpUpdateTime::GetInstance().autoTimeInfo_.status = status;
2224 }
2225
2226 /**
2227 * @tc.name: ResetAllProxy001.
2228 * @tc.desc: test RefreshNetworkTimeByTimer.
2229 * @tc.type: FUNC
2230 */
2231 HWTEST_F(TimeServiceTest, ResetAllProxy001, TestSize.Level0)
2232 {
2233 DeletePermission();
2234 auto res = TimeSystemAbility::GetInstance()->ResetAllProxy();
2235 EXPECT_EQ(res, E_TIME_NO_PERMISSION);
2236 }
2237
2238 /**
2239 * @tc.name: GetNtpTimeMs001.
2240 * @tc.desc: test RefreshNetworkTimeByTimer.
2241 * @tc.type: FUNC
2242 */
2243 HWTEST_F(TimeServiceTest, GetNtpTimeMs001, TestSize.Level0)
2244 {
2245 DeletePermission();
2246 int64_t time = 0;
2247 auto res = TimeSystemAbility::GetInstance()->GetNtpTimeMs(time);
2248 EXPECT_EQ(res, E_TIME_NOT_SYSTEM_APP);
2249 }
2250
2251 /**
2252 * @tc.name: GetRealTimeMs001.
2253 * @tc.desc: test GetRealTimeMs.
2254 * @tc.type: FUNC
2255 */
2256 HWTEST_F(TimeServiceTest, GetRealTimeMs, TestSize.Level0)
2257 {
2258 DeletePermission();
2259 int64_t time = 0;
2260 auto res = TimeSystemAbility::GetInstance()->GetRealTimeMs(time);
2261 EXPECT_EQ(res, E_TIME_NOT_SYSTEM_APP);
2262 }
2263
2264 #ifdef MULTI_ACCOUNT_ENABLE
2265 /**
2266 * @tc.name: CheckUserIdForNotify001.
2267 * @tc.desc: test CheckUserIdForNotify.
2268 * @tc.type: FUNC
2269 */
2270 HWTEST_F(TimeServiceTest, CheckUserIdForNotify001, TestSize.Level0)
2271 {
2272 auto duration = std::chrono::milliseconds::zero();
2273 auto timePoint = std::chrono::steady_clock::now();
2274 auto timerInfo = std::make_shared<TimerInfo>("", TIMER_ID, 0, duration, timePoint, duration, timePoint, duration,
2275 nullptr, nullptr, 0, false, -1, 0, "");
2276 auto res = TimerManager::GetInstance()->CheckUserIdForNotify(timerInfo);
2277 EXPECT_EQ(res, E_TIME_ACCOUNT_ERROR);
2278 timerInfo = std::make_shared<TimerInfo>("", TIMER_ID, 0, duration, timePoint, duration, timePoint, duration,
2279 nullptr, nullptr, 0, false, 0, 0, "");
2280 res = TimerManager::GetInstance()->CheckUserIdForNotify(timerInfo);
2281 EXPECT_EQ(res, E_TIME_OK);
2282 }
2283 #endif
2284 } // namespace