1 /*
2  * Copyright (c) 2021-2023 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 #define private public
17 #include "app_mgr_service.h"
18 #include "app_mgr_service_inner.h"
19 #undef private
20 
21 #include <gmock/gmock.h>
22 #include <gtest/gtest.h>
23 
24 #include "app_scheduler_host.h"
25 #include "app_scheduler_proxy.h"
26 #include "mock_app_mgr_service_inner.h"
27 #include "mock_native_token.h"
28 #include "semaphore_ex.h"
29 
30 using namespace testing::ext;
31 using testing::_;
32 using testing::Invoke;
33 using testing::InvokeWithoutArgs;
34 using testing::Return;
35 
36 namespace {
37 constexpr int COUNT = 1;
38 }
39 
40 namespace OHOS {
41 namespace AppExecFwk {
42 class TestAppSchedulerImpl : public AppSchedulerHost {
43 public:
ScheduleForegroundApplication()44     bool ScheduleForegroundApplication() override
45     {
46         return true;
47     }
ScheduleBackgroundApplication()48     void ScheduleBackgroundApplication() override
49     {}
ScheduleTerminateApplication(bool isLastProcess=false)50     void ScheduleTerminateApplication(bool isLastProcess = false) override
51     {}
ScheduleShrinkMemory(const int)52     void ScheduleShrinkMemory(const int) override
53     {}
ScheduleLowMemory()54     void ScheduleLowMemory() override
55     {}
ScheduleMemoryLevel(const int)56     void ScheduleMemoryLevel(const int) override
57     {}
ScheduleHeapMemory(const int,OHOS::AppExecFwk::MallocInfo &)58     void ScheduleHeapMemory(const int, OHOS::AppExecFwk::MallocInfo&) override
59     {}
ScheduleLaunchApplication(const AppLaunchData &,const Configuration &)60     void ScheduleLaunchApplication(const AppLaunchData&, const Configuration&) override
61     {}
ScheduleLaunchAbility(const AbilityInfo &,const sptr<IRemoteObject> &,const std::shared_ptr<AAFwk::Want> &,int32_t)62     void ScheduleLaunchAbility(const AbilityInfo&, const sptr<IRemoteObject>&,
63         const std::shared_ptr<AAFwk::Want>&, int32_t) override
64     {}
ScheduleCleanAbility(const sptr<IRemoteObject> &,bool isCacheProcess)65     void ScheduleCleanAbility(const sptr<IRemoteObject>&, bool isCacheProcess) override
66     {}
ScheduleProfileChanged(const Profile &)67     void ScheduleProfileChanged(const Profile&) override
68     {}
ScheduleConfigurationUpdated(const Configuration &)69     void ScheduleConfigurationUpdated(const Configuration&) override
70     {}
ScheduleProcessSecurityExit()71     void ScheduleProcessSecurityExit() override
72     {}
ScheduleAbilityStage(const HapModuleInfo &)73     void ScheduleAbilityStage(const HapModuleInfo&) override
74     {}
ScheduleUpdateApplicationInfoInstalled(const ApplicationInfo &)75     void ScheduleUpdateApplicationInfoInstalled(const ApplicationInfo&) override
76     {}
ScheduleAcceptWant(const AAFwk::Want & want,const std::string & moduleName)77     void ScheduleAcceptWant(const AAFwk::Want& want, const std::string& moduleName) override
78     {}
ScheduleNewProcessRequest(const AAFwk::Want & want,const std::string & moduleName)79     void ScheduleNewProcessRequest(const AAFwk::Want& want, const std::string& moduleName) override
80     {}
ScheduleNotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)81     int32_t ScheduleNotifyLoadRepairPatch(const std::string& bundleName,
82         const sptr<IQuickFixCallback>& callback, const int32_t recordId) override
83     {
84         return 0;
85     }
ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> & callback,const int32_t recordId)86     int32_t ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback>& callback, const int32_t recordId) override
87     {
88         return 0;
89     }
ScheduleNotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)90     int32_t ScheduleNotifyUnLoadRepairPatch(const std::string& bundleName,
91         const sptr<IQuickFixCallback>& callback, const int32_t recordId) override
92     {
93         return 0;
94     }
ScheduleNotifyAppFault(const FaultData & faultData)95     int32_t ScheduleNotifyAppFault(const FaultData &faultData) override
96     {
97         return 0;
98     }
99 
ScheduleChangeAppGcState(int32_t state)100     int32_t ScheduleChangeAppGcState(int32_t state) override
101     {
102         return 0;
103     }
104 
AttachAppDebug()105     void AttachAppDebug() override
106     {}
107 
DetachAppDebug()108     void DetachAppDebug() override
109     {}
110 
ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)111     void ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info) override
112     {}
113 
ScheduleDumpIpcStart(std::string & result)114     int32_t ScheduleDumpIpcStart(std::string& result) override
115     {
116         return 0;
117     }
118 
ScheduleDumpIpcStop(std::string & result)119     int32_t ScheduleDumpIpcStop(std::string& result) override
120     {
121         return 0;
122     }
123 
ScheduleDumpIpcStat(std::string & result)124     int32_t ScheduleDumpIpcStat(std::string& result) override
125     {
126         return 0;
127     }
128 
ScheduleCacheProcess()129     void ScheduleCacheProcess() override
130     {}
131 
ScheduleDumpFfrt(std::string & result)132     int32_t ScheduleDumpFfrt(std::string& result) override
133     {
134         return 0;
135     }
136 
ScheduleClearPageStack()137     void ScheduleClearPageStack() override
138     {}
139 };
140 class AppMgrServiceModuleTest : public testing::Test {
141 public:
142     static void SetUpTestCase();
143     static void TearDownTestCase();
144     void SetUp();
145     void TearDown();
146 
147 protected:
148     inline static std::shared_ptr<MockAppMgrServiceInner> mockAppMgrServiceInner_{ nullptr };
149     inline static std::shared_ptr<AppMgrService> appMgrService_{ nullptr };
150     inline static sptr<IRemoteObject> testRemoteObject_{ nullptr };
151 };
152 
SetUpTestCase()153 void AppMgrServiceModuleTest::SetUpTestCase()
154 {
155     MockNativeToken::SetNativeToken();
156     if (!appMgrService_) {
157         appMgrService_ = std::make_shared<AppMgrService>();
158     }
159 
160     if (!mockAppMgrServiceInner_) {
161         mockAppMgrServiceInner_ = std::make_shared<MockAppMgrServiceInner>();
162     }
163 
164     if (appMgrService_ && mockAppMgrServiceInner_) {
165         appMgrService_->appMgrServiceInner_ = mockAppMgrServiceInner_;
166         appMgrService_->OnStart();
167     }
168 
169     if (!testRemoteObject_) {
170         testRemoteObject_ = static_cast<IRemoteObject*>(new TestAppSchedulerImpl);
171     }
172 }
173 
TearDownTestCase()174 void AppMgrServiceModuleTest::TearDownTestCase()
175 {
176     if (testRemoteObject_) {
177         testRemoteObject_.clear();
178     }
179 
180     if (mockAppMgrServiceInner_) {
181         mockAppMgrServiceInner_.reset();
182     }
183 
184     if (appMgrService_) {
185         appMgrService_->OnStop();
186         int sleepTime = 1;
187         sleep(sleepTime);  // Waiting for appMgrService_'s event loop backend thread exited.
188         if (appMgrService_->appMgrServiceInner_) {
189             appMgrService_->appMgrServiceInner_.reset();
190         }
191         if (appMgrService_->amsMgrScheduler_) {
192             appMgrService_->amsMgrScheduler_.clear();
193         }
194         appMgrService_.reset();
195     }
196 }
197 
SetUp()198 void AppMgrServiceModuleTest::SetUp()
199 {}
200 
TearDown()201 void AppMgrServiceModuleTest::TearDown()
202 {}
203 
204 /*
205  * Feature: AppMgrService
206  * Function: GetAmsMgr
207  * SubFunction: NA
208  * FunctionPoints: NA
209  * CaseDescription: Check GetAmsMgr.
210  */
211 HWTEST_F(AppMgrServiceModuleTest, GetAmsMgr_001, TestSize.Level1)
212 {
213     EXPECT_TRUE(appMgrService_);
214 
215     auto amsMgr = appMgrService_->GetAmsMgr();
216 
217     EXPECT_TRUE(amsMgr);
218 }
219 
220 /*
221  * Feature: AppMgrService
222  * Function: AttachApplication
223  * SubFunction: NA
224  * FunctionPoints: AppMgrService => AppMgrServiceInner: AttachApplication
225  * CaseDescription: Check event loop AttachApplication task post from AppMgrService to AppMgrServiceInner.
226  */
227 HWTEST_F(AppMgrServiceModuleTest, AttachApplication_001, TestSize.Level1)
228 {
229     EXPECT_TRUE(appMgrService_);
230     EXPECT_TRUE(mockAppMgrServiceInner_);
231     EXPECT_TRUE(testRemoteObject_);
232 
233     for (int i = 0; i < COUNT; ++i) {
234         EXPECT_CALL(*mockAppMgrServiceInner_, AddAppDeathRecipient(_, _))
235             .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner_.get(), &MockAppMgrServiceInner::Post));
236         EXPECT_CALL(*mockAppMgrServiceInner_, AttachApplication(_, _))
237             .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner_.get(), &MockAppMgrServiceInner::Post));
238 
239         sptr<IRemoteObject> client;
240         appMgrService_->AttachApplication(client);
241         mockAppMgrServiceInner_->Wait();
242     }
243 }
244 
245 /*
246  * Feature: AppMgrService
247  * Function: ApplicationForegrounded
248  * SubFunction: NA
249  * FunctionPoints: AppMgrService => AppMgrServiceInner: ApplicationForegrounded
250  * CaseDescription: Check event loop ApplicationForegrounded task post from AppMgrService to AppMgrServiceInner.
251  */
252 HWTEST_F(AppMgrServiceModuleTest, ApplicationForegrounded_001, TestSize.Level1)
253 {
254     EXPECT_TRUE(appMgrService_);
255     EXPECT_TRUE(mockAppMgrServiceInner_);
256 
257     auto appMgrService = std::make_shared<AppMgrService>();
258     int32_t testRecordId = 123;
259     bool testResult = false;
260     Semaphore sem(0);
261 
__anone22fe8df0202(const int32_t recordId) 262     auto mockHandler = [&](const int32_t recordId) {
263         testResult = (recordId == testRecordId);
264         sem.Post();
265     };
266 
267     for (int i = 0; i < COUNT; ++i) {
268         testResult = false;
269 
270         EXPECT_CALL(*mockAppMgrServiceInner_, ApplicationForegrounded(_)).Times(1).WillOnce(Invoke(mockHandler));
271 
272         appMgrService->SetInnerService(nullptr);
273         appMgrService->ApplicationForegrounded(testRecordId);
274 
275         EXPECT_TRUE(appMgrService != nullptr);
276     }
277 }
278 
279 /*
280  * Feature: AppMgrService
281  * Function: ApplicationBackgrounded
282  * SubFunction: NA
283  * FunctionPoints: AppMgrService => AppMgrServiceInner: ApplicationBackgrounded
284  * CaseDescription: Check event loop ApplicationBackgrounded task post from AppMgrService to AppMgrServiceInner.
285  */
286 HWTEST_F(AppMgrServiceModuleTest, ApplicationBackgrounded_001, TestSize.Level1)
287 {
288     EXPECT_TRUE(appMgrService_);
289     EXPECT_TRUE(mockAppMgrServiceInner_);
290 
291     auto appMgrService = std::make_shared<AppMgrService>();
292     int32_t testRecordId = 123;
293     bool testResult = false;
294     Semaphore sem(0);
295 
__anone22fe8df0302(const int32_t recordId) 296     auto mockHandler = [&](const int32_t recordId) {
297         testResult = (recordId == testRecordId);
298         sem.Post();
299     };
300 
301     for (int i = 0; i < COUNT; ++i) {
302         testResult = false;
303 
304         EXPECT_CALL(*mockAppMgrServiceInner_, ApplicationBackgrounded(_)).Times(1).WillOnce(Invoke(mockHandler));
305 
306         appMgrService->SetInnerService(nullptr);
307         appMgrService->ApplicationBackgrounded(testRecordId);
308 
309         EXPECT_TRUE(appMgrService != nullptr);
310     }
311 }
312 
313 /*
314  * Feature: AppMgrService
315  * Function: ApplicationTerminated
316  * SubFunction: NA
317  * FunctionPoints: AppMgrService => AppMgrServiceInner: ApplicationTerminated
318  * CaseDescription: Check event loop ApplicationTerminated task post from AppMgrService to AppMgrServiceInner.
319  */
320 HWTEST_F(AppMgrServiceModuleTest, ApplicationTerminated_001, TestSize.Level1)
321 {
322     EXPECT_TRUE(appMgrService_);
323     EXPECT_TRUE(mockAppMgrServiceInner_);
324 
325     auto appMgrService = std::make_shared<AppMgrService>();
326     int32_t testRecordId = 123;
327     bool testResult = false;
328     Semaphore sem(0);
329 
__anone22fe8df0402(const int32_t recordId) 330     auto mockHandler = [&testResult, testRecordId, &sem](const int32_t recordId) {
331         testResult = (recordId == testRecordId);
332         sem.Post();
333     };
334 
335     for (int i = 0; i < COUNT; ++i) {
336         testResult = false;
337 
338         EXPECT_CALL(*mockAppMgrServiceInner_, ApplicationTerminated(_)).Times(1).WillOnce(Invoke(mockHandler));
339 
340         appMgrService->SetInnerService(nullptr);
341         appMgrService->ApplicationTerminated(testRecordId);
342 
343         EXPECT_TRUE(appMgrService != nullptr);
344     }
345 }
346 
347 /*
348  * Feature: AppMgrService
349  * Function: ClearUpApplicationData
350  * SubFunction: NA
351  * FunctionPoints: AppMgrService => AppMgrServiceInner: ClearUpApplicationData
352  * CaseDescription: Check event loop ClearUpApplicationData task post from AppMgrService to AppMgrServiceInner.
353  */
354 HWTEST_F(AppMgrServiceModuleTest, ClearUpApplicationData_001, TestSize.Level1)
355 {
356     auto appMgrService = std::make_shared<AppMgrService>();
357     std::shared_ptr<OHOS::AAFwk::TaskHandlerWrap> taskHandler_ =
358         OHOS::AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME);
359     std::string bundleName = "bundleName";
360     appMgrService->SetInnerService(std::make_shared<AppMgrServiceInner>());
361     appMgrService->eventHandler_ = std::make_shared<AMSEventHandler>(taskHandler_, appMgrService->appMgrServiceInner_);
362     int32_t res = appMgrService->ClearUpApplicationData(bundleName, 0);
363     EXPECT_EQ(res, ERR_INVALID_OPERATION);
364 }
365 
366 /*
367  * Feature: AppMgrService
368  * Function: GetAllRunningProcesses
369  * SubFunction: NA
370  * FunctionPoints: AppMgrService => AppMgrServiceInner: GetAllRunningProcesses
371  * CaseDescription: Check GetAllRunningProcesses.
372  */
373 HWTEST_F(AppMgrServiceModuleTest, GetAllRunningProcesses_001, TestSize.Level1)
374 {
375     EXPECT_TRUE(appMgrService_);
376     EXPECT_TRUE(mockAppMgrServiceInner_);
377 
378     std::vector<RunningProcessInfo> testRunningProcessInfo;
379 
380     int32_t testPid = 456;
381     std::string testProcessName = "testProcess";
382 
383     Semaphore sem(0);
__anone22fe8df0502(std::vector<RunningProcessInfo>& runningProcessInfo) 384     auto mockHandler = [testProcessName, testPid, &sem](std::vector<RunningProcessInfo>& runningProcessInfo) {
385         auto& it = runningProcessInfo.emplace_back();
386         it.processName_ = testProcessName;
387         it.pid_ = testPid;
388         sem.Post();
389         return ERR_OK;
390     };
391 
392     for (int i = 0; i < COUNT; ++i) {
393         testRunningProcessInfo.clear();
394         EXPECT_CALL(*mockAppMgrServiceInner_, GetAllRunningProcesses(_)).Times(1).WillOnce(Invoke(mockHandler));
395 
396         auto result = appMgrService_->GetAllRunningProcesses(testRunningProcessInfo);
397         sem.Wait();
398 
399         EXPECT_EQ(testRunningProcessInfo.size(), size_t(1));
400         EXPECT_EQ(testRunningProcessInfo[0].processName_, testProcessName);
401         EXPECT_EQ(testRunningProcessInfo[0].pid_, testPid);
402         EXPECT_EQ(result, ERR_OK);
403     }
404 }
405 
406 /*
407  * Feature: AppMgrService
408  * Function: GetAllRunningInstanceKeysBySelf
409  * SubFunction: NA
410  * FunctionPoints: AppMgrService => AppMgrServiceInner: GetAllRunningInstanceKeysBySelf
411  * CaseDescription: Check GetAllRunningInstanceKeysBySelf.
412  */
413 HWTEST_F(AppMgrServiceModuleTest, GetAllRunningInstanceKeysBySelf_001, TestSize.Level1)
414 {
415     EXPECT_TRUE(appMgrService_);
416     EXPECT_TRUE(mockAppMgrServiceInner_);
417 
418     std::vector<std::string> testInstanceKeys;
419 
420     EXPECT_CALL(*mockAppMgrServiceInner_, GetAllRunningInstanceKeysBySelf(_))
421         .Times(1).WillOnce(Return(ERR_OK));
422 
423     auto result = appMgrService_->GetAllRunningInstanceKeysBySelf(testInstanceKeys);
424     EXPECT_EQ(result, ERR_OK);
425 }
426 
427 /*
428  * Feature: AppMgrService
429  * Function: GetAllRunningInstanceKeysByBundleName
430  * SubFunction: NA
431  * FunctionPoints: AppMgrService => AppMgrServiceInner: GetAllRunningInstanceKeysByBundleName
432  * CaseDescription: Check GetAllRunningInstanceKeysByBundleName.
433  */
434 HWTEST_F(AppMgrServiceModuleTest, GetAllRunningInstanceKeysByBundleName_001, TestSize.Level1)
435 {
436     EXPECT_TRUE(appMgrService_);
437     EXPECT_TRUE(mockAppMgrServiceInner_);
438 
439     std::string testBundleName = "testBundleName";
440     std::vector<std::string> testInstanceKeys;
441 
442     EXPECT_CALL(*mockAppMgrServiceInner_, GetAllRunningInstanceKeysByBundleName(_, _, _))
443         .Times(1).WillOnce(Return(ERR_OK));
444 
445     auto result = appMgrService_->GetAllRunningInstanceKeysByBundleName(testBundleName, testInstanceKeys);
446     EXPECT_EQ(result, ERR_OK);
447 }
448 
449 /*
450  * Feature: AppMgrService
451  * Function: KillApplication
452  * SubFunction: NA
453  * FunctionPoints: AppMgrService => AppMgrServiceInner: KillApplication
454  * CaseDescription: Check KillApplication task post from AppMgrService to AppMgrServiceInner.
455  */
456 HWTEST_F(AppMgrServiceModuleTest, KillApplication_001, TestSize.Level1)
457 {
458     EXPECT_TRUE(appMgrService_);
459     EXPECT_TRUE(mockAppMgrServiceInner_);
460 
461     std::string testBundleName("testApp");
462     bool testResult = false;
463     Semaphore sem(0);
464 
465     auto mockHandler = [&testResult, testBundleName, &sem](
__anone22fe8df0602( const std::string& bundleName, const bool clearPageStack = false) 466         const std::string& bundleName, const bool clearPageStack = false) {
467         testResult = (bundleName == testBundleName);
468         sem.Post();
469         return 0;
470     };
471 
472     for (int i = 0; i < COUNT; ++i) {
473         testResult = false;
474 
475         EXPECT_CALL(*mockAppMgrServiceInner_, KillApplication(_, _)).Times(1).WillOnce(Invoke(mockHandler));
476 
477         int ret = appMgrService_->GetAmsMgr()->KillApplication(testBundleName);
478 
479         sem.Wait();
480 
481         EXPECT_TRUE(testResult);
482         EXPECT_EQ(ret, 0);
483     }
484 }
485 
486 /*
487  * Feature: AppMgrService
488  * Function: QueryServiceState
489  * SubFunction: AppMgrService => AppMgrServiceInner: QueryAppSpawnConnectionState
490  * FunctionPoints: NA
491  * CaseDescription: Check QueryServiceState.
492  */
493 HWTEST_F(AppMgrServiceModuleTest, QueryServiceState_001, TestSize.Level1)
494 {
495     EXPECT_TRUE(appMgrService_);
496     EXPECT_TRUE(mockAppMgrServiceInner_);
497 
498     SpawnConnectionState testSpawnConnectionState = SpawnConnectionState::STATE_CONNECTED;
499     Semaphore sem(0);
500 
__anone22fe8df0702() 501     auto mockHandler = [&]() {
502         sem.Post();
503         return testSpawnConnectionState;
504     };
505 
506     for (int i = 0; i < COUNT; ++i) {
507         EXPECT_CALL(*mockAppMgrServiceInner_, QueryAppSpawnConnectionState()).Times(1).WillOnce(Invoke(mockHandler));
508 
509         auto serviceState = appMgrService_->QueryServiceState();
510 
511         sem.Wait();
512 
513         EXPECT_EQ(serviceState.connectionState, testSpawnConnectionState);
514     }
515 }
516 }  // namespace AppExecFwk
517 }  // namespace OHOS
518