1 /*
2  * Copyright (c) 2021-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 <gtest/gtest.h>
17 
18 #define private public
19 #define protected public
20 #include "bundle_manager_helper.h"
21 #undef private
22 #undef protected
23 #define UNIT_TEST
24 #include "common_event_constant.h"
25 #include "common_event_listener.h"
26 #include "datetime_ex.h"
27 #include "inner_common_event_manager.h"
28 #include "mock_bundle_manager.h"
29 
30 using namespace testing::ext;
31 using namespace OHOS::EventFwk;
32 using namespace OHOS::AppExecFwk;
33 namespace {
34 const std::string EVENTCASE1 = "com.ces.test.event.case1";
35 const std::string EVENTCASE2 = "com.ces.test.event.case2";
36 const std::string EVENTCASE3 = "com.ces.test.event.case3";
37 const std::string EVENTCASE4 = "com.ces.test.event.case4";
38 const std::string EVENTCASE5 = "com.ces.test.event.case5";
39 const std::string EVENTCASE6 = "com.ces.test.event.case6";
40 const std::string EVENTCASE7 = "com.ces.test.event.case7";
41 const std::string INNITDATA = "com.ces.test.initdata";
42 const std::string CHANGEDATA = "com.ces.test.changedata";
43 const std::string CHANGEDATA2 = "com.ces.test.changedata2";
44 constexpr uint8_t INNITCODE = 0;
45 constexpr uint8_t CHANGECODE = 1;
46 constexpr uint8_t CHANGECODE2 = 2;
47 constexpr uint8_t PID = 0;
48 constexpr uint16_t SYSTEM_UID = 1000;
49 constexpr uid_t UID = 1;
50 constexpr uid_t UID2 = 2;
51 constexpr uint8_t FREEZE_SLEEP = 1;
52 constexpr uint8_t FREEZE_SLEEP2 = 12;
53 bool isFreeze_uid = false;
54 bool isFreeze_uid2 = false;
55 std::mutex mtx;
56 
57 static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
58 OHOS::sptr<OHOS::IRemoteObject> commonEventListener;
59 OHOS::sptr<OHOS::IRemoteObject> commonEventListener2;
60 OHOS::sptr<OHOS::IRemoteObject> commonEventListener3;
61 class CommonEventFreezeTest : public testing::Test {
62 public:
CommonEventFreezeTest()63     CommonEventFreezeTest()
64     {}
~CommonEventFreezeTest()65     ~CommonEventFreezeTest()
66     {}
67     static void SetUpTestCase(void);
68     static void TearDownTestCase(void);
69     void SetUp();
70     void TearDown();
71     bool SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber, uid_t callingUid,
72         OHOS::sptr<OHOS::IRemoteObject> &commonEventListener);
73     bool PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
74         const std::shared_ptr<CommonEventSubscriber> &subscriber, OHOS::sptr<OHOS::IRemoteObject> &commonEventListener);
75     static bool FinishReceiver(
76         const OHOS::sptr<OHOS::IRemoteObject> &proxy, const int &code, const std::string &data, const bool &abortEvent);
77     bool Freeze(const uid_t &uid);
78     bool Unfreeze(const uid_t &uid);
79     void AsyncProcess();
80 
81 private:
82     std::shared_ptr<EventRunner> runner_;
83     static std::shared_ptr<EventHandler> handler_;
84     static std::shared_ptr<InnerCommonEventManager> innerCommonEventManager_;
85 };
86 
87 class SubscriberTest : public CommonEventSubscriber {
88 public:
SubscriberTest(const CommonEventSubscribeInfo & sp)89     explicit SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
90     {
91         handler_ = std::make_shared<EventHandler>(EventRunner::Create());
92     }
93 
~SubscriberTest()94     ~SubscriberTest()
95     {}
96 
OnReceiveEvent(const CommonEventData & data)97     virtual void OnReceiveEvent(const CommonEventData &data)
98     {
99         std::string action = data.GetWant().GetAction();
100         if (action == EVENTCASE1) {
101             ProcessSubscriberTestCase1(data);
102         } else if (action == EVENTCASE2) {
103             ProcessSubscriberTestCase2(data);
104         } else {
105         }
106     }
107 
108 private:
ProcessSubscriberTestCase1(CommonEventData data)109     void ProcessSubscriberTestCase1(CommonEventData data)
110     {
111         EVENT_LOGI("Subscriber1: Type:  %{public}s", data.GetWant().GetType().c_str());
112         if (!IsOrderedCommonEvent()) {
113             return;
114         }
115         EXPECT_EQ(INNITCODE, data.GetCode());
116         EXPECT_EQ(INNITDATA, data.GetData());
117         std::shared_ptr<AsyncCommonEventResult> result = GoAsyncCommonEvent();
118         std::function<void()> asyncProcessFunc = std::bind(&SubscriberTest::AsyncProcess, this, commonEventListener);
119         handler_->PostTask(asyncProcessFunc);
120     }
ProcessSubscriberTestCase2(CommonEventData data)121     void ProcessSubscriberTestCase2(CommonEventData data)
122     {
123         EVENT_LOGI("Subscriber1: Type: %{public}s ", data.GetWant().GetType().c_str());
124         EXPECT_EQ(INNITCODE, data.GetCode());
125         EXPECT_EQ(INNITDATA, data.GetData());
126     }
127 
AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)128     void AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)
129     {
130         EXPECT_TRUE(CommonEventFreezeTest::FinishReceiver(commonEventListener, CHANGECODE, CHANGEDATA, false));
131     }
132 
133 private:
134     std::shared_ptr<EventHandler> handler_;
135 };
136 
137 class SubscriberTest2 : public CommonEventSubscriber {
138 public:
SubscriberTest2(const CommonEventSubscribeInfo & sp)139     explicit SubscriberTest2(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
140     {
141         handler_ = std::make_shared<EventHandler>(EventRunner::Create());
142     }
143 
~SubscriberTest2()144     ~SubscriberTest2()
145     {}
146 
OnReceiveEvent(const CommonEventData & data)147     virtual void OnReceiveEvent(const CommonEventData &data)
148     {
149         std::string action = data.GetWant().GetAction();
150         if (action == EVENTCASE1) {
151             ProcessSubscriberTest2Case1(data);
152         } else if (action == EVENTCASE2) {
153             ProcessSubscriberTest2Case2(data);
154         } else {
155         }
156     }
157 
158 private:
ProcessSubscriberTest2Case1(CommonEventData data)159     void ProcessSubscriberTest2Case1(CommonEventData data)
160     {
161         EVENT_LOGI("Subscriber2: Type:  %{public}s", data.GetWant().GetType().c_str());
162         if (!IsOrderedCommonEvent()) {
163             return;
164         }
165         if (!isFreeze_uid) {
166             EXPECT_EQ(CHANGECODE, data.GetCode());
167             EXPECT_EQ(CHANGEDATA, data.GetData());
168         } else {
169             EXPECT_EQ(INNITCODE, data.GetCode());
170             EXPECT_EQ(INNITDATA, data.GetData());
171         }
172         std::shared_ptr<AsyncCommonEventResult> result = GoAsyncCommonEvent();
173         std::function<void()> asyncProcessFunc = std::bind(&SubscriberTest2::AsyncProcess, this, commonEventListener2);
174         handler_->PostTask(asyncProcessFunc);
175     }
ProcessSubscriberTest2Case2(CommonEventData data)176     void ProcessSubscriberTest2Case2(CommonEventData data)
177     {
178         EVENT_LOGI("Subscriber2: Type: %{public}s ", data.GetWant().GetType().c_str());
179         EXPECT_EQ(INNITCODE, data.GetCode());
180         EXPECT_EQ(INNITDATA, data.GetData());
181     }
182 
AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)183     void AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)
184     {
185         EXPECT_TRUE(CommonEventFreezeTest::FinishReceiver(commonEventListener, CHANGECODE2, CHANGEDATA2, false));
186     }
187 
188 private:
189     std::shared_ptr<EventHandler> handler_;
190 };
191 
192 class SubscriberTestLast : public CommonEventSubscriber {
193 public:
SubscriberTestLast()194     SubscriberTestLast() : CommonEventSubscriber()
195     {
196         handler_ = std::make_shared<EventHandler>(EventRunner::Create());
197     }
198 
SubscriberTestLast(const CommonEventSubscribeInfo & sp)199     explicit SubscriberTestLast(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
200     {
201         handler_ = std::make_shared<EventHandler>(EventRunner::Create());
202     }
203 
~SubscriberTestLast()204     ~SubscriberTestLast()
205     {}
206 
OnReceiveEvent(const CommonEventData & data)207     virtual void OnReceiveEvent(const CommonEventData &data)
208     {
209         std::string action = data.GetWant().GetAction();
210         if (action == EVENTCASE1) {
211             ProcessSubscriberTestLastCase1(data);
212         } else if (action == EVENTCASE2) {
213             ProcessSubscriberTestLastCase2(data);
214         } else {
215         }
216     }
217 
218 private:
ProcessSubscriberTestLastCase1(CommonEventData data)219     void ProcessSubscriberTestLastCase1(CommonEventData data)
220     {
221         EVENT_LOGI("SubscriberLast: Type: %{public}s ", data.GetWant().GetType().c_str());
222         if (!isFreeze_uid2) {
223             EXPECT_EQ(CHANGECODE2, data.GetCode());
224             EXPECT_EQ(CHANGEDATA2, data.GetData());
225         } else {
226             if (!isFreeze_uid) {
227                 EXPECT_EQ(CHANGECODE, data.GetCode());
228                 EXPECT_EQ(CHANGEDATA, data.GetData());
229             } else {
230                 EXPECT_EQ(INNITCODE, data.GetCode());
231                 EXPECT_EQ(INNITDATA, data.GetData());
232             }
233         }
234         std::shared_ptr<AsyncCommonEventResult> result = GoAsyncCommonEvent();
235         std::function<void()> asyncProcessFunc =
236             std::bind(&SubscriberTestLast::AsyncProcess, this, commonEventListener3);
237         handler_->PostTask(asyncProcessFunc);
238     }
ProcessSubscriberTestLastCase2(CommonEventData data)239     void ProcessSubscriberTestLastCase2(CommonEventData data)
240     {}
241 
AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)242     void AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)
243     {
244         EXPECT_TRUE(CommonEventFreezeTest::FinishReceiver(commonEventListener, CHANGECODE2, CHANGEDATA2, false));
245     }
246 
247 private:
248     std::shared_ptr<EventHandler> handler_;
249 };
250 
251 std::shared_ptr<EventHandler> CommonEventFreezeTest::handler_ = nullptr;
252 std::shared_ptr<InnerCommonEventManager> CommonEventFreezeTest::innerCommonEventManager_ = nullptr;
253 
SetUpTestCase(void)254 void CommonEventFreezeTest::SetUpTestCase(void)
255 {
256     bundleObject = new MockBundleMgrService();
257     OHOS::DelayedSingleton<BundleManagerHelper>::GetInstance()->sptrBundleMgr_ =
258         OHOS::iface_cast<OHOS::AppExecFwk::IBundleMgr>(bundleObject);
259 }
260 
TearDownTestCase(void)261 void CommonEventFreezeTest::TearDownTestCase(void)
262 {}
263 
SetUp(void)264 void CommonEventFreezeTest::SetUp(void)
265 {
266     runner_ = EventRunner::Create(true);
267     if (!runner_) {
268         return;
269     }
270     handler_ = std::make_shared<EventHandler>(runner_);
271     innerCommonEventManager_ = std::make_shared<InnerCommonEventManager>();
272 }
273 
TearDown(void)274 void CommonEventFreezeTest::TearDown(void)
275 {}
276 
SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> & subscriber,uid_t callingUid,OHOS::sptr<OHOS::IRemoteObject> & commonEventListener)277 bool CommonEventFreezeTest::SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber,
278     uid_t callingUid, OHOS::sptr<OHOS::IRemoteObject> &commonEventListener)
279 {
280     OHOS::sptr<IEventReceive> listener = new CommonEventListener(subscriber);
281     if (!listener) {
282         return false;
283     }
284     commonEventListener = listener->AsObject();
285     struct tm recordTime = {0};
286     if (!OHOS::GetSystemCurrentTime(&recordTime)) {
287         return false;
288     }
289     pid_t callingPid = 0;
290     OHOS::Security::AccessToken::AccessTokenID tokenID = 0;
291 
292     std::string bundleName = "";
293 
294     std::function<void()> SubscribeCommonEventFunc = std::bind(&InnerCommonEventManager::SubscribeCommonEvent,
295         innerCommonEventManager_,
296         subscriber->GetSubscribeInfo(),
297         commonEventListener,
298         recordTime,
299         callingPid,
300         callingUid,
301         tokenID,
302         bundleName,
303         0,
304         0);
305     return handler_->PostTask(SubscribeCommonEventFunc);
306 }
307 
PublishCommonEvent(const CommonEventData & data,const CommonEventPublishInfo & publishInfo,const std::shared_ptr<CommonEventSubscriber> & subscriber,OHOS::sptr<OHOS::IRemoteObject> & commonEventListener)308 bool CommonEventFreezeTest::PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
309     const std::shared_ptr<CommonEventSubscriber> &subscriber, OHOS::sptr<OHOS::IRemoteObject> &commonEventListener)
310 {
311     if (commonEventListener == nullptr && publishInfo.IsOrdered()) {
312         OHOS::sptr<IEventReceive> listener = new CommonEventListener(subscriber);
313         if (!listener) {
314             return false;
315         }
316         commonEventListener = listener->AsObject();
317     } else if (!publishInfo.IsOrdered()) {
318         commonEventListener = nullptr;
319     }
320 
321     struct tm recordTime = {0};
322     if (!OHOS::GetSystemCurrentTime(&recordTime)) {
323         return false;
324     }
325     OHOS::Security::AccessToken::AccessTokenID tokenID = 0;
326     int32_t userId = UNDEFINED_USER;
327     std::string bundleName = "";
328 
329     std::function<void()> PublishCommonEventFunc = std::bind(&InnerCommonEventManager::PublishCommonEvent,
330         innerCommonEventManager_,
331         data,
332         publishInfo,
333         commonEventListener,
334         recordTime,
335         PID,
336         SYSTEM_UID,
337         tokenID,
338         userId,
339         bundleName,
340         nullptr);
341     return handler_->PostTask(PublishCommonEventFunc);
342 }
343 
FinishReceiver(const OHOS::sptr<OHOS::IRemoteObject> & proxy,const int & code,const std::string & data,const bool & abortEvent)344 bool CommonEventFreezeTest::FinishReceiver(
345     const OHOS::sptr<OHOS::IRemoteObject> &proxy, const int &code, const std::string &data, const bool &abortEvent)
346 {
347     std::function<void()> FinishReceiverFunc =
348         std::bind(&InnerCommonEventManager::FinishReceiver, innerCommonEventManager_, proxy, code, data, abortEvent);
349     return handler_->PostTask(FinishReceiverFunc);
350 }
351 
Freeze(const uid_t & uid)352 bool CommonEventFreezeTest::Freeze(const uid_t &uid)
353 {
354     std::function<void()> FreezeFunc = std::bind(&InnerCommonEventManager::Freeze, innerCommonEventManager_, uid);
355     return handler_->PostImmediateTask(FreezeFunc);
356 }
357 
Unfreeze(const uid_t & uid)358 bool CommonEventFreezeTest::Unfreeze(const uid_t &uid)
359 {
360     std::function<void()> UnfreezeFunc = std::bind(&InnerCommonEventManager::Unfreeze, innerCommonEventManager_, uid);
361     return handler_->PostImmediateTask(UnfreezeFunc);
362 }
363 
AsyncProcess()364 void CommonEventFreezeTest::AsyncProcess()
365 {
366     isFreeze_uid = false;
367     isFreeze_uid2 = false;
368     sleep(FREEZE_SLEEP);
369     EVENT_LOGI("Subscriber1 Freeze");
370     Freeze(UID);
371     EVENT_LOGI("Subscriber2 Freeze");
372     Freeze(UID2);
373     isFreeze_uid = true;
374     isFreeze_uid2 = true;
375     sleep(FREEZE_SLEEP);
376     EVENT_LOGI("Subscriber1 Unfreeze");
377     Unfreeze(UID);
378     isFreeze_uid = false;
379     sleep(FREEZE_SLEEP2);
380     EVENT_LOGI("Subscriber2 Unfreeze");
381     Unfreeze(UID2);
382     isFreeze_uid2 = false;
383     sleep(FREEZE_SLEEP);
384     mtx.unlock();
385 }
386 
387 HWTEST_F(CommonEventFreezeTest, CommonEventFreezeTest_001, TestSize.Level1)
388 {
389     /* Subscribe */
390     // make matching skills
391     MatchingSkills matchingSkills;
392     matchingSkills.AddEvent(EVENTCASE1);
393 
394     // make subscriber info
395     CommonEventSubscribeInfo subscribeInfo(matchingSkills);
396 
397     // make a subscriber object
398     std::shared_ptr<SubscriberTest> subscriberTest = std::make_shared<SubscriberTest>(subscribeInfo);
399 
400     // subscribe a common event
401     EXPECT_TRUE(SubscribeCommonEvent(subscriberTest, UID, commonEventListener));
402 
403     // make another matching skills
404     MatchingSkills matchingSkillsAnother;
405     matchingSkillsAnother.AddEvent(EVENTCASE1);
406 
407     // make another subscriber info
408     CommonEventSubscribeInfo subscribeInfo2(matchingSkillsAnother);
409 
410     // make another subscriber object
411     std::shared_ptr<SubscriberTest2> subscriberTest2 = std::make_shared<SubscriberTest2>(subscribeInfo2);
412 
413     // subscribe another event
414     EXPECT_TRUE(SubscribeCommonEvent(subscriberTest2, UID2, commonEventListener2));
415 
416     mtx.lock();
417     auto handler = std::make_shared<EventHandler>(EventRunner::Create());
418     std::function<void()> asyncProcessFunc = std::bind(&CommonEventFreezeTest::AsyncProcess, this);
419     handler->PostTask(asyncProcessFunc);
420 
421     std::shared_ptr<SubscriberTestLast> subscriber = std::make_shared<SubscriberTestLast>();
422     /* Publish */
423     int i = 0;
424     while (!mtx.try_lock()) {
425         // make a want
426         Want want;
427         want.SetAction(EVENTCASE1);
428         i++;
429         want.SetType(std::to_string(i));
430         EVENT_LOGI("PublishCommonEvent: Type: %{public}s ", std::to_string(i).c_str());
431         // make common event data
432         CommonEventData data;
433         data.SetWant(want);
434         data.SetData(INNITDATA);
435         data.SetCode(INNITCODE);
436         CommonEventPublishInfo publishInfo;
437         publishInfo.SetOrdered(true);
438 
439         usleep(100000);
440 
441         // publish order event
442         EXPECT_TRUE(PublishCommonEvent(data, publishInfo, subscriber, commonEventListener3));
443     }
444 
445     usleep(100000);
446     mtx.unlock();
447 }
448 
449 HWTEST_F(CommonEventFreezeTest, CommonEventFreezeTest_002, TestSize.Level1)
450 {
451     /* Subscribe */
452     // make matching skills
453     MatchingSkills matchingSkills;
454     matchingSkills.AddEvent(EVENTCASE2);
455 
456     // make subscriber info
457     CommonEventSubscribeInfo subscribeInfo(matchingSkills);
458 
459     // make a subscriber object
460     std::shared_ptr<SubscriberTest> subscriberTest = std::make_shared<SubscriberTest>(subscribeInfo);
461 
462     // subscribe a common event
463     EXPECT_TRUE(SubscribeCommonEvent(subscriberTest, UID, commonEventListener));
464 
465     // make another matching skills
466     MatchingSkills matchingSkillsAnother;
467     matchingSkillsAnother.AddEvent(EVENTCASE2);
468 
469     // make another subscriber info
470     CommonEventSubscribeInfo subscribeInfo2(matchingSkillsAnother);
471 
472     // make another subscriber object
473     std::shared_ptr<SubscriberTest2> subscriberTest2 = std::make_shared<SubscriberTest2>(subscribeInfo2);
474 
475     // subscribe another event
476     EXPECT_TRUE(SubscribeCommonEvent(subscriberTest2, UID2, commonEventListener2));
477 
478     mtx.lock();
479     auto handler = std::make_shared<EventHandler>(EventRunner::Create());
480     std::function<void()> asyncProcessFunc = std::bind(&CommonEventFreezeTest::AsyncProcess, this);
481     handler->PostTask(asyncProcessFunc);
482 
483     std::shared_ptr<SubscriberTestLast> subscriber = nullptr;
484     /* Publish */
485     int i = 0;
486     while (!mtx.try_lock()) {
487         // make a want
488         Want want;
489         want.SetAction(EVENTCASE2);
490         i++;
491         want.SetType(std::to_string(i));
492         EVENT_LOGI("PublishCommonEvent: Type: %{public}s ", std::to_string(i).c_str());
493         // make common event data
494         CommonEventData data;
495         data.SetWant(want);
496         data.SetData(INNITDATA);
497         data.SetCode(INNITCODE);
498         CommonEventPublishInfo publishInfo;
499         usleep(100000);
500 
501         // publish order event
502         EXPECT_TRUE(PublishCommonEvent(data, publishInfo, subscriber, commonEventListener3));
503     }
504 
505     usleep(100000);
506     mtx.unlock();
507 }
508 }  // namespace
509