1 /*
2 * Copyright (c) 2022 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 <functional>
17 #include <chrono>
18 #include <thread>
19 #include <gtest/gtest.h>
20
21 #include "ability_state_data.h"
22 #include "app_state_data.h"
23 #include "app_state_observer.h"
24 #include "background_task_mgr_service.h"
25 #include "bg_continuous_task_mgr.h"
26 #include "bg_efficiency_resources_mgr.h"
27 #include "bundle_info.h"
28 #include "bundle_manager_helper.h"
29 #include "common_event_data.h"
30 #include "continuous_task_record.h"
31 #include "decision_maker.h"
32 #include "delay_suspend_info_ex.h"
33 #include "device_info_manager.h"
34 #include "event_info.h"
35 #include "event_handler.h"
36 #include "event_runner.h"
37 #include "input_manager.h"
38 #include "key_info.h"
39 #include "notification.h"
40 #include "notification_sorting_map.h"
41 #include "notification_tools.h"
42 #include "pkg_delay_suspend_info.h"
43 #include "process_data.h"
44 #include "singleton.h"
45 #include "string_wrapper.h"
46 #include "suspend_controller.h"
47 #include "task_notification_subscriber.h"
48 #include "time_provider.h"
49 #include "timer_manager.h"
50 #include "watchdog.h"
51
52 using namespace testing::ext;
53
54 namespace OHOS {
55 extern void SetPublishContinuousTaskNotificationFlag(int32_t flag);
56 extern void SetCancelContinuousTaskNotificationFlag(int32_t flag);
57 extern void SetGetAllActiveNotificationsFlag(int32_t flag);
58
59 namespace BackgroundTaskMgr {
60 namespace {
61 static constexpr int32_t SLEEP_TIME = 500;
62 static constexpr int32_t BGTASKMGR_UID = 3051;
63 static constexpr int32_t TEST_NUM_ONE = 1;
64 static constexpr int32_t TEST_NUM_TWO = 2;
65 static constexpr int32_t MIN_ALLOW_QUOTA_TIME = 10 * MSEC_PER_SEC; // 10s
66 }
67
68 class BgTaskMiscUnitTest : public testing::Test {
69 public:
70 static void SetUpTestCase();
71 static void TearDownTestCase();
72 void SetUp();
73 void TearDown();
SleepForFC()74 inline void SleepForFC()
75 {
76 std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME));
77 }
78 };
79
SetUpTestCase()80 void BgTaskMiscUnitTest::SetUpTestCase() {}
81
TearDownTestCase()82 void BgTaskMiscUnitTest::TearDownTestCase() {}
83
SetUp()84 void BgTaskMiscUnitTest::SetUp() {}
85
TearDown()86 void BgTaskMiscUnitTest::TearDown() {}
87
88 /**
89 * @tc.name: AppStateObserverTest_001
90 * @tc.desc: test AppStateObserver class CheckParamValid method.
91 * @tc.type: FUNC
92 * @tc.require: issueI4QT3W issueI4QU0V
93 */
94 HWTEST_F(BgTaskMiscUnitTest, AppStateObserverTest_001, TestSize.Level1)
95 {
96 sptr<AppStateObserver> appStateObserver = sptr<AppStateObserver>(new AppStateObserver());
97 AppExecFwk::ProcessData processData = AppExecFwk::ProcessData();
98 appStateObserver->OnProcessDied(processData);
99 appStateObserver->OnProcessDiedEfficiencyRes(processData);
100 AppExecFwk::AbilityStateData abilityStateData = AppExecFwk::AbilityStateData();
101 appStateObserver->OnAbilityStateChanged(abilityStateData);
102 auto handler = std::make_shared<OHOS::AppExecFwk::EventHandler>(nullptr);
103 appStateObserver->SetEventHandler(handler);
104 abilityStateData.abilityState = static_cast<int32_t>(AppExecFwk::AbilityState::ABILITY_STATE_TERMINATED);
105 appStateObserver->OnAbilityStateChanged(abilityStateData);
106 abilityStateData.abilityState = static_cast<int32_t>(AppExecFwk::AbilityState::ABILITY_STATE_CREATE);
107 appStateObserver->OnAbilityStateChanged(abilityStateData);
108 abilityStateData.abilityState = static_cast<int32_t>(AppExecFwk::AbilityState::ABILITY_STATE_TERMINATED);
109 appStateObserver->OnAbilityStateChanged(abilityStateData);
110 AppExecFwk::AppStateData appStateData = AppExecFwk::AppStateData();
111 appStateObserver->OnAppStopped(appStateData);
112 appStateData.uid = 1;
113 appStateData.bundleName = "bundleName";
114 appStateObserver->OnAppStopped(appStateData);
115 appStateData.state = static_cast<int32_t>(AppExecFwk::ApplicationState::APP_STATE_TERMINATED);
116 appStateObserver->OnAppStopped(appStateData);
117 appStateData.state = static_cast<int32_t>(AppExecFwk::ApplicationState::APP_STATE_END);
118 appStateObserver->OnAppStopped(appStateData);
119 appStateObserver->OnAppStopped(appStateData);
120 EXPECT_EQ(appStateData.uid, 1);
121 }
122
123 /**
124 * @tc.name: BundleManagerHelperTest_001
125 * @tc.desc: test BundleManagerHelper class.
126 * @tc.type: FUNC
127 * @tc.require: issueI4QT3W issueI4QU0V
128 */
129 HWTEST_F(BgTaskMiscUnitTest, BundleManagerHelperTest_001, TestSize.Level1)
130 {
131 EXPECT_EQ(BundleManagerHelper::GetInstance()->GetClientBundleName(1), "");
132 EXPECT_FALSE(BundleManagerHelper::GetInstance()->CheckPermission("permission"));
133 EXPECT_FALSE(BundleManagerHelper::GetInstance()->IsSystemApp(1LLU));
134 AppExecFwk::BundleInfo bundleInfo;
135 EXPECT_FALSE(BundleManagerHelper::GetInstance()->GetBundleInfo("bundleName",
136 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo));
137 AppExecFwk::ApplicationInfo applicationInfo;
138 EXPECT_FALSE(BundleManagerHelper::GetInstance()->GetApplicationInfo("bundleName",
139 AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, 100, applicationInfo));
140 BundleManagerHelper::GetInstance()->OnRemoteDied(nullptr);
141 BundleManagerHelper::GetInstance()->bundleMgr_ = nullptr;
142 BundleManagerHelper::GetInstance()->OnRemoteDied(nullptr);
143 AAFwk::Want want;
144 want.SetAction("action.system.home");
145 want.AddEntity("entity.system.home");
146 want.SetElementName("", "bundleName", "", "");
147 AppExecFwk::AbilityInfo abilityInfo;
148 BundleManagerHelper::GetInstance()->QueryAbilityInfo(want,
149 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, 0, abilityInfo);
150 BundleManagerHelper::GetInstance()->bundleMgr_ = nullptr;
151 BundleManagerHelper::GetInstance()->QueryAbilityInfo(want,
152 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, 0, abilityInfo);
153 }
154
155 /**
156 * @tc.name: SystemEventObserverTest_001
157 * @tc.desc: test SystemEventObserver class.
158 * @tc.type: FUNC
159 * @tc.require: issueI4QT3W issueI4QU0V
160 */
161 HWTEST_F(BgTaskMiscUnitTest, SystemEventObserver_001, TestSize.Level1)
162 {
163 EventFwk::MatchingSkills matchingSkills;
164 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED);
165 EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills);
166 auto systemEventListener = std::make_shared<SystemEventObserver>(commonEventSubscribeInfo);
167 EXPECT_TRUE(systemEventListener->Subscribe());
168 EXPECT_TRUE(systemEventListener->Unsubscribe());
169
170 EventFwk::CommonEventData eventData = EventFwk::CommonEventData();
171 systemEventListener->OnReceiveEvent(eventData);
172
173 auto handler = std::make_shared<OHOS::AppExecFwk::EventHandler>(nullptr);
174 systemEventListener->SetEventHandler(handler);
175 systemEventListener->OnReceiveEventContinuousTask(eventData);
176 auto bgContinuousTaskMgr = std::make_shared<BgContinuousTaskMgr>();
177 systemEventListener->SetBgContinuousTaskMgr(bgContinuousTaskMgr);
178 systemEventListener->OnReceiveEventContinuousTask(eventData);
179 AAFwk::Want want = AAFwk::Want();
180 want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
181 eventData.SetWant(want);
182 systemEventListener->OnReceiveEventContinuousTask(eventData);
183 want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_ADDED);
184 eventData.SetWant(want);
185 systemEventListener->OnReceiveEventContinuousTask(eventData);
186 want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED);
187 eventData.SetWant(want);
188 systemEventListener->OnReceiveEventContinuousTask(eventData);
189
190 EventFwk::CommonEventData eventData2 = EventFwk::CommonEventData();
191 AAFwk::Want want2 = AAFwk::Want();
192 want2.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
193 eventData2.SetWant(want2);
194 systemEventListener->OnReceiveEventEfficiencyRes(eventData2);
195 EXPECT_TRUE(true);
196 }
197
198 /**
199 * @tc.name: ContinuousTaskRecordTest_001
200 * @tc.desc: test ContinuousTaskRecord class.
201 * @tc.type: FUNC
202 * @tc.require: issueI4QT3W issueI4QU0V
203 */
204 HWTEST_F(BgTaskMiscUnitTest, ContinuousTaskRecordTest_001, TestSize.Level1)
205 {
206 ContinuousTaskRecord record = ContinuousTaskRecord();
207 std::string str1 = record.ParseToJsonStr();
208 EXPECT_NE(str1, "");
209 record.wantAgentInfo_ = std::make_shared<WantAgentInfo>();
210 std::string str2 = record.ParseToJsonStr();
211 EXPECT_NE(str2, "");
212 ContinuousTaskRecord record2 = ContinuousTaskRecord();
213 nlohmann::json json2 = nlohmann::json::parse("", nullptr, false);
214 EXPECT_FALSE(record2.ParseFromJson(json2));
215 nlohmann::json json3;
216 json3["bundleName"] = "bundleName";
217 EXPECT_FALSE(record2.ParseFromJson(json3));
218 nlohmann::json json4 = nlohmann::json::parse(str1, nullptr, false);
219 ContinuousTaskRecord record3 = ContinuousTaskRecord();
220 EXPECT_TRUE(record3.ParseFromJson(json4));
221 nlohmann::json json5 = nlohmann::json::parse(str2, nullptr, false);
222 ContinuousTaskRecord record4 = ContinuousTaskRecord();
223 EXPECT_TRUE(record4.ParseFromJson(json5));
224 }
225
226 /**
227 * @tc.name: NotificationToolsTest_001
228 * @tc.desc: test NotificationTools class.
229 * @tc.type: FUNC
230 * @tc.require: issueI4QT3W issueI4QU0V
231 */
232 HWTEST_F(BgTaskMiscUnitTest, NotificationToolsTest_001, TestSize.Level1)
233 {
234 #ifdef DISTRIBUTED_NOTIFICATION_ENABLE
235 auto taskRecord = std::make_shared<ContinuousTaskRecord>();
236 NotificationTools::GetInstance()->PublishNotification(taskRecord, "appName", "prompt", 1);
237 SetPublishContinuousTaskNotificationFlag(1);
238 EXPECT_EQ(NotificationTools::GetInstance()->PublishNotification(taskRecord, "appName", "prompt", 1),
239 ERR_BGTASK_NOTIFICATION_ERR);
240 NotificationTools::GetInstance()->CancelNotification("label", 0);
241 SetCancelContinuousTaskNotificationFlag(1);
242 EXPECT_EQ(NotificationTools::GetInstance()->CancelNotification("label", 0), ERR_BGTASK_NOTIFICATION_ERR);
243 std::set<std::string> notificationLabels;
244 NotificationTools::GetInstance()->GetAllActiveNotificationsLabels(notificationLabels);
245
246 std::map<std::string, std::pair<std::string, std::string>> newPromptInfos;
247 newPromptInfos.emplace("label", std::make_pair<std::string, std::string>("test1", "test2"));
248 SetGetAllActiveNotificationsFlag(TEST_NUM_ONE);
249 SetPublishContinuousTaskNotificationFlag(0);
250 SetPublishContinuousTaskNotificationFlag(0);
251 NotificationTools::GetInstance()->RefreshContinuousNotifications(newPromptInfos, 0);
252 SetGetAllActiveNotificationsFlag(TEST_NUM_TWO);
253 SetPublishContinuousTaskNotificationFlag(1);
254 NotificationTools::GetInstance()->RefreshContinuousNotifications(newPromptInfos, 0);
255 #endif
256 }
257
258 /**
259 * @tc.name: TaskNotificationSubscriber_001
260 * @tc.desc: test TaskNotificationSubscriber class.
261 * @tc.type: FUNC
262 * @tc.require: issueI4QT3W issueI4QU0V
263 */
264 HWTEST_F(BgTaskMiscUnitTest, TaskNotificationSubscriber_001, TestSize.Level1)
265 {
266 auto subscriber = std::make_shared<TaskNotificationSubscriber>();
267 subscriber->OnCanceled(nullptr, nullptr, 1);
268 auto notificationMap = std::make_shared<Notification::NotificationSortingMap>();
269 auto notificationRequest = sptr<Notification::NotificationRequest>(new Notification::NotificationRequest());
270 auto notification = std::make_shared<Notification::Notification>(notificationRequest);
271 subscriber->OnCanceled(notification, notificationMap, 1);
272 BgContinuousTaskMgr::GetInstance()->bgTaskUid_ = BGTASKMGR_UID;
273
274 notification->request_->creatorUid_ = BGTASKMGR_UID;
275 subscriber->OnCanceled(notification, notificationMap, 1);
276 notification->request_->label_ = "label";
277 subscriber->OnCanceled(notification, notificationMap, 1);
278 notification->request_->label_ = "bgmode_1";
279 subscriber->OnCanceled(notification, notificationMap, 1);
280 notification->request_->label_ = "bgmode_1_1";
281 subscriber->OnCanceled(notification, notificationMap, 1);
282 subscriber->OnCanceled(notification, notificationMap,
283 Notification::NotificationConstant::APP_CANCEL_REASON_DELETE);
284
285 std::shared_ptr<AAFwk::WantParams> extraInfo = std::make_shared<AAFwk::WantParams>();
286 extraInfo->SetParam("abilityName", AAFwk::String::Box("abilityName"));
287 notification->request_->additionalParams_ = extraInfo;
288 subscriber->OnCanceled(notification, notificationMap,
289 Notification::NotificationConstant::USER_STOPPED_REASON_DELETE);
290
291 std::shared_ptr<ContinuousTaskRecord> continuousTaskRecord = std::make_shared<ContinuousTaskRecord>();
292 BgContinuousTaskMgr::GetInstance()->continuousTaskInfosMap_["1_abilityName"] = continuousTaskRecord;
293 subscriber->OnCanceled(notification, notificationMap,
294 Notification::NotificationConstant::USER_STOPPED_REASON_DELETE);
295 EXPECT_TRUE(true);
296 }
297
298 /**
299 * @tc.name: DecisionMakerTest_001
300 * @tc.desc: test DecisionMaker class decide method.
301 * @tc.type: FUNC
302 * @tc.require: issueI4QT3W issueI4QU0V
303 */
304 HWTEST_F(BgTaskMiscUnitTest, DecisionMakerTest_001, TestSize.Level1)
305 {
306 auto deviceInfoManeger = std::make_shared<DeviceInfoManager>();
307 auto bgtaskService = sptr<BackgroundTaskMgrService>(new BackgroundTaskMgrService());
308 auto timerManager = std::make_shared<TimerManager>(bgtaskService,
309 AppExecFwk::EventRunner::Create("tdd_test_handler"));
310 auto decisionMaker = std::make_shared<DecisionMaker>(timerManager, deviceInfoManeger);
311 decisionMaker->lastRequestTime_ = TimeProvider::GetCurrentTime();
312 EXPECT_EQ(decisionMaker->Decide(nullptr, nullptr), ERR_BGTASK_NO_MEMORY);
313
314 auto keyInfo = std::make_shared<KeyInfo>("bundleName1", 1);
315 auto delayInfo = std::make_shared<DelaySuspendInfoEx>(1);
316 decisionMaker->pkgBgDurationMap_[keyInfo] = TimeProvider::GetCurrentTime() - ALLOW_REQUEST_TIME_BG - 1;
317 EXPECT_EQ(decisionMaker->Decide(keyInfo, delayInfo), ERR_BGTASK_NOT_IN_PRESET_TIME);
318 decisionMaker->pkgBgDurationMap_[keyInfo] = TimeProvider::GetCurrentTime();
319 EXPECT_EQ(decisionMaker->Decide(keyInfo, nullptr), ERR_BGTASK_NO_MEMORY);
320
321 auto keyInfo2 = std::make_shared<KeyInfo>("bundleName2", 2);
322 auto pkgDelaySuspendInfo = std::make_shared<PkgDelaySuspendInfo>("bundleName2", 2, timerManager);
323 auto delayInfo1 = std::make_shared<DelaySuspendInfoEx>(1);
324 auto delayInfo2 = std::make_shared<DelaySuspendInfoEx>(2);
325 auto delayInfo3 = std::make_shared<DelaySuspendInfoEx>(3);
326 pkgDelaySuspendInfo->requestList_.push_back(delayInfo1);
327 pkgDelaySuspendInfo->requestList_.push_back(delayInfo2);
328 pkgDelaySuspendInfo->requestList_.push_back(delayInfo3);
329 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo2] = pkgDelaySuspendInfo;
330 EXPECT_EQ(decisionMaker->Decide(keyInfo2, delayInfo1), ERR_BGTASK_EXCEEDS_THRESHOLD);
331 decisionMaker->pkgDelaySuspendInfoMap_.clear();
332 deviceInfoManeger->isScreenOn_ = true;
333 EXPECT_EQ(decisionMaker->Decide(keyInfo, delayInfo1), ERR_OK);
334 decisionMaker->pkgDelaySuspendInfoMap_.clear();
335 deviceInfoManeger->isScreenOn_ = false;
336 EXPECT_EQ(decisionMaker->Decide(keyInfo, delayInfo1), ERR_OK);
337 }
338
339 /**
340 * @tc.name: DecisionMakerTest_002
341 * @tc.desc: test DecisionMaker class misc method.
342 * @tc.type: FUNC
343 * @tc.require: issueI4QT3W issueI4QU0V
344 */
345 HWTEST_F(BgTaskMiscUnitTest, DecisionMakerTest_002, TestSize.Level1)
346 {
347 auto deviceInfoManeger = std::make_shared<DeviceInfoManager>();
348 auto bgtaskService = sptr<BackgroundTaskMgrService>(new BackgroundTaskMgrService());
349 auto timerManager = std::make_shared<TimerManager>(bgtaskService,
350 AppExecFwk::EventRunner::Create("tdd_test_handler"));
351 auto decisionMaker = std::make_shared<DecisionMaker>(timerManager, deviceInfoManeger);
352
353 decisionMaker->RemoveRequest(nullptr, -1);
354 auto keyInfo = std::make_shared<KeyInfo>("bundleName1", 1);
355 decisionMaker->RemoveRequest(keyInfo, -1);
356
357 auto pkgDelaySuspendInfo = std::make_shared<PkgDelaySuspendInfo>("bundleName1", 1, timerManager);
358 auto delayInfo1 = std::make_shared<DelaySuspendInfoEx>(1);
359 pkgDelaySuspendInfo->requestList_.push_back(delayInfo1);
360 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo] = pkgDelaySuspendInfo;
361 decisionMaker->RemoveRequest(keyInfo, -1);
362 decisionMaker->RemoveRequest(keyInfo, 1);
363
364 decisionMaker->pkgDelaySuspendInfoMap_.clear();
365 EXPECT_EQ(decisionMaker->GetRemainingDelayTime(nullptr, -1), -1);
366 EXPECT_EQ(decisionMaker->GetRemainingDelayTime(nullptr, -1), -1);
367 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo] = pkgDelaySuspendInfo;
368 EXPECT_EQ(decisionMaker->GetRemainingDelayTime(keyInfo, -1), 0);
369
370 EXPECT_EQ(decisionMaker->GetQuota(nullptr), -1);
371 decisionMaker->pkgDelaySuspendInfoMap_.clear();
372 EXPECT_EQ(decisionMaker->GetQuota(keyInfo), INIT_QUOTA);
373 pkgDelaySuspendInfo->quota_ = -1;
374 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo] = pkgDelaySuspendInfo;
375 EXPECT_EQ(decisionMaker->GetQuota(keyInfo), 0);
376 EXPECT_FALSE(decisionMaker->IsFrontApp("pkgName", 1));
377
378 decisionMaker->requestId_ = INT_MAX;
379 EXPECT_EQ(decisionMaker->NewDelaySuspendRequestId(), 1);
380 EXPECT_EQ(decisionMaker->NewDelaySuspendRequestId(), TEST_NUM_TWO);
381
382 decisionMaker->lastRequestTime_ = TimeProvider::GetCurrentTime() - 1;
383 decisionMaker->ResetDayQuotaLocked();
384 decisionMaker->lastRequestTime_ = TimeProvider::GetCurrentTime() - QUOTA_UPDATE - 1;
385 decisionMaker->pkgDelaySuspendInfoMap_.clear();
386 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo] = pkgDelaySuspendInfo;
387 auto keyInfo2 = std::make_shared<KeyInfo>("bundleName2", TEST_NUM_TWO);
388 auto pkgDelaySuspendInfo2 = std::make_shared<PkgDelaySuspendInfo>("bundleName2", TEST_NUM_TWO, timerManager);
389 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo2] = pkgDelaySuspendInfo2;
390 decisionMaker->ResetDayQuotaLocked();
391
392 EventInfo eventInfo = EventInfo();
393 eventInfo.eventId_ = 0;
394 decisionMaker->OnInputEvent(eventInfo);
395 eventInfo.eventId_ = EVENT_SCREEN_ON;
396 decisionMaker->OnInputEvent(eventInfo);
397 eventInfo.eventId_ = EVENT_SCREEN_OFF;
398 decisionMaker->OnInputEvent(eventInfo);
399 eventInfo.eventId_ = EVENT_SCREEN_UNLOCK;
400 decisionMaker->OnInputEvent(eventInfo);
401 EXPECT_TRUE(true);
402 }
403
404 /**
405 * @tc.name: DeviceInfoManagerTest_001
406 * @tc.desc: test DeviceInfoManager class.
407 * @tc.type: FUNC
408 * @tc.require: issueI4QT3W issueI4QU0V
409 */
410 HWTEST_F(BgTaskMiscUnitTest, DeviceInfoManagerTest_001, TestSize.Level1)
411 {
412 auto deviceInfoManeger = std::make_shared<DeviceInfoManager>();
413 deviceInfoManeger->isDump_ = true;
414 EventInfo eventInfo = EventInfo();
415 std::vector<std::string> args;
416 args.emplace_back("test");
417 eventInfo.SetStringArgs(args);
418 deviceInfoManeger->OnInputEvent(eventInfo);
419 args.clear();
420 args.emplace_back("dump");
421 eventInfo.SetStringArgs(args);
422 deviceInfoManeger->isDump_ = false;
423 eventInfo.eventId_ = EVENT_SCREEN_ON;
424 deviceInfoManeger->OnInputEvent(eventInfo);
425 eventInfo.eventId_ = EVENT_SCREEN_OFF;
426 deviceInfoManeger->OnInputEvent(eventInfo);
427 eventInfo.eventId_ = EVENT_SCREEN_UNLOCK;
428 deviceInfoManeger->OnInputEvent(eventInfo);
429 eventInfo.eventId_ = EVENT_BATTERY_LOW;
430 deviceInfoManeger->OnInputEvent(eventInfo);
431 eventInfo.eventId_ = EVENT_BATTERY_OKAY;
432 deviceInfoManeger->OnInputEvent(eventInfo);
433 eventInfo.eventId_ = EVENT_MAX;
434 deviceInfoManeger->OnInputEvent(eventInfo);
435 EXPECT_TRUE(true);
436 }
437
438 /**
439 * @tc.name: InputManagerTest_001
440 * @tc.desc: test InputManager class.
441 * @tc.type: FUNC
442 * @tc.require: issueI4QT3W issueI4QU0V
443 */
444 HWTEST_F(BgTaskMiscUnitTest, InputManagerTest_001, TestSize.Level1)
445 {
446 auto inputManager = std::make_shared<InputManager>(AppExecFwk::EventRunner::Create("tdd_test_handler"));
447 auto deviceInfoManeger1 = std::make_shared<DeviceInfoManager>();
448 inputManager->RegisterEventListener(nullptr);
449 inputManager->RegisterEventListener(deviceInfoManeger1);
450 auto eventInfo = std::make_shared<EventInfo>();
451 inputManager->SendEventInfo(nullptr);
452 inputManager->SendEventInfo(eventInfo);
453 auto deviceInfoManeger2 = std::make_shared<DeviceInfoManager>();
454 inputManager->UnRegisterEventListener(nullptr);
455 inputManager->UnRegisterEventListener(deviceInfoManeger2);
456 EXPECT_EQ(inputManager->listenerList_.size(), 1);
457 inputManager->UnRegisterEventListener(deviceInfoManeger1);
458 EXPECT_EQ(inputManager->listenerList_.size(), 0);
459 EXPECT_TRUE(true);
460 }
461
462 /**
463 * @tc.name: PkgDelaySuspendInfoTest_001
464 * @tc.desc: test PkgDelaySuspendInfo class.
465 * @tc.type: FUNC
466 * @tc.require: issueI4QT3W issueI4QU0V
467 */
468 HWTEST_F(BgTaskMiscUnitTest, PkgDelaySuspendInfoTest_001, TestSize.Level1)
469 {
470 auto bgtaskService = sptr<BackgroundTaskMgrService>(new BackgroundTaskMgrService());
471 auto timerManager = std::make_shared<TimerManager>(bgtaskService,
472 AppExecFwk::EventRunner::Create("tdd_test_handler"));
473 auto pkgDelaySuspendInfo = std::make_shared<PkgDelaySuspendInfo>("bundleName1", 1, timerManager);
474 pkgDelaySuspendInfo->isCounting_ = true;
475 pkgDelaySuspendInfo->baseTime_ = (int32_t)TimeProvider::GetCurrentTime() + MIN_ALLOW_QUOTA_TIME;
476 EXPECT_EQ(pkgDelaySuspendInfo->IsAllowRequest(), ERR_OK);
477 pkgDelaySuspendInfo->quota_ = 0;
478 pkgDelaySuspendInfo->baseTime_ = (int32_t)TimeProvider::GetCurrentTime();
479 EXPECT_EQ(pkgDelaySuspendInfo->IsAllowRequest(), ERR_BGTASK_TIME_INSUFFICIENT);
480 auto delayInfo1 = std::make_shared<DelaySuspendInfoEx>(1, 1);
481 auto delayInfo2 = std::make_shared<DelaySuspendInfoEx>(1, 2);
482 pkgDelaySuspendInfo->AddRequest(delayInfo1, 1);
483 pkgDelaySuspendInfo->AddRequest(delayInfo1, 1);
484 pkgDelaySuspendInfo->AddRequest(delayInfo2, 1);
485 EXPECT_EQ(pkgDelaySuspendInfo->IsAllowRequest(), ERR_BGTASK_EXCEEDS_THRESHOLD);
486 pkgDelaySuspendInfo->RemoveRequest(1);
487 pkgDelaySuspendInfo->RemoveRequest(1);
488 pkgDelaySuspendInfo->RemoveRequest(2);
489
490 pkgDelaySuspendInfo->requestList_.clear();
491 EXPECT_EQ(pkgDelaySuspendInfo->GetRemainDelayTime(-1), 0);
492 delayInfo1->actualDelayTime_ = 1;
493 auto delayInfo3 = std::make_shared<DelaySuspendInfoEx>(1, 1, 1);
494 pkgDelaySuspendInfo->requestList_.emplace_back(delayInfo3);
495 EXPECT_EQ(pkgDelaySuspendInfo->GetRemainDelayTime(-1), 0);
496 EXPECT_EQ(pkgDelaySuspendInfo->GetRemainDelayTime(1), 1);
497 }
498
499 /**
500 * @tc.name: PkgDelaySuspendInfoTest_002
501 * @tc.desc: test PkgDelaySuspendInfo class.
502 * @tc.type: FUNC
503 * @tc.require: issueI4QT3W issueI4QU0V
504 */
505 HWTEST_F(BgTaskMiscUnitTest, PkgDelaySuspendInfoTest_002, TestSize.Level1)
506 {
507 auto bgtaskService = sptr<BackgroundTaskMgrService>(new BackgroundTaskMgrService());
508 auto timerManager =
509 std::make_shared<TimerManager>(bgtaskService, AppExecFwk::EventRunner::Create("tdd_test_handler"));
510 auto pkgDelaySuspendInfo = std::make_shared<PkgDelaySuspendInfo>("bundleName1", 1, timerManager);
511 auto delayInfo1 = std::make_shared<DelaySuspendInfoEx>(1, 1);
512
513 pkgDelaySuspendInfo->requestList_.clear();
514 pkgDelaySuspendInfo->StartAccounting(1);
515 pkgDelaySuspendInfo->AddRequest(delayInfo1, 1);
516 pkgDelaySuspendInfo->StartAccounting(2);
517 pkgDelaySuspendInfo->StartAccounting(-1);
518 pkgDelaySuspendInfo->isCounting_ = false;
519 pkgDelaySuspendInfo->baseTime_ = 0;
520 pkgDelaySuspendInfo->StartAccounting(1);
521 pkgDelaySuspendInfo->isCounting_ = true;
522 pkgDelaySuspendInfo->baseTime_ = 1;
523 pkgDelaySuspendInfo->StartAccounting(1);
524
525 pkgDelaySuspendInfo->requestList_.clear();
526 pkgDelaySuspendInfo->StopAccounting(1);
527 pkgDelaySuspendInfo->AddRequest(delayInfo1, 1);
528 pkgDelaySuspendInfo->StopAccounting(-1);
529 pkgDelaySuspendInfo->baseTime_ = 0;
530 pkgDelaySuspendInfo->StopAccounting(1);
531 pkgDelaySuspendInfo->baseTime_ = 1;
532 pkgDelaySuspendInfo->StopAccounting(1);
533 pkgDelaySuspendInfo->requestList_.clear();
534 pkgDelaySuspendInfo->StopAccountingAll();
535 pkgDelaySuspendInfo->AddRequest(delayInfo1, 1);
536 pkgDelaySuspendInfo->baseTime_ = 0;
537 pkgDelaySuspendInfo->StopAccounting(1);
538 pkgDelaySuspendInfo->baseTime_ = 1;
539 pkgDelaySuspendInfo->StopAccounting(1);
540
541 pkgDelaySuspendInfo->isCounting_ = true;
542 pkgDelaySuspendInfo->quota_ = 0;
543 pkgDelaySuspendInfo->baseTime_ = (int32_t)TimeProvider::GetCurrentTime() - 1;
544 pkgDelaySuspendInfo->UpdateQuota(false);
545 pkgDelaySuspendInfo->quota_ = 0;
546 pkgDelaySuspendInfo->baseTime_ = (int32_t)TimeProvider::GetCurrentTime() + 1;
547 pkgDelaySuspendInfo->UpdateQuota(true);
548 EXPECT_TRUE(true);
549 }
550
551 /**
552 * @tc.name: SuspendControllerTest_001
553 * @tc.desc: test SuspendController.
554 * @tc.type: FUNC
555 * @tc.require: issueI4QT3W issueI4QU0V
556 */
557 HWTEST_F(BgTaskMiscUnitTest, SuspendControllerTest_001, TestSize.Level1)
558 {
559 SuspendController suspendController = SuspendController();
560 auto keyInfo = std::make_shared<KeyInfo>("bundleName", 1);
561 suspendController.RequestSuspendDelay(nullptr);
562 suspendController.RequestSuspendDelay(keyInfo);
563 suspendController.CancelSuspendDelay(nullptr);
564 suspendController.CancelSuspendDelay(keyInfo);
565 EXPECT_TRUE(true);
566 }
567
568 /**
569 * @tc.name: WatchdogTest_001
570 * @tc.desc: test Watchdog class.
571 * @tc.type: FUNC
572 * @tc.require: issueI4QT3W issueI4QU0V
573 */
574 HWTEST_F(BgTaskMiscUnitTest, WatchdogTest_001, TestSize.Level1)
575 {
576 auto deviceInfoManeger = std::make_shared<DeviceInfoManager>();
577 auto bgtaskService = sptr<BackgroundTaskMgrService>(new BackgroundTaskMgrService());
578 auto timerManager =
579 std::make_shared<TimerManager>(bgtaskService, AppExecFwk::EventRunner::Create("tdd_test_handler"));
580 auto decisionMaker = std::make_shared<DecisionMaker>(timerManager, deviceInfoManeger);
581 auto watchdog = std::make_shared<Watchdog>(bgtaskService, decisionMaker,
582 AppExecFwk::EventRunner::Create("tdd_test_handler"));
583 EXPECT_TRUE(watchdog->KillApplicationByUid("bundleName", 1, 1));
584 EXPECT_TRUE(watchdog->KillApplicationByUid("bundleName", 1, 1));
585 }
586
587 /**
588 * @tc.name: ConfigChangeObserver_001
589 * @tc.desc: test ConfigChangeObserver class.
590 * @tc.type: FUNC
591 * @tc.require: issueI4QT3W issueI4QU0V
592 */
593 HWTEST_F(BgTaskMiscUnitTest, ConfigChangeObserver_001, TestSize.Level1)
594 {
595 // Given
596 sptr<ConfigChangeObserver> configChangeObserver1 = sptr<ConfigChangeObserver>(
597 new ConfigChangeObserver(nullptr, nullptr));
598
599 // When & Then
600 EXPECT_FALSE(configChangeObserver1->CheckExpired());
601 }
602
603 /**
604 * @tc.name: ConfigChangeObserver_002
605 * @tc.desc: test ConfigChangeObserver class.
606 * @tc.type: FUNC
607 * @tc.require: issueI4QT3W issueI4QU0V
608 */
609 HWTEST_F(BgTaskMiscUnitTest, ConfigChangeObserver_002, TestSize.Level1)
610 {
611 // Given
612 auto handler = std::make_shared<OHOS::AppExecFwk::EventHandler>(nullptr);
613 auto bgContinuousTaskMgr = std::make_shared<BgContinuousTaskMgr>();
614 sptr<ConfigChangeObserver> configChangeObserver2 = sptr<ConfigChangeObserver>(
615 new ConfigChangeObserver(handler, nullptr));
616
617 // When & Then
618 EXPECT_FALSE(configChangeObserver2->CheckExpired());
619 }
620
621 /**
622 * @tc.name: ConfigChangeObserver_003
623 * @tc.desc: test ConfigChangeObserver class.
624 * @tc.type: FUNC
625 * @tc.require: issueI4QT3W issueI4QU0V
626 */
627 HWTEST_F(BgTaskMiscUnitTest, ConfigChangeObserver_003, TestSize.Level1)
628 {
629 // Given
630 auto handler = std::make_shared<OHOS::AppExecFwk::EventHandler>(nullptr);
631 auto bgContinuousTaskMgr = std::make_shared<BgContinuousTaskMgr>();
632 sptr<ConfigChangeObserver> configChangeObserver3 = sptr<ConfigChangeObserver>(
633 new ConfigChangeObserver(handler, bgContinuousTaskMgr));
634
635 // When & Then
636 EXPECT_TRUE(configChangeObserver3->CheckExpired());
637
638 AppExecFwk::Configuration configuration;
639 configChangeObserver3->OnConfigurationUpdated(configuration);
640 SUCCEED();
641 }
642
643 /**
644 * @tc.name: DataStorageHelper_001
645 * @tc.desc: test Watchdog class.
646 * @tc.type: FUNC
647 * @tc.require: issueI4QT3W issueI4QU0V
648 */
649 HWTEST_F(BgTaskMiscUnitTest, DataStorageHelper_001, TestSize.Level1)
650 {
651 std::unordered_map<std::string, std::shared_ptr<ContinuousTaskRecord>> continuousTaskInfosMap1;
652 auto continuousTaskRecord = std::make_shared<ContinuousTaskRecord>();
653 continuousTaskInfosMap1.emplace("key", continuousTaskRecord);
654 DelayedSingleton<DataStorageHelper>::GetInstance()->RefreshTaskRecord(continuousTaskInfosMap1);
655 std::unordered_map<std::string, std::shared_ptr<ContinuousTaskRecord>> continuousTaskInfosMap2;
656 EXPECT_EQ(DelayedSingleton<DataStorageHelper>::GetInstance()->RestoreTaskRecord(continuousTaskInfosMap2),
657 ERR_OK);
658 EXPECT_EQ(DelayedSingleton<DataStorageHelper>::GetInstance()->SaveJsonValueToFile("", ""),
659 ERR_BGTASK_CREATE_FILE_ERR);
660 nlohmann::json json1;
661 EXPECT_EQ(DelayedSingleton<DataStorageHelper>::GetInstance()->ParseJsonValueFromFile(json1, ""),
662 ERR_BGTASK_DATA_STORAGE_ERR);
663 EXPECT_FALSE(DelayedSingleton<DataStorageHelper>::GetInstance()->CreateNodeFile(""));
664 std::string fullPath;
665 EXPECT_FALSE(DelayedSingleton<DataStorageHelper>::GetInstance()->ConvertFullPath("", fullPath));
666 }
667
668 /**
669 * @tc.name: DataStorageHelper_002
670 * @tc.desc: test ParseFastSuspendDozeTime.
671 * @tc.type: FUNC
672 * @tc.require: issue#I99360
673 */
674 HWTEST_F(BgTaskMiscUnitTest, DataStorageHelper_002, TestSize.Level1)
675 {
676 int time = -1;
677 // 文件路径错误
678 std::string file("");
679 DelayedSingleton<DataStorageHelper>::GetInstance()->ParseFastSuspendDozeTime(file, time);
680 EXPECT_EQ(time, -1);
681 // 文件路径正确
682 file = "/etc/efficiency_manager/suspend_manager_config.json";
683 DelayedSingleton<DataStorageHelper>::GetInstance()->ParseFastSuspendDozeTime(file, time);
684 SUCCEED();
685 }
686
687 /**
688 * @tc.name: DecisionMakerTest_003
689 * @tc.desc: test Watchdog class.
690 * @tc.type: FUNC
691 * @tc.require: issueI4QT3W issueI4QU0V
692 */
693 HWTEST_F(BgTaskMiscUnitTest, DecisionMakerTest_003, TestSize.Level1)
694 {
695 auto deviceInfoManeger = std::make_shared<DeviceInfoManager>();
696 auto bgtaskService = sptr<BackgroundTaskMgrService>(new BackgroundTaskMgrService());
697 auto timerManager =
698 std::make_shared<TimerManager>(bgtaskService, AppExecFwk::EventRunner::Create("tdd_test_handler"));
699 auto decisionMaker = std::make_shared<DecisionMaker>(timerManager, deviceInfoManeger);
700 auto applicationStateObserver = sptr<DecisionMaker::ApplicationStateObserver>(
701 new (std::nothrow) DecisionMaker::ApplicationStateObserver(*decisionMaker));
702
703 AppExecFwk::AppStateData appStateData;
704 appStateData.uid = 1;
705 appStateData.bundleName = "bundleName1";
706 appStateData.state = static_cast<int32_t>(AppExecFwk::ApplicationState::APP_STATE_FOREGROUND);
707 applicationStateObserver->OnForegroundApplicationChanged(appStateData);
708 appStateData.state = static_cast<int32_t>(AppExecFwk::ApplicationState::APP_STATE_FOCUS);
709 applicationStateObserver->OnForegroundApplicationChanged(appStateData);
710
711 auto keyInfo1 = std::make_shared<KeyInfo>("bundleName1", 1);
712 auto pkgDelaySuspendInfo = std::make_shared<PkgDelaySuspendInfo>("bundleName1", 1, timerManager);
713 auto delayInfo = std::make_shared<DelaySuspendInfoEx>(1);
714 pkgDelaySuspendInfo->requestList_.push_back(delayInfo);
715 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo1] = pkgDelaySuspendInfo;
716 auto keyInfo = std::make_shared<KeyInfo>("bundleName1", 1);
717 decisionMaker->pkgBgDurationMap_[keyInfo] = TimeProvider::GetCurrentTime() - ALLOW_REQUEST_TIME_BG - 1;
718 appStateData.state = static_cast<int32_t>(AppExecFwk::ApplicationState::APP_STATE_FOREGROUND);
719 applicationStateObserver->OnForegroundApplicationChanged(appStateData);
720 appStateData.state = static_cast<int32_t>(AppExecFwk::ApplicationState::APP_STATE_FOCUS);
721 applicationStateObserver->OnForegroundApplicationChanged(appStateData);
722
723 decisionMaker->pkgDelaySuspendInfoMap_.clear();
724 appStateData.state = static_cast<int32_t>(AppExecFwk::ApplicationState::APP_STATE_BACKGROUND);
725 applicationStateObserver->OnForegroundApplicationChanged(appStateData);
726 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo1] = pkgDelaySuspendInfo;
727 applicationStateObserver->OnForegroundApplicationChanged(appStateData);
728 EXPECT_EQ((int32_t)decisionMaker->pkgDelaySuspendInfoMap_.size(), 1);
729 }
730
731 /**
732 * @tc.name: DecisionMakerTest_004
733 * @tc.desc: test PauseTransientTaskTimeForInner.
734 * @tc.type: FUNC
735 * @tc.require: issueI936BL
736 */
737 HWTEST_F(BgTaskMiscUnitTest, DecisionMakerTest_004, TestSize.Level1)
738 {
739 auto deviceInfoManeger = std::make_shared<DeviceInfoManager>();
740 auto bgtaskService = sptr<BackgroundTaskMgrService>(new BackgroundTaskMgrService());
741 auto timerManager = std::make_shared<TimerManager>(bgtaskService,
742 AppExecFwk::EventRunner::Create("tdd_test_handler"));
743 auto decisionMaker = std::make_shared<DecisionMaker>(timerManager, deviceInfoManeger);
744
745 decisionMaker->pkgBgDurationMap_.clear();
746 std::string name = "bundleName1";
747 int32_t uid = 1;
748 EXPECT_EQ(decisionMaker->PauseTransientTaskTimeForInner(uid, name), ERR_BGTASK_FOREGROUND);
749
750 auto keyInfo = std::make_shared<KeyInfo>("bundleName1", 1);
751 decisionMaker->pkgBgDurationMap_[keyInfo] = TimeProvider::GetCurrentTime() - ALLOW_REQUEST_TIME_BG - 1;
752 decisionMaker->pkgDelaySuspendInfoMap_.clear();
753 EXPECT_EQ(decisionMaker->PauseTransientTaskTimeForInner(uid, name), ERR_BGTASK_NOREQUEST_TASK);
754
755 auto keyInfo1 = std::make_shared<KeyInfo>("bundleName1", 1);
756 auto pkgDelaySuspendInfo = std::make_shared<PkgDelaySuspendInfo>("bundleName1", 1, timerManager);
757 auto delayInfo = std::make_shared<DelaySuspendInfoEx>(1);
758 pkgDelaySuspendInfo->requestList_.push_back(delayInfo);
759 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo1] = pkgDelaySuspendInfo;
760 EXPECT_EQ(decisionMaker->PauseTransientTaskTimeForInner(uid, name), ERR_OK);
761 }
762
763 /**
764 * @tc.name: DecisionMakerTest_005
765 * @tc.desc: test StartTransientTaskTimeForInner.
766 * @tc.type: FUNC
767 * @tc.require: issueI936BL
768 */
769 HWTEST_F(BgTaskMiscUnitTest, DecisionMakerTest_005, TestSize.Level1)
770 {
771 auto deviceInfoManeger = std::make_shared<DeviceInfoManager>();
772 auto bgtaskService = sptr<BackgroundTaskMgrService>(new BackgroundTaskMgrService());
773 auto timerManager = std::make_shared<TimerManager>(bgtaskService,
774 AppExecFwk::EventRunner::Create("tdd_test_handler"));
775 auto decisionMaker = std::make_shared<DecisionMaker>(timerManager, deviceInfoManeger);
776
777 decisionMaker->pkgBgDurationMap_.clear();
778 std::string name = "bundleName1";
779 int32_t uid = 1;
780 EXPECT_EQ(decisionMaker->StartTransientTaskTimeForInner(uid, name), ERR_BGTASK_FOREGROUND);
781
782 auto keyInfo = std::make_shared<KeyInfo>("bundleName1", 1);
783 decisionMaker->pkgBgDurationMap_[keyInfo] = TimeProvider::GetCurrentTime() - ALLOW_REQUEST_TIME_BG - 1;
784 decisionMaker->pkgDelaySuspendInfoMap_.clear();
785 EXPECT_EQ(decisionMaker->StartTransientTaskTimeForInner(uid, name), ERR_BGTASK_NOREQUEST_TASK);
786
787 auto keyInfo1 = std::make_shared<KeyInfo>("bundleName1", 1);
788 auto pkgDelaySuspendInfo = std::make_shared<PkgDelaySuspendInfo>("bundleName1", 1, timerManager);
789 auto delayInfo = std::make_shared<DelaySuspendInfoEx>(1);
790 pkgDelaySuspendInfo->requestList_.push_back(delayInfo);
791 decisionMaker->pkgDelaySuspendInfoMap_[keyInfo1] = pkgDelaySuspendInfo;
792 EXPECT_EQ(decisionMaker->StartTransientTaskTimeForInner(uid, name), ERR_OK);
793 }
794
795 /**
796 * @tc.name: DelaySuspendInfoEx_001
797 * @tc.desc: test DelaySuspendInfoEx.
798 * @tc.type: FUNC
799 * @tc.require: issueI4QT3W issueI4QU0V
800 */
801 HWTEST_F(BgTaskMiscUnitTest, DelaySuspendInfoEx_001, TestSize.Level1)
802 {
803 auto delayInfo = std::make_shared<DelaySuspendInfoEx>(1);
804 delayInfo->baseTime_ = 1;
805 delayInfo->StartAccounting();
806 delayInfo->baseTime_ = 0;
807 delayInfo->StopAccounting();
808 EXPECT_EQ(delayInfo->spendTime_, 0);
809 }
810 }
811 }
812